Skip to main content

vpn-keepalive.sh

#!/bin/bash
# keepalive for ipsec
# 2007 Oliver Voelker <wiki(at)magenbrot.net>
 
failmax=3 # beim dritten Fehler restarten
keepalive=30 # alle $keepalive Sekunden testen
maxage=120 # maximales Alter der Checkdatei in Sekunden
nextrestart=3600 # nach einem neustart erst wieder in X sekunden probieren
 
CHECKFILE="/tmp/keep-alive" # Dieses File muss minuetlich durch die VPN-Gegenseite erzeugt werden, z.B. durch einen Cronjob: "ssh user@bla.de -C touch /tmp/keep-alive"
TMPFILE="/tmp/vpntest-$$"
ADMIN="admin@bla.de" # wird bei Stoerungen informiert
TUNNEL="ipsec-tunnel" # Tunnelname aus ipsec.conf
 
# do not edit anything beyond this point!
 
fail=0
 
MESSAGE=""
 
function tunnelrestart () {
  MESSAGE="Maxfail ($failmax) reached: restarting tunnel $TUNNEL (age of checkfile $DIFF seconds)"
  logger -p local2.info -t TUNNEL "$MESSAGE"
  /usr/sbin/ipsec auto --down $TUNNEL
  sleep 5
  /usr/sbin/ipsec auto --up $TUNNEL
  echo "tunnel $TUNNEL on `hostname -f` was restarted, because checkfile $CHECKFILE was too old. Please check!" | mail -s "VPN-Problem on `hostname -f`!" $ADMIN
  touch $TMPFILE
  sleep 120
}
 
while (true); do
  CHECK=`stat -c"%Y" $CHECKFILE`
  NOW=`date +%s`
  DIFF=`echo $NOW - $CHECK | bc`
 
  if [ "$DIFF" -lt "$maxage" ]; then
    MESSAGE="Tunnel $TUNNEL OK (age of checkfile $DIFF seconds)"
    logger -p local2.info -t TUNNEL "$MESSAGE"
    fail=0
  else
    fail=`echo $fail+1|bc`
    MESSAGE="Tunnel $TUNNEL DOWN: $fail (age of checkfile $DIFF seconds with maxage of $maxage)"
    logger -p local2.info -t TUNNEL "$MESSAGE"
  fi
 
  if [ "$fail" -ge "$failmax" ] ; then
 
    if [ -f $TMPFILE ]; then
      ATMP=`stat -c"%Y" $TMPFILE`
      SSLR=`echo $NOW - $ATMP | bc` # seconds since last restart
      if [ "$SSLR" -ge "$nextrestart" ]; then
        rm -f $TMPFILE
        tunnelrestart
        fail=0
      else
        MESSAGE="Maxfail ($failmax) reached, but tunnel was already restarted $SSLR seconds ago. Only one restart per $nextrestart seconds."
        logger -p local2.info -t TUNNEL "$MESSAGE"
        echo "tunnel $TUNNEL should have been restarted, but this already happened $SSLR seconds ago. Please check!" | mail -s "BIG VPN-Problem on vpn.meinserver.de!" $ADMIN
      fi
    else
      tunnelrestart
    fi
  fi
  sleep $keepalive
done