Bash script to automate generation of certificates in WireGuard VPN
In this post you will find two easy bash scripts that can help you in process of generation multiple certificates in WireGuard VPN service. I create it to reduce time of certificate generation for myself, but it can be useful for you, as I could not find such solution with Google.
To use these scripts you need to have configured WireGuard service and access to wg
tool.
Next create folder and create bash file, give him executable rights and put this code in it. Change PublicKey
property of your servers WireGuard config. Create folder serts
in the same folder.
#!/bin/bash
file="publickey";
[ -e $file ] && rm $file;
file="privatekey";
[ -e $file ] && rm $file;
wg genkey | tee privatekey | wg pubkey > publickey
privatekey=`cat privatekey`
publickey=`cat publickey`
echo Print name of sert with lowcases;
read name;
echo Print last ip number;
read iplast;
echo $name" "$iplast;
wg set wg0 peer $publickey allowed-ips 10.0.0.$iplast
#print to sert
sertname=$name".meniko.vpn.conf";
folder='./serts';
echo "[Interface]" >> $folder"/"$sertname
echo "PrivateKey = "$privatekey >> $folder"/"$sertname
echo "Address = 10.0.0."$iplast"/24" >> $folder"/"$sertname
echo "DNS = 1.1.1.1, 8.8.8.8" >> $folder"/"$sertname
echo "[Peer]" >> $folder"/"$sertname
echo "PublicKey = [public key of server]" >> $folder"/"$sertname
echo "AllowedIPs = 0.0.0.0/0" >> $folder"/"$sertname
echo "Endpoint = vpn.meniko.ru:51820" >> $folder"/"$sertname
When you executes this bash script, you will be prompted for name and ip address of your user. After that script will create certificate for you and register it in WireGuard. Execute it with admin rights.
Next script can do restoring work, if something goes wrong, it reads every cert and resets it in WireGuard.
#!/bin/bash
for file in ./serts/*
do
echo "----"
echo $file
private=''
public=''
iplast=''
while IFS= read -r line
do
# find private key
pat="^PrivateKey = (.+)$"
if [[ $line =~ $pat ]];
then
echo $line
private="${BASH_REMATCH[1]}"
fi
# find ip adress
pat2="^Address = 10\.0\.0\.(.+)\/24$"
if [[ $line =~ $pat2 ]];
then
echo $line
iplast="${BASH_REMATCH[1]}"
fi
echo $line
done < "$file"
echo $private
public=`echo $private | wg pubkey`
echo $public
echo $iplast
wg set wg0 peer $public allowed-ips 10.0.0.$iplast
done