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
@dajul
Copy link

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
Copy link

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
Copy link

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
Copy link
Author

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
Copy link

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
Copy link

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?

@eduardogaleano
Copy link

eduardogaleano 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
Copy link

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

@eduardogaleano
Copy link

eduardogaleano 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
Copy link

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

@eduardogaleano
Copy link

eduardogaleano 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
Copy link

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
Copy link

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
Copy link

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
Copy link
Author

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
Copy link

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
Copy link
Author

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
Copy link

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
Copy link

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
Copy link
Author

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
Copy link

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
Copy link

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
Copy link
Author

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
Copy link

davidromba commented Oct 5, 2020

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

@alexforsale
Copy link

alexforsale commented Nov 27, 2020

any way to pass ipv6 address to the clients?

@deyvissonbrenoveras
Copy link

deyvissonbrenoveras commented Apr 13, 2021

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

Is trustworthy?

Source code of https://ovpnconfig.com.br is available now: https://github.com/deyvissonbrenoveras/ovpnconfig.com.br.

@sandorhoffmann
Copy link

sandorhoffmann commented Apr 26, 2021

Works, I can connect, can access internet, but can not access my server with mstsc, and the shared folders.
I tried everything above. Could someone please help?
Thanks!

@HaithamDev
Copy link

HaithamDev commented May 21, 2021

Hello
Can you do this on my own device?
I followed the steps carefully, but it didn't work for me

@shakisha
Copy link

shakisha commented Apr 30, 2022

Hello, after a router restore openvpn stopped working. What can be the issue?

@shakisha
Copy link

shakisha commented Apr 30, 2022

I have found the issue.... after updating from routers 6 to 7 the vpn stops working.
Downgrading again to 6 will make things again working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment