wg-createconfig.sh 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/bin/bash
  2. # Setup keys, psk and config for a central wireguard server including peers
  3. # Dependencies
  4. # apk add wireguard-tools libqrencode
  5. ### References
  6. # https://wiki.archlinux.org/title/WireGuard
  7. # Source global variables
  8. confdir='./config'
  9. source ./config/server.cfg
  10. # ---------Functions-----------
  11. ## Create key-pair
  12. wgkeypair() { wg genkey | (umask 0077 && tee $1.key) | wg pubkey > $1.pub; }
  13. ## Create psk
  14. wgpsk() { wg genpsk | (umask 0077 && cat > $1.psk) }
  15. ## Create peer config file
  16. wgconfig() {
  17. peer=$1
  18. ip=$2
  19. cat >$peer.conf <<EOL
  20. # Client config for $peer
  21. [Interface]
  22. PrivateKey = `cat $peer.key`
  23. Address = $ip
  24. DNS = $dns
  25. [Peer]
  26. PublicKey = `cat $servername.pub`
  27. AllowedIPs = $network
  28. Endpoint = $servername:$serverport
  29. PersistentKeepalive = 15
  30. PresharedKey = `cat $peer.psk`
  31. EOL
  32. qrencode -t ANSIUTF8 -r $peer.conf > $peer-qr.txt
  33. qrencode -t png -r $peer.conf -o $peer.png
  34. }
  35. # ---------Functions-----------
  36. ## Create and move to output folder
  37. mkdir -p $confdir
  38. cd $confdir
  39. ## Create server keys
  40. wgkeypair $servername
  41. ## Create server config
  42. cat >$servername.conf <<EOL
  43. # Config for $peer
  44. [Interface]
  45. PrivateKey = `cat $servername.key`
  46. Address = $serverip
  47. DNS = $dns
  48. EOL
  49. ## Create peers' key-pair, psk and config from peers.cfg
  50. while read peer;
  51. do
  52. ip=`echo $peer | cut -d' ' -f1`
  53. host=`echo $peer | cut -d' ' -f2`
  54. wgkeypair $host
  55. wgpsk $host
  56. wgconfig $host $ip
  57. # Add peers to server config
  58. cat >>$servername.conf <<EOL
  59. [Peer]
  60. PublicKey = `cat $host.pub`
  61. AllowedIPs = $ip
  62. PresharedKey = `cat $host.psk`
  63. EOL
  64. done < peers.cfg