#! /bin/bash
# This script creates a new vti interface and adds routes based on data passed from Strongswan.
# To use, add to "conn..." section of ipsec config file:
# leftupdown=/path/to/ipsec-leftupdown.sh
set -o nounset
set -o errexit
VTI_IF="vti-${PLUTO_CONNECTION:0:10}"
VTI_IF="${VTI_IF/./}"
# Create run directory
RUNDIR=/var/run/acreto ; mkdir -p $RUNDIR
# Read configuration from config file
networks_right=''
if [ -f /etc/ipsec.d/$PLUTO_CONNECTION.route ] ; then
networks_right=`cat /etc/ipsec.d/$PLUTO_CONNECTION.route`
else
echo WARN: Routing info file /etc/ipsec.d/$PLUTO_CONNECTION.route not found
fi
# Determine gateway to use to reach ${PLUTO_PEER}
function detectGateway {
# Find a route with a 'via' address
local gateway=""
# Start with default route
# Note that we exclude gateways that are on vti- devices
[ -z "$gateway" ] && gateway=`ip route show default | grep -v 'dev vti-' | egrep -o1 'via (([0-9]{1,3}.){3}[0-9]{1,3})' | head -1 |cut -d' ' -f2 `
# Try 'ip route get'
# It's not first rule because it doesn't survive link change
[ -z "$gateway" ] && gateway=`ip route get $1 | grep -v 'dev vti-' | egrep -o 'via (([0-9]{1,3}.){3}[0-9]{1,3})' |cut -d' ' -f2`
# Fallback to a previously detected gateway
[ -z "$gateway" ] && gateway=`cat $RUNDIR/local-gateway.conf` || true
# Save detected gateway
[ ! -z "$gateway" ] && echo $gateway > $RUNDIR/local-gateway.conf
echo $gateway
}
set -x
gateway=`detectGateway ${PLUTO_PEER}`
case "${PLUTO_VERB}" in
up-client)
if ip tunnel show "${VTI_IF}" ; then
op=change
else
op=add
fi
ip tunnel $op "${VTI_IF}" local "${PLUTO_ME}" remote "${PLUTO_PEER}" mode vti \
okey "${PLUTO_MARK_OUT%%/*}" ikey "${PLUTO_MARK_IN%%/*}"
ip link set "${VTI_IF}" up
sysctl -w "net.ipv4.conf.${VTI_IF}.disable_policy=1"
iptables -t nat -F
iptables -t mangle -F
iptables -F
iptables -X
for net in $networks_right ; do
if [ $net == '0.0.0.0/0' ] ; then
# Ensure that PEER is always accessible if we set up default route (and ignore errors)
[ ! -z "$gateway" ] && ip route replace ${PLUTO_PEER} via $gateway || true
# Ensure we don't have any other default gateway defined
while ip route show default|grep -q default ; do
ip route del default
done
fi
ip route add $net dev ${VTI_IF}
done
;;
down-client)
# Ensure that PEER is always accessible if we set up default route (and ignore errors)
[ ! -z "$gateway" ] && ip route replace ${PLUTO_PEER} via $gateway || true
# Nothing else to do here:
# 1. We don't delete the tunnel interface and routing setup because it causes connection reset, as down-client is called whenever a connectionis renegotiated, and it makes apps (like mtr) break.
# 2. We also don't remove the specific route to our gateway to be able to re-establish the connection.
# 3. We also don't recover the default gateway, as we want to block all traffic if the tunnel is down.
;;
esac