Skip to content

Instantly share code, notes, and snippets.

@vishvananda
Created October 22, 2013 03:16
Show Gist options
  • Save vishvananda/7094676 to your computer and use it in GitHub Desktop.
Save vishvananda/7094676 to your computer and use it in GitHub Desktop.
Script to set up an ipsec tunnel between two machines For Example: ./tunnel.sh 10.10.10.1 10.10.10.2 192.168.0.1 192.168.0.2 would set up an ipsec tunnel over 10.10.10.1 address using 192.168.0.1 as a virtual address passwordless sudo required for user on remote machine
#!/bin/bash
if [ "$4" == "" ]; then
echo "usage: $0 <local_ip> <remote_ip> <new_local_ip> <new_remote_ip>"
echo "creates an ipsec tunnel between two machines"
exit 1
fi
SRC="$1"; shift
DST="$1"; shift
LOCAL="$1"; shift
REMOTE="$1"; shift
KEY1=0x`dd if=/dev/urandom count=32 bs=1 2> /dev/null| xxd -p -c 64`
KEY2=0x`dd if=/dev/urandom count=32 bs=1 2> /dev/null| xxd -p -c 64`
ID=0x`dd if=/dev/urandom count=4 bs=1 2> /dev/null| xxd -p -c 8`
echo "spdflush; flush;" | sudo setkey -c
sudo ip xfrm state add src $SRC dst $DST proto esp spi $ID reqid $ID mode tunnel auth sha256 $KEY1 enc aes $KEY2
sudo ip xfrm state add src $DST dst $SRC proto esp spi $ID reqid $ID mode tunnel auth sha256 $KEY1 enc aes $KEY2
sudo ip xfrm policy add src $LOCAL dst $REMOTE dir out tmpl src $SRC dst $DST proto esp reqid $ID mode tunnel
sudo ip xfrm policy add src $REMOTE dst $LOCAL dir in tmpl src $DST dst $SRC proto esp reqid $ID mode tunnel
sudo ip addr add $LOCAL dev lo
sudo ip route add $REMOTE dev eth1 src $LOCAL
ssh $DST /bin/bash << EOF
echo "spdflush; flush;" | sudo setkey -c
sudo ip xfrm state add src $SRC dst $DST proto esp spi $ID reqid $ID mode tunnel auth sha256 $KEY1 enc aes $KEY2
sudo ip xfrm state add src $DST dst $SRC proto esp spi $ID reqid $ID mode tunnel auth sha256 $KEY1 enc aes $KEY2
sudo ip xfrm policy add src $REMOTE dst $LOCAL dir out tmpl src $DST dst $SRC proto esp reqid $ID mode tunnel
sudo ip xfrm policy add src $LOCAL dst $REMOTE dir in tmpl src $SRC dst $DST proto esp reqid $ID mode tunnel
sudo ip addr add $REMOTE dev lo
sudo ip route add $LOCAL dev eth1 src $REMOTE
EOF
@jlearman
Copy link

jlearman commented Jun 15, 2022

I believe that echo "spdflush; flush;" | sudo setkey -c can be replaced by ip xfrm state flush && ip xfrm policy flush, in which case there is no need to install ipsec-tools for setkey.

(Thanks for this and netlink API!)

@congzhangzh
Copy link

I believe that echo "spdflush; flush;" | sudo setkey -c can be replaced by ip xfrm state flush && ip xfrm policy flush, in which case there is no need to install ipsec-tools for setkey.

(Thanks for this and netlink API!)

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment