You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
79 lines
2.1 KiB
79 lines
2.1 KiB
#!/bin/bash
|
|
set -euo pipefail
|
|
|
|
# hardcoded constants
|
|
wg_domain="wg.alemor.org"
|
|
wg_dev="wg0"
|
|
|
|
# functions
|
|
help() {
|
|
case $1 in
|
|
main) echo "Usage: $(basename $0) [COMMAND] [DESTINATION]"
|
|
echo "Automatically configure WireGuard peer connection to a given destination that you are able to SSH to and are a sudoer on."
|
|
echo "Commands:"
|
|
echo -e "\tadd"
|
|
;;
|
|
add) echo "Usage: $(basename $0) add [DESTINATION]"
|
|
echo "Add a peer connection."
|
|
;;
|
|
esac
|
|
exit 1
|
|
}
|
|
|
|
|
|
cmd_add() {
|
|
# add peer on host
|
|
sudo wg set $wg_dev peer "${dest_key}" endpoint $dest_fqdn:$dest_port allowed-ips $dest_wgip/32
|
|
line="$dest_wgip\t$dest_name.$wg_domain"
|
|
regex="^[0-9.]+\s+$dest_name.$wg_domain\$"
|
|
sed -E -e "/$regex/{s/.*/$line/;:a;n;ba;q}" -e "\$a $line" /etc/hosts | sudo tee /etc/hosts >/dev/null
|
|
|
|
# add peer on dest
|
|
sshp sudo wg set $wg_dev peer "'${host_key}'" endpoint $host_fqdn:$host_port allowed-ips $host_wgip/32
|
|
line="$host_wgip\t$host_name.$wg_domain"
|
|
regex="^[0-9.]+\s+$host_name.$wg_domain"
|
|
sshp "sed -E -e '/$regex/{s/.*/$line/;:a;n;ba;q}' -e '\$a $line' /etc/hosts | sudo tee /etc/hosts >/dev/null"
|
|
}
|
|
|
|
# Main
|
|
|
|
# Check args
|
|
if [[ $# -lt 1 ]]; then
|
|
help main
|
|
fi
|
|
case $1 in
|
|
add)
|
|
if [[ $# -lt 2 ]]; then
|
|
help add
|
|
fi
|
|
cmd=add
|
|
dest=$2
|
|
;;
|
|
*)
|
|
help main
|
|
;;
|
|
esac
|
|
|
|
# ask for local sudo password
|
|
sudo -p '[sudo] password for %u@%h: ' true
|
|
# connect to remote
|
|
# script expects ssh-persist to be either in the same directory as script itself, or in the path
|
|
. ssh-persist.sh "$dest" || . $(dirname $0)/ssh-persist.sh "$dest"
|
|
|
|
# gather host info
|
|
host_name=$(hostname)
|
|
host_fqdn=$(hostname --fqdn)
|
|
host_wgip=$(ip -4 addr show $wg_dev | grep -oP '(?<=inet\s)\d+(\.\d+){3}')
|
|
host_port=$(sudo wg show $wg_dev listen-port)
|
|
host_key=$(sudo wg show $wg_dev public-key)
|
|
|
|
# gather dest info
|
|
dest_name=$(sshp hostname)
|
|
dest_fqdn=$(sshp hostname --fqdn)
|
|
dest_wgip="$(sshp ip -4 addr show $wg_dev | grep -oP '(?<=inet\s)\d+(\.\d+){3}')"
|
|
dest_port=$(sshp sudo wg show $wg_dev listen-port)
|
|
dest_key=$(sshp sudo wg show $wg_dev public-key)
|
|
|
|
case $cmd in
|
|
add) cmd_add;;
|
|
esac
|
|
|