Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MikroTik (RouterOS) script for setup OpenVPN server and generate certificates

OpenVPN Server and certificate management on MikroTik

Contents

Setup OpenVPN server and generate certificates

# Setup OpenVPN Server and generate certs
#
# Change variables below if needed then copy the whole script
# and paste into MikroTik terminal window.
#

:global CN [/system identity get name]
:global PORT 1194

## generate a CA certificate
/certificate
add name=ca-template common-name="$CN" days-valid=3650 \
  key-usage=crl-sign,key-cert-sign
sign ca-template ca-crl-host=127.0.0.1 name="$CN"
:delay 10

## generate a server certificate
/certificate
add name=server-template common-name="server@$CN" days-valid=3650 \
  key-usage=digital-signature,key-encipherment,tls-server
sign server-template ca="$CN" name="server@$CN"
:delay 10

## create a client template
/certificate
add name=client-template common-name="client" days-valid=3650 \
  key-usage=tls-client

## create IP pool
/ip pool
add name=VPN-POOL ranges=192.168.252.128-192.168.252.224

## add VPN profile
/ppp profile
add dns-server=192.168.252.1 local-address=192.168.252.1 name=VPN-PROFILE \
  remote-address=VPN-POOL use-encryption=yes

## setup OpenVPN server
/interface ovpn-server server
set auth=sha1 certificate="server@$CN" cipher=aes128,aes192,aes256 \
  default-profile=VPN-PROFILE mode=ip netmask=24 port="$PORT" \
  enabled=yes require-client-certificate=yes

## add a firewall rule
/ip firewall filter
add chain=input action=accept dst-port="$PORT" protocol=tcp \
  comment="Allow OpenVPN"
add chain=input action=accept dst-port=53 protocol=udp \
  src-address=192.168.252.0/24 \
  comment="Accept DNS requests from VPN clients"
move [find comment="Allow OpenVPN"] 0
move [find comment="Accept DNS requests from VPN clients"] 1

## Setup completed. Do not forget to create a user.

NOTE: To allow clients to surf the Internet, make sure that there are permissive rules, such as:

/ip firewall filter
add chain=forward action=accept src-address=192.168.252.0/24 \
  out-interface-list=WAN place-before=0
add chain=forward action=accept in-interface-list=WAN \
  dst-address=192.168.252.0/24 place-before=1
/ip firewall nat
add chain=srcnat src-address=192.168.252.0/24 out-interface-list=WAN \
  action=masquerade

Add a new user

# Add a new user and generate/export certs
#
# Change variables below if needed then copy the whole script
# and paste into MikroTik terminal window.
#

:global CN [/system identity get name]
:global USERNAME "user"
:global PASSWORD "password"

## add a user
/ppp secret
add name=$USERNAME password=$PASSWORD profile=VPN-PROFILE service=ovpn

## generate a client certificate
/certificate
add name=client-template-to-issue copy-from=client-template \
  common-name="$USERNAME@$CN"
sign client-template-to-issue ca="$CN" name="$USERNAME@$CN"
:delay 10

## export the CA, client certificate, and private key
/certificate
export-certificate "$CN" export-passphrase=""
export-certificate "$USERNAME@$CN" export-passphrase="$PASSWORD"

## Done. You will find the created certificates in Files.

Setup OpenVPN client

  1. Copy the exported certificates from the MikroTik

    sftp admin@MikroTik_IP:cert_export_\*

    Also, you can download the certificates from the web interface or Winbox. Open Winbox/WebFig → Files for this.

  2. Create user.auth file

    The file auth.auth holds your username/password combination. On the first line must be the username and on the second line your password.

    user
    password
    
  3. Create OpenVPN config that named like USERNAME.ovpn:

    client
    dev tun
    proto tcp-client
    remote MikroTik_IP 1194
    nobind
    persist-key
    persist-tun
    cipher AES-128-CBC
    auth SHA1
    pull
    verb 2
    mute 3
    
    # Create a file 'user.auth' with a username and a password
    #
    # cat << EOF > user.auth
    # user
    # password
    # EOF
    auth-user-pass user.auth
    
    # Copy the certificates from MikroTik and change
    # the filenames below if needed
    ca cert_export_MikroTik.crt
    cert cert_export_user@MikroTik.crt
    key cert_export_user@MikroTik.key
    
    # Uncomment the following line if Internet access is needed
    #redirect-gateway def1
    
    # Add routes to networks behind MikroTik
    #route 192.168.88.0 255.255.255.0
  4. Try to connect

    sudo openvpn USERNAME.ovpn
    

Decrypt private key to avoid password asking (optional)

openssl rsa -passin pass:password -in cert_export_user@MikroTik.key -out cert_export_user@MikroTik.key

Delete a user and revoke his certificate

# Delete a user and revoke his certificate
#
# Change variables below and paste the script
# into MikroTik terminal window.
#

:global CN [/system identity get name]
:global USERNAME "user"

## delete a user
/ppp secret
remove [find name=$USERNAME profile=VPN-PROFILE]

## revoke a client certificate
/certificate
issued-revoke [find name="$USERNAME@$CN"]

## Done.

Revert OpenVPN server configuration on MikroTik

## Revert OpenVPN configuration

/interface ovpn-server server
set enabled=no default-profile=default port=1194

/ip pool
remove [find name=VPN-POOL]

/ppp secret
remove [find profile=VPN-PROFILE]

/ppp profile
remove [find name=VPN-PROFILE]

/ip firewall filter
remove [find comment="Allow OpenVPN"]
remove [find comment="Accept DNS requests from VPN clients"]

/certificate
## delete the certificates manually
@bryanm92s

This comment has been minimized.

Copy link

@bryanm92s bryanm92s commented Aug 26, 2016

WARNING: Bad encapsulated packet length from peer (21331), which must be > 0 and <= 1562 -- please ensure that --tun-mtu or --link-mtu is equal on both peers -- this condition could also indicate a possible active attack on the TCP link --

Help me.
Thanks.

@christiannageby

This comment has been minimized.

Copy link

@christiannageby christiannageby commented Jan 31, 2018

This doesn't work. And when i tried to run the Resetscript the ruoter disabled dhcp

@SmartFinn

This comment has been minimized.

Copy link
Owner Author

@SmartFinn SmartFinn commented Feb 5, 2018

@christiannageby I tried this script on RouterOS 6.41.1 works as expected.

@SmartFinn

This comment has been minimized.

Copy link
Owner Author

@SmartFinn SmartFinn commented Feb 5, 2018

@christiannageby oh, I see an error in the revert script. Fixed now. Thanks for the report.

@malikshi

This comment has been minimized.

Copy link

@malikshi malikshi commented Feb 6, 2018

can you help me?
why is it error?
Tue Feb 06 18:25:36 2018 TAP-WIN32 device [Ethernet 6] opened: \.\Global{E5A23A94-1200-41D8-9971-AE595A85C6F6}.tap
Tue Feb 06 18:25:36 2018 Set TAP-Windows TUN subnet mode network/local/netmask = 192.168.252.0/192.168.252.254/255.255.255.0 [SUCCEEDED]
Tue Feb 06 18:25:36 2018 ERROR: There is a clash between the --ifconfig local address and the internal DHCP server address -- both are set to 192.168.252.254 -- please use the --ip-win32 dynamic option to choose a different free address from the --ifconfig subnet for the internal DHCP server
Tue Feb 06 18:25:36 2018 Exiting due to fatal error

@SmartFinn

This comment has been minimized.

Copy link
Owner Author

@SmartFinn SmartFinn commented Feb 9, 2018

@malikshi I was faced with this problem too. I don't know why but Windows DHCP client doesn't like IP address that ended on .254. To fix that change the VPN-POOL using the following command:

/ip pool
set VPN-POOL ranges=192.168.252.2-192.168.252.224
@ctrlaltca

This comment has been minimized.

Copy link

@ctrlaltca ctrlaltca commented Apr 4, 2018

A couple notes that could help others:

  • in the IP-> Firewall section i had to move the "Allow OpenVPN" rule up in position 3, just before the builtin "drop input" rule;
  • in the PPP-> OVPN Server section i had to change "Mode" from "ethernet" to "ip".
@flaviostutz

This comment has been minimized.

Copy link

@flaviostutz flaviostutz commented May 20, 2018

Just applied the entire script on a remote RB2011 and it worked flawlessly!

@UAnton

This comment has been minimized.

Copy link

@UAnton UAnton commented Jun 8, 2018

deleted

@idenkov

This comment has been minimized.

Copy link

@idenkov idenkov commented Jul 28, 2018

I tried your scripts and they to work like a charm, but I have a problem
Clients are connecting, but they do not get the router IP, they keep the ones they have.
I think it should have to do with routes, but I am not sure what should I look for.

@kerkybon

This comment has been minimized.

Copy link

@kerkybon kerkybon commented Aug 4, 2018

Revision :)

/ppp secrets
remove [find profile=VPN-PROFILE]

/ppp secret
remove [find profile=VPN-PROFILE]

@SmartFinn

This comment has been minimized.

Copy link
Owner Author

@SmartFinn SmartFinn commented Aug 5, 2018

@kerkybon thanks for pointing this out. It fixed now.

@athbot

This comment has been minimized.

Copy link

@athbot athbot commented Sep 4, 2018

Hello , i've been testing your script but i had many errors on implementing it on my mikrotik, but before i become more specific about my errors i would like to ask about your base configuration before applying the script . Is it the default out of the box configuration?Do you change anything specific before applying the script? If you do change this what are those and and could you link your base config if it's different from the default out of the box config?I'll keep testing and wait for answer thanks in advance!!!

@SmartFinn

This comment has been minimized.

Copy link
Owner Author

@SmartFinn SmartFinn commented Sep 4, 2018

@athbot this script works perfectly with the default configuration and with no configuration. You should understand that this script can conflict with your setup because a lot of names and IPs are hardcoded. It is necessary to check whether there are conflicts before applying this config.

In addition, it is possible that there are no conflicts, but sign command takes longer time than delay calculated by waitSec, as a result, you will get errors when executing subsequent commands. In this case, try to increase the delay by change the line :global waitSec do={:return ($KEYSIZE * 20 / 1024)}

@athbot

This comment has been minimized.

Copy link

@athbot athbot commented Sep 4, 2018

@SmartFinn since your response i have been able to successfully apply the configuration without errors based on what you said me by using the default out of the box config and i have managed to connect to it , but i am unable to access anything behind mikrotik ,only 192.168.88.1 and 192.168.252.1, but nothing else. I tried adding "redirect-gateway def1" and "route 192.168.88.0 255.255.255.0 192.168.252.2" to the .ovpn file but had no luck again. Is there anything i can change in order to test it more?

@SmartFinn

This comment has been minimized.

Copy link
Owner Author

@SmartFinn SmartFinn commented Sep 5, 2018

@athbot see that fork bondarenkod/ovpn-server-with-certs.md. I didn't try to setup VPN with internet access yet.

@purna89

This comment has been minimized.

Copy link

@purna89 purna89 commented Sep 16, 2018

it's working, thankyou so much :)

@bricktopm

This comment has been minimized.

Copy link

@bricktopm bricktopm commented Sep 26, 2018

Hello, its very good, and working fine on WIndows PC's.
But can't use on IOS12 openvpn client.
Help me please, how can I generate crt and keyfiles for IOS devices?

@piolomartin

This comment has been minimized.

Copy link

@piolomartin piolomartin commented Dec 6, 2018

Hi SmartFINN,

Thank you, it's working

@dajul

This comment has been minimized.

Copy link

@dajul dajul commented Dec 21, 2018

It's working fine with RouterOS 6.43.7. I've added two lines to Client Config to route all traffict through VPN and to use my DNS server, also uncommented "route" line to access my LAN:

#Add routes to networks behind MikroTik
route 192.168.88.0 255.255.255.0
redirect-gateway def1
dhcp-option DNS 192.168.88.8

@Nordlicht123

This comment has been minimized.

Copy link

@Nordlicht123 Nordlicht123 commented Apr 1, 2019

Hi,
I use the script to generate Setup OpenVPN server. Because I use port 443 instead 1194.
The default port in the OpenVPN server setting is 1194, and the port setting isn't change by the script, only for the firewall setting.

It's would be better to change the port setting also for the OpenVPN server:
:global PORT "443"

setup OpenVPN server

/interface ovpn-server server
set auth=sha1 certificate="server@$CN" cipher=aes128,aes192,aes256
default-profile=VPN-PROFILE enabled=yes port="$PORT" require-client-certificate=yes

add a firewall rule

/ip firewall filter
add chain=input dst-port="$PORT" protocol=tcp comment="Allow OpenVPN"

@lfdmn

This comment has been minimized.

Copy link

@lfdmn lfdmn commented Apr 7, 2019

Hi,
I tried this on RouterOS v6.42.7, default config.

If I try to connect within the router LAN, the connection goes through, no problem. But if I try to connect to the routers public IP, I get "WARNING: bad encapsulated packet length from pear... which must be 0 > and <= 1626 ...".

The OpenVPN firewall rule is set in second position, right after the passthrough / forward rule. I do see 0B and 0 Packets on that Allow OpenVPN rule.

What am I missing?

@SmartFinn

This comment has been minimized.

Copy link
Owner Author

@SmartFinn SmartFinn commented Apr 8, 2019

@lfdmn that is not an error, I even didn't try to fix it. Try to add tun-mtu 1400 to client's ovpn file.

@aminbadiee

This comment has been minimized.

Copy link

@aminbadiee aminbadiee commented Apr 26, 2019

Hi,
Mikrotik has changed the structure of /ipsec and some new tabs are added in its new firmware (6.43.14) , do you have a compatible code with this new firmware ?
Thanks...

@yotuze

This comment has been minimized.

Copy link

@yotuze yotuze commented Jul 27, 2019

Great job with the script, only problem I have is that I can't connect to the devices in my local lan. I managed to make internet work by allowing remote requests in IP -> DNS but I can't go to my samba shares, etc. Can You help?

@EduardG94

This comment has been minimized.

Copy link

@EduardG94 EduardG94 commented Dec 13, 2019

Great job with the script, only problem I have is that I can't connect to the devices in my local lan. I managed to make internet work by allowing remote requests in IP -> DNS but I can't go to my samba shares, etc. Can You help?

/ip firewall nat
add action=accept chain=srcnat dst-address=network-vpn/xx src-address=
network-lan/xx
add action=accept chain=srcnat dst-address=network-lan/xx src-address=
network-vpn/xx

@deyvissonbrenoveras

This comment has been minimized.

Copy link

@deyvissonbrenoveras deyvissonbrenoveras commented Jan 7, 2020

Hey guys, I'm using this website to generate my .ovpn files with a mikrotik server: https://ovpnconfig.com.br

@EduardG94

This comment has been minimized.

Copy link

@EduardG94 EduardG94 commented Jan 8, 2020

Hey guys, I'm using this website to generate my .ovpn files with a mikrotik server: https://ovpnconfig.com.br

Is trustworthy?

@deyvissonbrenoveras

This comment has been minimized.

Copy link

@deyvissonbrenoveras deyvissonbrenoveras commented Jan 8, 2020

Hey guys, I'm using this website to generate my .ovpn files with a mikrotik server: https://ovpnconfig.com.br

Is trustworthy?

Yes, I developed it. The website doesn't require that you send your credentials, just generate the .ovpn file. You need do create the auth-user-pass manually and edit the line "auth-user-pass" with your credentials file name.
ex: auth-user-pass credentials.txt.

The real motivation to develop this site was the time that I lost editing the .ovpn files, decrypting the key..

Any doubts or suggestions you can contact me: deyvissonbrenoveras@gmail.com

@EduardG94

This comment has been minimized.

Copy link

@EduardG94 EduardG94 commented Jan 9, 2020

Hey guys, I'm using this website to generate my .ovpn files with a mikrotik server: https://ovpnconfig.com.br

Is trustworthy?

Yes, I developed it. The website doesn't require that you send your credentials, just generate the .ovpn file. You need do create the auth-user-pass manually and edit the line "auth-user-pass" with your credentials file name.
ex: auth-user-pass credentials.txt.

