nixos-config/modules/mullvad/mullvad.sh

61 lines
1.5 KiB
Bash
Executable file

#!/usr/bin/env bash
# This reads wg-quick compatible configuration files from
# /etc/wireguard/mullvad-LOCATION.conf
#
# Since they are autogenerated by nix and therefore world-readable, they do not
# include secrets like the private key and client address. Instead, they are
# manually added after wg-quick set up the tunnel by retrieving them with
# pass(1) from web/mullvad.net/wireguard.
#
# Format of pass entry:
# PrivateKey: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=
# Address4: 10.0.0.1/32
# Address6: fd00::1/128
set -euo pipefail
if (( $# < 1 )); then
echo "USAGE: $0 LOCATION|off" >&2
exit 1
fi
INTERFACE="mullvad-$1"
cmd() {
echo "[#] $*" >&2
sudo "$@"
}
for interface in /sys/class/net/*; do
interface="${interface#/sys/class/net/}"
[[ $interface =~ ^mullvad-(v6-)?[a-z]{2}[0-9]*$ ]] && cmd wg-quick down "$interface"
done
if [ "$1" != "off" ]; then
# Make sure gpg-agent is unlocked so the period where the interface exists but
# no private key is set is minised.
pass web/mullvad.net/wireguard >/dev/null
cmd wg-quick up "$INTERFACE"
pass web/mullvad.net/wireguard | while read -r line; do
key="${line%%: *}"
value="${line#*: }"
case "$key" in
PrivateKey)
cmd wg set "$INTERFACE" private-key /dev/stdin <<< "$value"
continue
;;
Address4)
cmd ip -4 address add "$value" dev "$INTERFACE"
continue
;;
Address6)
cmd ip -6 address add "$value" dev "$INTERFACE"
continue
;;
*)
echo "Invalid key '$key'"
exit 1
esac
done
fi