Skip to content

Instantly share code, notes, and snippets.

@archit-p
Last active July 1, 2020 08:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save archit-p/ad01f715c81f128b271400653d05e09f to your computer and use it in GitHub Desktop.
Save archit-p/ad01f715c81f128b271400653d05e09f to your computer and use it in GitHub Desktop.
#!/bin/bash
if [ ${USER} != "root" ]
then
echo "${0}: rerun as root" 1>&2
exit 1
fi
function cleanup() {
# delete the existing interfaces
ip -n client link del wgc 2> /dev/null
ip -n server link del wgs 2> /dev/null
# delete the existing namespaces
ip netns del client 2> /dev/null
ip netns del router 2> /dev/null
ip netns del server 2> /dev/null
# delete existing interfaces
ip link del wg0 2> /dev/null
ip link del wg0 2> /dev/null
}
# in case cleanup required
trap cleanup EXIT
# generate keys
cpriv="$(wg genkey)"
spriv="$(wg genkey)"
cpub="$(wg pubkey <<<"$cpriv")"
spub="$(wg pubkey <<<"$spriv")"
# delete existing interfaces
ip -n client link del wgc 2> /dev/null
ip -n server link del wgs 2> /dev/null
# delete existing namespaces
ip netns del client 2> /dev/null
ip netns del router 2> /dev/null
ip netns del server 2> /dev/null
# delete existing interfaces
ip link del wg0 2> /dev/null
ip link del wg0 2> /dev/null
# create network namespaces
ip netns add client
ip netns add router
ip netns add server
# set loopback up
ip -n client link set lo up
ip -n router link set lo up
ip -n server link set lo up
# create wg interfaces and move them to namespaces
ip -n router link add dev wgc type wireguard
ip -n router link add dev wgs type wireguard
ip -n router link set wgc netns client
ip -n router link set wgs netns server
# assign IP addresses to each of the interfaces
ip -n client addr add 10.0.0.1/24 dev wgc
ip -n server addr add 10.0.0.2/24 dev wgs
# configure wireguard interfaces and add peers
ip netns exec client wg set wgc \
private-key <(echo "$cpriv") \
listen-port 12121 \
peer "$spub" \
allowed-ips 10.0.0.2 \
endpoint 127.0.0.1:13131
ip netns exec server wg set wgs \
private-key <(echo "$spriv") \
listen-port 13131 \
peer "$cpub" \
allowed-ips 10.0.0.1 \
endpoint 127.0.0.1:12121
# set the interfaces up
ip -n client link set wgc up
ip -n server link set wgs up
# verify setup using ping
ip netns exec client ping -c 100 -f 10.0.0.2
ip netns exec client ping -c 100 -f 10.0.0.1
# print out wg status
ip netns exec client wg
ip netns exec server wg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment