LLI Wiki — My Digital Knowledge Base

MikroTik RouterOS WireGuard client with DHCP-driven route

Configure a MikroTik RouterOS device as a WireGuard client, with a DHCP client script that enables the server route while the lease is bound.

This example configures a MikroTik RouterOS device as a WireGuard client. A DHCP client script keeps a host route to the WireGuard server pointing at the WAN gateway while the lease is bound, so the tunnel can be established. The route is disabled when the lease is lost.

Create the WireGuard interface and peer

/interface wireguard add name=wireguard1 private-key="<PRIVATE_KEY>"
/interface wireguard peers
add interface=wireguard1 endpoint-address=192.0.2.10 endpoint-port=443 public-key="<PUBLIC_KEY>" allowed-address=0.0.0.0/0

Addresses and routes

/ip address
add interface=wireguard1 address=192.0.2.11
/ip route
add dst-address=192.0.2.10 comment=wgserver disabled=yes
add dst-address=0.0.0.0/0 gateway=wireguard1

The host route to the server (comment wgserver) is created disabled. The DHCP client script enables it.

DHCP client script on the WAN interface

/ip dhcp-client
add add-default-route=no interface=ether1 script=":local route [/ip route find comment=\"wgserver\"]\r\
    \n:if (\$bound=1) do={\r\
    \n  /ip route set \$route gateway=\$\"gateway-address\" disabled=no\r\
    \n} else={\r\
    \n  /ip route set \$route disabled=yes\r\
    \n}" use-peer-dns=no use-peer-ntp=no

The script runs when the DHCP lease state changes. The variable $bound is 1 when the lease is bound.

Interface list and DNS

/interface list member
add interface=wireguard1 list=WAN
/ip dns
set allow-remote-requests=yes servers=192.0.2.12,192.0.2.13

Matching WireGuard client configuration

The same tunnel, expressed as a standard WireGuard client configuration:

[Interface]
PrivateKey = <PRIVATE_KEY>
Address = 192.0.2.11/32
DNS = 192.0.2.12, 192.0.2.13

[Peer]
PublicKey = <PUBLIC_KEY>
AllowedIPs = 0.0.0.0/0
Endpoint = vpn.example.com:443

Debugging the script

The following commands print the matched route and the $bound state. They are useful to test the script logic:

:local route [/ip route find gateway="ether1-gateway"];
:put $route;
:put $bound
Mastodon LLIMastodon SocialFosstodon