#!/bin/bash
#
#	dynipsec.sh: Dynamic IP checker for IPSEC
#	Written by Scott Ragen scott@roadtechsystems.com.au
#
#	This file needs the program logtail.c to run
#
#	The purpose of this script is for small to meduim VPNs using
#	Freeswan (www.freeswan.org) with dynamic IP's but using a name 
#	server, like dyndns.org. This script watches the /var/log/secure
#	for a particular line where it appears there is an  unauthorised
#	connection, when it is actually a subnet with a changed IP address.
#	
#	Note: You may need to change the ipsec.err file as this is for our 
#	particular machine, you can verify what yours is by browsing your log.
#	
#	Version: 0.1
#	To work it put this in your cronjob, I have mine set to every 5 minutes

# CONFIGURATION SECTION

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

LOGTAIL=/usr/local/bin/logtail		#This is the program used to check the logs.

TMPDIR=/usr/local/etc/tmp		#The TMP Directory, just change it to your liking
PINGS="your.dynhost.net>yourconn"		#add these as "dynamic.host.name>ipsec-conn-name" with spaces for each connection
GREP=egrep

# The Reject Log can be either one statement, or if you have multiple errors please change this to a file.
REJECT_LOG=/usr/local/etc/ipsec.err

#	You shouldn't need to modify this configuration at all.

$LOGTAIL /var/log/secure >> $TMPDIR/checkipsec.$$

#	Time to get on with it, We will check if anything is to report, if not
#	this will exit with no complaints

    $GREP -i -f "$REJECT_LOG" $TMPDIR/checkipsec.$$ |cut -d " " -f 7 |sort |uniq  > $TMPDIR/checkipsecoutput.$$
	if [ "`cat $TMPDIR/checkipsecoutput.$$`" != "" ] ; then
		for i in $PINGS ; do
			echo "$i" | {
			IFS=':>' read host ipsecrule
			ping $host -n -c 1 |cut -d " " -f 4 |head  -n 2 |tail -n 1 |cut -d ":" -f 1 >$TMPDIR/${ipsecrule}.tmp
	 		[ `cat $TMPDIR/checkipsecoutput.$$` =  `cat $TMPDIR/${ipsecrule}.tmp` ]
		/usr/local/sbin/ipsec auto --replace $ipsecrule
					}
		done
	fi

# Clean Up
rm -f $TMPDIR/checkipsec.$$ $TMPDIR/checkipsecoutput.$$ $TMPDIR/${ipsecrule}.tmp


