wg-createconfig.sh 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 >$confdir/$peer.conf <<EOL
  20. # Client config for $peer
  21. [Interface]
  22. PrivateKey = `cat $confdir/$peer.key`
  23. Address = $ip
  24. DNS = $dns
  25. [Peer]
  26. PublicKey = `cat $confdir/$servername.pub`
  27. AllowedIPs = $network
  28. Endpoint = $servername:$serverport
  29. PersistentKeepalive = 15
  30. PresharedKey = `cat $confdir/$peer.psk`
  31. EOL
  32. qrencode -t ANSIUTF8 -r $confdir/$peer.conf > $peer-qr.txt
  33. qrencode -t png -r $confdir/$peer.conf > $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. echo debug $confdir/$servername.conf
  43. cat >$confdir/$servername.conf <<EOL
  44. # Config for $peer
  45. [Interface]
  46. PrivateKey = `cat $confdir/$servername.key`
  47. Address = $serverip
  48. DNS = $dns
  49. EOL
  50. ## Create peers' key-pair, psk and config from peers.cfg
  51. while read peer;
  52. do
  53. ip=`echo $peer | cut -d' ' -f1`
  54. host=`echo $peer | cut -d' ' -f2`
  55. wgkeypair $host
  56. wgpsk $host
  57. wgconfig $host $ip
  58. # Add peers to server config
  59. cat >>$confdir/$servername.conf <<EOL
  60. [Peer]
  61. PublicKey = `cat $confdir/$host.pub`
  62. AllowedIPs = $ip
  63. PresharedKey = `cat $confdir/$host.psk`
  64. EOL
  65. done < peers.cfg