The real motivation to develop this site was the time that I lost editing the .ovpn files, decrypting the key..

Any doubts or suggestions you can contact me: deyvissonbrenoveras@gmail.com

Excellent thanks.

@pepitolechuga

This comment has been minimized.

Copy link

@pepitolechuga pepitolechuga commented Jan 14, 2020

Hey, guys, the next thing is pretty ugly but it works. Maybe some of you can use it.

{
# Variables.
    :local CN [/system identity get name]
    :local USERNAME "USER"
    :local PASSWORD "PASS"
    :local PORT "1194"
    :local IPMIKROTIK "1.2.3.4"
    :local Contenido ("client" . "\n" . "dev tun" . "\n" . "proto tcp-client" . "\n" . "remote " . "$IPMIKROTIK" . " $PORT" . "\n" . "nobind" . "\n" . "persist-key" . "\n" . "persist-tun" . "\n" . "cipher AES-256-CBC" . "\n" . "auth SHA1" . "\n" . "pull" . "\n" . "verb 2" . "\n" . "mute 3" . "\n" . "\n" . "auth-user-pass user.txt" . "\n" . "\n" . "ca cert_export_" . "$CN" . ".crt" . "\n" . "cert " . "cert_export_" . "$USERNAME@" . "$CN" . ".crt" . "\n" . "key " . "cert_export_" . "$USERNAME@" . "$CN" . ".key" . "\n" . "\n" . "# Uncomment the following line if Internet #access is needed" . "\n" . "#redirect-gateway def1" . "\n"  . "\n" . "# Add routes to #networks behind MikroTik" . "\n" . "#route 192.168.88.0 255.255.255.0" . "\n")
    :delay 2
# Create file.
    /file print file=("user" . ".txt") where name=""
# Wait for the file to be created.
    :delay 2
# Set file's content.
    /file set ("user" . ".txt") contents=("$USERNAME" . "\n" . "$PASSWORD")

# Create file.
    /file print file=("$USERNAME" . "@$CN" . ".txt") where name=""
# Wait for the file to be created.
    :delay 2
# Set file's content.
    /file set ("$USERNAME" . "@$CN" . ".txt") contents=($Contenido)
# It is necessary to delete the extension ".txt" to "ovpn" after downloading
    :delay 2
}

@skryvets

This comment has been minimized.

Copy link

@skryvets skryvets commented Jan 14, 2020

Hi, folks,
I was able to setup VPN and able to connect and access all machines in my local network, however how hard didn't I try (adding, modifying, removing, disabling/enabling various firewall rules) I still wasn't able to get internet working inside the network.

When I do ping it timeouts:

ping: google.com: Temporary failure in name resolution

Any suggestions?
Appreciate any help.

Here's my dns config

Here's my firewall config

Ok, problem solved. I didn't need to add any additional rules such as op mentioned in "NOTE: To allow clients to surf the Internet..." section. All I did is configured my "OpenVPN" network in "IP -> DHCP Server -> Networks" section (Adding gateway solved the problem).

@joacimmelin

This comment has been minimized.

Copy link

@joacimmelin joacimmelin commented Jan 23, 2020

Everything seems to be working fine except I can't get the key-file to export. I'm running 6.46.1. Anyone got an idea on how to fix that?

@SmartFinn

This comment has been minimized.

Copy link
Owner Author

@SmartFinn SmartFinn commented Jan 23, 2020

@joacimmelin you have to set a non-empty passphrase to export-passphrase=PASSWORD option to export the key-file.

@joacimmelin

This comment has been minimized.

Copy link

@joacimmelin joacimmelin commented Jan 23, 2020

@SmartFinn ok, the script says:

export the CA, client certificate, and private key

/certificate
export-certificate "$CN" export-passphrase=""
export-certificate "$USERNAME@$CN" export-passphrase="$PASSWORD"

I then assume it's the last row in the above example that exports the key?

Thanks for any help.

@SmartFinn

This comment has been minimized.

Copy link
Owner Author

@SmartFinn SmartFinn commented Jan 23, 2020

