117 lines
2.3 KiB
Bash
Executable file
117 lines
2.3 KiB
Bash
Executable file
#!/bin/bash
|
|
|
|
# Usage : parseConf $fileContent $propertyName
|
|
# Retrieves the value of propertyName from fileContent
|
|
# And echoes it back
|
|
function parseConf() {
|
|
result=$(echo "$1" | grep $2 | cut -f2 -d'=')
|
|
echo $result
|
|
}
|
|
|
|
|
|
if [ $EUID -ne 0 ]; then
|
|
echo "This script can only be run as root"
|
|
exit -1
|
|
fi
|
|
|
|
if [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
|
|
cat <<EOF
|
|
This script adds a peer to a Wireguard configuration and
|
|
outputs the corresponding configuration file.
|
|
|
|
Usage :
|
|
$0 [ PATH_TO_WIREGUARD_CONFIGURATIONS ]
|
|
|
|
EOF
|
|
|
|
exit 0
|
|
fi
|
|
|
|
configurationsPath="/etc/wireguard"
|
|
if [ -d "$1" ]; then
|
|
configurationsPath="$1"
|
|
fi
|
|
|
|
# Retrieve every configuration file using a glob.
|
|
# Don't add anything to the array if nothing is present
|
|
shopt -s nullglob
|
|
wireguardConfigs=(/etc/wireguard/*)
|
|
shopt -u nullglob
|
|
|
|
configCount=${#wireguardConfigs[@]}
|
|
|
|
if [ $configCount -eq 0 ]; then
|
|
echo "There are no wireguard configs availabe !"
|
|
exit -1
|
|
fi
|
|
|
|
count=0
|
|
echo "Available configurations :"
|
|
for configuration in ${wireguardConfigs[@]}; do
|
|
echo -e "\t"$count. "$configuration"
|
|
count=$(($count+1))
|
|
done
|
|
|
|
invalid=true
|
|
while $invalid; do
|
|
echo -n "Please choose a configuration: "
|
|
read choice
|
|
echo ""
|
|
|
|
case $choice in
|
|
[0-$(($configCount-1))])
|
|
invalid=false
|
|
;;
|
|
'')
|
|
echo "Exiting"
|
|
exit 0
|
|
;;
|
|
*)
|
|
echo "Invalid argument, please use the numbers printed before the configurations"
|
|
;;
|
|
esac
|
|
done
|
|
|
|
|
|
confFile=${wireguardConfigs[$choice]}
|
|
echo "Using $confFile"
|
|
|
|
|
|
fileContent="$(cat $confFile)"
|
|
|
|
listenPort=$(parseConf "$fileContent" ListenPort)
|
|
address=$(parseConf "$fileContent" Address)
|
|
targetDomain=$(echo $(ip -4 -resolve -brief addr show | grep UP) | cut -f3 -d' ' | cut -f1 -d'/')
|
|
# Manually add '=' as we cut with delimiter '='
|
|
pubKey=$(echo $(parseConf "$fileContent" PrivateKey)= | wg pubkey)
|
|
|
|
|
|
echo -n "Server address is $address, please enter peer address: "
|
|
read peerAddress
|
|
|
|
echo -n "Please enter allowed IPs range for peer: "
|
|
read peerAllowedIPs
|
|
|
|
peerKey=$(wg genkey)
|
|
peerPubKey=$(echo $peerKey | wg pubkey)
|
|
|
|
cat <<EOF >> $confFile
|
|
|
|
[Peer]
|
|
PublicKey = $peerPubKey
|
|
AllowedIPs = $peerAddress/32
|
|
|
|
EOF
|
|
|
|
cat <<EOF
|
|
[Interface]
|
|
Address = $peerAddress/$(echo $address | cut -f2 -d'/')
|
|
PrivateKey = $peerKey
|
|
|
|
[Peer]
|
|
PublicKey = $pubKey
|
|
AllowedIPs = $peerAllowedIPs
|
|
Endpoint = $targetDomain:$listenPort
|
|
|
|
|
|
EOF
|