IPSec Policy Dynamic

From MikroTik Wiki
Jump to: navigation, search
Version.png

Applies to RouterOS: v6

Basic Info

This fixes IPSec policy to work with dynamic WAN IP.

What to configure

Configure the WAN interface name at the annotated line.

Schedule the script to run every 2 or 3 seconds.


This script assumes that there are no other policies defined in "/ip ipsec policy"

If there are, you will need to modify the [find] commands to only modify the needed policy.

The script

# ------------------- header -------------------
# Script by Tomas Kirnak, version 1.0.2
# If you use this script, or edit and
# re-use it, please keep the header intact.
#
# For more information and details about
# this script please visit the wiki page at
# http://wiki.mikrotik.com/wiki/IPSec_Policy_Dynamic
# ------------------- header -------------------
{
# Configure the WAN interface name here in the interface="" quotes
:local WANip [/ip address get [find interface="ether1 - CHANGE THIS"] address]

:global oWANip

:set WANip [:pick "$WANip" 0 ([:len $WANip] - 3)]

if ($WANip != $oWANip) do={
  :log warning "WAN IP changed, fixing IPSec"
  
  /ip ipsec policy
   disable [find]
  /ip ipsec peer
   disable [find]
  
  /ip ipsec policy
   set [find] tunnel=yes
  /ip ipsec policy
   set [find] src-address="$WANip/32"
  /ip ipsec policy
   set [find] sa-src-address=$WANip
  /ip ipsec policy
   set [find] tunnel=no
  
  /ip ipsec peer
   enable [find]
  /ip ipsec policy
   enable [find]
  
  :set oWANip $WANip
}
}