@joacimmelin yes, by default the script exports the key with passphrase "password", but if you set (or didn't set at all) :global PASSWORD "" variable to empty then key-file isn't exported. I didn't face another case of that issue.

@jgaye-luko

This comment has been minimized.

Copy link

@jgaye-luko jgaye-luko commented Mar 16, 2020

This works great, thanks a lot.
Here is a bash script that downloads the certificates, and generate the ovpn config files that you descire at https://gist.github.com/SmartFinn/8324a55a2020c56b267b#setup-openvpn-client , section 2 and 3

export OVPN_USERNAME=$1
export OVPN_PASSWORD=$2
export CN=$3

sftp -P 22 <Mikrokit_admin>@<your_Mikrokit_IP>:cert_export_$CN.crt
sftp -P 22 <Mikrokit_admin>@<your_Mikrokit_IP>:cert_export_$OVPN_USERNAME\* 

cat >> $OVPN_USERNAME.auth << EOF
$OVPN_USERNAME
$OVPN_PASSWORD
EOF

cat >> $OVPN_USERNAME.ovpn << EOF
client
dev tun
proto tcp-client
remote <VPN IP>1194
nobind
persist-key
persist-tun
cipher AES-256-CBC
auth SHA1
pull
verb 2
mute 3

auth-user-pass $OVPN_USERNAME.auth

ca cert_export_$CN.crt
cert cert_export_$OVPN_USERNAME@$CN.crt
key cert_export_$OVPN_USERNAME@$CN.key

redirect-gateway def1
EOF

Use by doing :
sh <the_script_name> <username> <password> <CN>

Hope that helps anybody that wants to crete many users configuration.

@jerryroy1

This comment has been minimized.

Copy link

@jerryroy1 jerryroy1 commented Jun 9, 2020

So I am trying this Between Mikrotik and ASUS Router RT-ACRH17. It has a built in OVPN client capability. I imported the Certificate but I keep getting a "Could not read Auth username from stdin" . I notice you create a user.auth file and then a username.ovpn file. Can these all be in one file?

IMG_20200608_175146
IMG_20200608_175124

@SmartFinn

This comment has been minimized.

Copy link
Owner Author

@SmartFinn SmartFinn commented Jun 9, 2020

@jerryroy1

I notice you create a user.auth file and then a username.ovpn file. Can these all be in one file?

No, it cannot be. You do not need this file because fields Username/Password do the same. But, that weird to see the error when Username/Password filled. I can not help you because I never faced with ASUS routers.

@GitHubBrainstorm

This comment has been minimized.

Copy link

@GitHubBrainstorm GitHubBrainstorm commented Sep 1, 2020

For me Work!

After export certificates in OpenVPN folder, need remove passphrase with this command:
*Need install OpenSSL Utilities and use openssl.exe for remove passphrase

Command for Windows:

  1. Navigate to folder certificates
  2. Paste location to openssl.exe and run this command

C:\Users\Username\Desktop\crt>"C:\Program Files (x86)\OpenVPN\bin\openssl.exe" rsa -in cert_export_MikroTik.crt -out cert_export_openvpn@MikroTik.key

Enter global PASSWOR: password

Now work for me.

@davidromba

This comment has been minimized.

Copy link

@davidromba davidromba commented Oct 3, 2020

i dont kow why but i am able to connect to the vpn but when i go to any explorer i am not able to access the websites, but i am able to ping their corespoding ip adresses and i am also able to connect to the local network of the router. basically i am not able to resolve dns names but iam able to ping their respective ip adrresses , i am able to reach the local network of the router.
if anyone is able to help i´d appreciate it.

@SmartFinn

This comment has been minimized.

Copy link
Owner Author

@SmartFinn SmartFinn commented Oct 3, 2020

@davidromba make sure that Allow Remote Requests option in IP → DNS is enabled (/ip dns set allow-remote-requests=yes) and the servers list is not empty, or just change DNS servers for VPN clients with /ppp profile set VPN-PROFILE dns-server=8.8.8.8,8.8.4.4

@davidromba

This comment has been minimized.

Copy link

@davidromba davidromba commented Oct 5, 2020

Thanks your advice almost worked i also needed to uncomment the "redirect-gateway def1" on the ovpn file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.