summary refs log tree commit diff
path: root/modules/wireguard.nix
diff options
context:
space:
mode:
Diffstat (limited to 'modules/wireguard.nix')
-rw-r--r--modules/wireguard.nix81
1 files changed, 81 insertions, 0 deletions
diff --git a/modules/wireguard.nix b/modules/wireguard.nix
new file mode 100644
index 0000000..176213f
--- /dev/null
+++ b/modules/wireguard.nix
@@ -0,0 +1,81 @@
+{ config, pkgs, ... }:
+
+let
+  inherit (pkgs) iptables;
+
+  wireguardPort = 51820;
+  wireguardIPv4 = number: subnet: "10.123.10.${number}/${subnet}";
+  wireguardIPv6 = number: subnet: "fd0f:123::${number}/${subnet}";
+
+  wireguardInterface = "wg0";
+  externalInterface = "enp1s0";
+
+  peerIPs = peerNumber: [
+    (wireguardIPv4 peerNumber "32")
+    (wireguardIPv6 peerNumber "128")
+  ];
+  peers = [
+    # mel
+    {
+      publicKey = "vnZoHXapCLLUhZ8A8R5W0iJ8LpWVLve29z41kkoT0BU=";
+      allowedIPs = peerIPs "2";
+    }
+
+    # andrei
+    {
+      publicKey = "qqU4uYImLfUohIwl4KBshPtTINFcs0JVALjbmwpfxRg=";
+      allowedIPs = peerIPs "3";
+    }
+  ];
+
+in
+{
+  age.secrets.wireguard-private-key = {
+    file = ../secrets/wireguard-private-key.age;
+  };
+
+  # enable nat, to rename internal wireguard ips to external ip (w/ iptables)
+  networking = {
+    nat = {
+      enable = true;
+      internalInterfaces = [ wireguardInterface ];
+      inherit externalInterface;
+    };
+
+    firewall = {
+      allowedUDPPorts = [ wireguardPort ];
+    };
+  };
+
+  # enable kernel support for ipv6 forwarding
+  boot.kernel.sysctl = {
+    "net.ipv6.conf.all.forwarding" = 1;
+    "net.ipv6.conf.default.forwarding" = 1;
+  };
+
+  networking.wireguard.interfaces.${wireguardInterface} = {
+    inherit peers;
+
+    # ip address of server + subnet of network
+    ips = [
+      (wireguardIPv4 "1" "24")
+      (wireguardIPv6 "1" "112")
+    ];
+    listenPort = wireguardPort;
+
+    # route wireguard traffic to the internet
+    # also requires clients to have dns set. (i think)
+    # to avoid, maybe? use wg-quick + dnsmasq?
+    postSetup = ''
+      ${iptables}/bin/iptables -t nat -A POSTROUTING -s ${wireguardIPv4 "0" "24"} -o ${externalInterface} -j MASQUERADE
+      ${iptables}/bin/ip6tables -t nat -A POSTROUTING -s ${wireguardIPv6 "0" "112"} -o ${externalInterface} -j MASQUERADE
+    '';
+
+    postShutdown = ''
+      ${iptables}/bin/iptables -t nat -D POSTROUTING -s ${wireguardIPv4 "0" "24"} -o ${externalInterface} -j MASQUERADE
+      ${iptables}/bin/ip6tables -t nat -D POSTROUTING -s ${wireguardIPv6 "0" "112"} -o ${externalInterface} -j MASQUERADE
+    '';
+
+    privateKeyFile = config.age.secrets.wireguard-private-key.path;
+  };
+}