Automatic restart of IPSec VPN on Teltonika RUT-950 / RUT-240

On one location where I am using a Teltonika RUT-950 / RUT-240 router, the IPSec VPN can only be connected in one direction which is outbound. Normally both ends can initiate the connection. The reason for this is that the router is connecting using 3G/4G and the provider only allows outbound traffic (i.e. “surf the Internet”). I need to buy an extra service for “fixed IP-address” in order to get their firewall removed from my service.

My IPSec VPN setup is based on hostname updated through dynamic DNS. If the router reboots, it will get a new IP-address and sometimes the router tries to connect the VPN before the dynamic DNS has been updated, causing the VPN connection to fail. The router gives up and does not try anymore to connect the VPN. A manual workaround is to remote control a computer on the LAN side of the router, login to the router, disable the VPN profile, save, enable it and save again. Now the VPN connects.

The Teltonika products are wonderful in many ways but I lack a way of restarting IPSec VPN via SMS. It is only possible to restart OpenVPN connections using SMS.

To avoid manual actions to get the VPN up in a case like this I have created a small script. It checks if an IP-address on the other side of the tunnel is ping:able, if not it restarts IPSec VPN and it normally resolves the problem.

#!/bin/ash
# chmod +x chk_vpn.sh
# crontab -e -> */6 * * * * /root/chk_vpn.sh
HOST=10.0.0.1

LANIP=/sbin/ifconfig br-lan | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
# Email settings
ROUTERNAME="MY ROUTER NAME"
EMAIL_SUBJECT="$ROUTERNAME: VPN restart"
EMAIL_BODY="$ROUTERNAME $LANIP: Ping $HOST failed, trying to restart VPN (date)"
EMAIL_FROM="senders.email@gmail.com"
EMAIL_TO="recipients.email@gmail.lt"
EMAIL_USER="senders.email@gmail.com"
EMAIL_PASS="MYEMAILACCOUNTPASSWORD"
EMAIL_SERVER="smtp.gmail.com"
EMAIL_PORT="587"
#
if ping -I $LANIP -c5 $HOST > /dev/null; then
  logger "chk_vpn.sh: $HOST responded; VPN is up!"
else
  logger "chk_vpn.sh: $HOST did not respond; trying to restart VPN"

echo -e "subject:$EMAIL_SUBJECT\nfrom:$EMAIL_FROM\n$EMAIL_BODY" | sendmail -v -H "exec openssl s_client -quiet -connect $EMAIL_SERVER:$EMAIL_PORT -tls1 -starttls smtp" -f $EMAIL_FROM -au"$EMAIL_USER" -ap"$EMAIL_PASS" $EMAIL_TO
  /usr/sbin/ipsec restart
fi

(The date in the code above should be in back aphostrophes but our WP editor removes it)

*/6 * * * * /root/chk_vpn.sh

This will check the VPN connection 10 times per hour and if necessary restart it.

Edit: 5 october 2022: Added LANIP as source

Exit mobile version