Setting up Raspberry Pi as a Wireguard Gateway

Requirements

Step by step

  1. download Raspberry OS Lite and write to SD
    sudo dd if=2021-01-11-raspios-buster-armhf-lite.img of=??? bs=4M
  2. Boot (we don’t need the USB adapter yet)
  3. Set a new password for the user pi:
    passwd
  4. Authenticate as root:
    sudo su
  5. apt update;apt dist-upgrade
  6. systemctl enable --now ssh
  7. raspi-config
    - change hostname
    - reduce GPU memory
    - wait for network before booting
  8. Add testing repository and install wireguard
    echo “deb http://archive.raspbian.org/raspbian testing main” > /etc/apt/sources.list.d/testing.list
    printf 'Package: *\nPin: release a=testing\nPin-Priority: 50\n' | tee –append /etc/apt/preferences.d/limit-testing
    apt update
    apt install wireguard
  9. Enable IPv4 Forwarding
    echo “net.ipv4.ip_forward = 1” » /etc/sysctl.conf
  10. Create a private key for the client
    wg genkey
  11. Calculate the corresponding public key
    echo '(INSERT PRIVATE KEY)' | wg pubkey
  12. Create client config
    [Interface]
    PrivateKey = RASPBERRYPRIVATEKEY
    Address = 192.168.4.70/24
    DNS = 192.168.0.1, 8.8.8.8
     
    [Peer]
    PublicKey = SERVERPUBLICKEY
    AllowedIPs = 0.0.0.0/0, ::/0
    Endpoint = example.com:12345
  13. Append a segment to the server's wireguard config
    [Peer] # raspberry
    PublicKey = RASPBERRYPUBLICKEY
    AllowedIPs = 192.168.4.70/32
  14. Restart wireguard interface on the server
    systemctl restart wg-quick@wg0.service
  15. Back on the raspberry, move the client config to /etc/wireguard, e.g. /etc/wireguard/raspberry.conf
  16. systemctl start wg-quick@raspberry
  17. Verify that the interface is used, eg. traceroute google.com
  18. Enable the service to make it permanent
    systemctl enable wg-quick@raspberry
  19. Install the DHCP server
    apt install isc-dhcp-server
  20. Plug in the USB adapter and check out it's interface name (should be eth1)
  21. Edit interface config /etc/network/interfaces.d/eth1
    auto eth1
    iface eth1 inet static
        address 192.168.100.1
        netmask 255.255.255.0
  22. Edit this line in /etc/default/isc-dhcp-server:
    INTERFACESv4=“eth1”
  23. Edit /etc/dhcp/dhcpd.conf:
    option domain-name-servers 8.8.8.8, 8.8.8.4;
    option subnet-mask 255.255.255.0;
    option broadcast-address 192.168.100.255;
    subnet 192.168.100.0 netmask 255.255.255.0 {
    range 192.168.100.20 192.168.100.100;
    option routers 192.168.100.1;
    } 
  24. systemctl restart isc-dhcp-server
  25. allow NAT forwarding iptables rule:
    iptables -t nat -A POSTROUTING -o raspberry -j MASQUERADE
  26. Save the iptables config:
    apt install iptables-persistent
    iptables-save > /etc/iptables/rules.v4
  27. Make sure the iptables config is loaded at boot:
    echo '/sbin/iptables-restore < /etc/iptables/rules.v4' » /etc/rc.local