Skip to content

Instantly share code, notes, and snippets.

@dm0-
Created March 10, 2017 00:28
Show Gist options
  • Save dm0-/205bfb4a1b5144dc2e9615742b910d7e to your computer and use it in GitHub Desktop.
Save dm0-/205bfb4a1b5144dc2e9615742b910d7e to your computer and use it in GitHub Desktop.
Test IPSec between two containers
#!/bin/bash -ex
# Test IPSec with a tunnel between two containers.
# Provide /proc/net/pfkey since af_key.ko apparently isn't autoloaded.
sudo modprobe af_key
# Start and prepare the containers.
for host in left right
do
docker run \
--detach \
--env=container=docker \
--{host,}name=$host \
--privileged \
--rm \
--volume=/lib/modules \
--volume=/dev/null:/dev/tty{1..6}:ro \
fedora /usr/lib/systemd/systemd 3
# Install everything useful
docker exec $host dnf -y install \
iptables iputils libreswan procps-ng tcpdump which
docker exec $host dnf clean all
# Create keys
docker exec $host ipsec initnss --nssdir /etc/ipsec.d
docker exec $host ipsec newhostkey --output /etc/ipsec.d/$host.secrets
done
# Write the shared configuration to both containers.
left_ckaid=$(docker exec left ipsec showhostkey --list | sed -n '1s/.* //p')
left_ip=$(docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' left)
right_ckaid=$(docker exec right ipsec showhostkey --list | sed -n '1s/.* //p')
right_ip=$(docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' right)
cat << EOF |
conn containertunnel
authby=rsasig
auto=start
left=$left_ip
right=$right_ip
leftid=@left.example.com
rightid=@right.example.com
$(docker exec left ipsec showhostkey --left --ckaid $left_ckaid)
$(docker exec right ipsec showhostkey --right --ckaid $right_ckaid)
EOF
tee >/dev/null \
>(docker exec -i left tee /etc/ipsec.d/left.conf >/dev/null) \
>(docker exec -i right tee /etc/ipsec.d/right.conf >/dev/null)
# Start the daemon in both containers.
for host in left right ; do docker exec $host systemctl restart ipsec ; done
# Bring up the tunnel on one of them.
docker exec left ipsec auto --add containertunnel || :
sleep 5 # Avoid: 024 need --listen before --initiate
docker exec left ipsec auto --up containertunnel
# Spawn pings on one and watch ESP traffic on the other.
docker exec --detach right ping -c 100 $left_ip
docker exec left tcpdump -ni any esp or udp port 500 or udp port 4500
# Check for errors.
grep -F XfrmInTmplMismatch /proc/net/xfrm_stat
# Clean up.
docker stop left right
@Andrii-hotfix
Copy link

Andrii-hotfix commented Dec 18, 2018

Thanks man. This script is awesome! Nice work! You saved me!

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