Skip to content

Instantly share code, notes, and snippets.

@hg
Created May 13, 2024 18:24
Show Gist options
  • Select an option

  • Save hg/f6697f59fad8fb7600d50ba46b52e320 to your computer and use it in GitHub Desktop.

Select an option

Save hg/f6697f59fad8fb7600d50ba46b52e320 to your computer and use it in GitHub Desktop.
lightweight ui to change active mullvad server
#!/usr/bin/bash
set -euo pipefail
for exe in sudo rofi wg curl jq; do
type "$exe" &>/dev/null || {
echo >&2 "please install $exe"
exit 1
}
done
cache=${XDG_CACHE_HOME:-~/.cache}/mullvad-lean
mkdir --parents "$cache"
chmod --silent 700 "$cache"
template="$cache"/mv.conf.in
config="$cache"/mv.conf
if [[ ! -f "$template" ]]; then
echo 'creating wireguard config symlink'
sudo ln --symbolic --force \
"$config" /etc/wireguard/mv.conf
echo 'adding restart wg operation to sudoers'
sudoers=$(mktemp)
echo >"$sudoers" "$USER ALL=(ALL:ALL) NOPASSWD: /usr/bin/systemctl restart wg-quick@mv"
visudo --check --file "$sudoers"
sudo install -Dm644 --owner root --group root \
"$sudoers" "/etc/sudoers.d/zz-mullvad-$USER"
key=$(wg genkey)
cat >"$template" <<EOF
[Interface]
# Add this public key on mullvad.net: $(wg pubkey <<<"$key")
PrivateKey = $key
Address = IP_V4_AND_V6_OF_YOUR_CLIENT_PROVIDED_BY_MULLVAD
# do not modify variables
[Peer]
PublicKey = \$PUBKEY
Endpoint = \$ENDPOINT:443
AllowedIPs = 0.0.0.0/0,::0/0
EOF
chmod 600 "$template"
echo "please copy public key from $template into mullvad.net and update it with your client IP"
exit
fi
chmod 600 "$config" "$template" || true
get_servers() {
local out="$cache/servers.json"
if ! find "$out" -type f -mtime +0 2>/dev/null; then
curl --silent --show-error --output "$out.tmp" \
https://api.mullvad.net/www/relays/wireguard
mv --force "$out.tmp" "$out"
fi
cat "$out"
}
server=$(
get_servers |
jq --raw-output '.[] | select(.active == true) | "\(.hostname) | \(.country_name) | \(.city_name) | \(.network_port_speed)G | \(.ipv4_addr_in)"' |
column --table --separator '|' |
rofi -dmenu -i -p server -no-custom |
cut --delimiter ' ' --fields 1
)
[[ -z $server ]] && exit
conn=$(
get_servers |
jq --raw-output --arg hostname "$server" \
'.[] | select(.hostname == $hostname) | { ip4: .ipv4_addr_in, key: .pubkey }'
)
[[ -z $conn ]] && exit 1
env --ignore-environment \
PUBKEY="$(jq --raw-output '.key' <<<"$conn")" \
ENDPOINT="$(jq --raw-output '.ip4' <<<"$conn")" \
envsubst <"$template" >"$config"
sudo systemctl restart wg-quick@mv
notify-send "switched to server $server" || true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment