summary refs log tree commit diff
path: root/modules/foundation/vpn.nix
blob: f4a5d216ba4a5241455ae0933f6311df6d27a3c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
{
  config,
  lib,
  ...
}:

let
  inherit (lib)
    mkEnableOption
    mkOption
    types
    mkIf
    attrValues
    replaceString
    ;

  cfg = config.foundation.vpn;

  inherit (import ../../assets/vpn.nix) users;

  interface = "vpn0";
  port = 51820;

  # while the tunnel uses the lower subnets for the paths,
  # the vpn always uses subnet number 10.
  subnetIndex = 10;

  addressFromTemplate =
    template: prefix: "${replaceString "X" (toString subnetIndex) template}/${toString prefix}";
in
{
  options.foundation.vpn = {
    enable = mkEnableOption "WireGuard VPN server";

    externalInterface = mkOption {
      type = types.str;
      description = "External network interface";
    };
  };

  config = mkIf cfg.enable {
    age.secrets.wg-private-key = {
      file = ../../secrets/wg-private-key.age;
      owner = "systemd-network";
    };

    networking.firewall.allowedUDPPorts = [ port ];

    systemd.network = {
      netdevs."30-${interface}" = {
        netdevConfig = {
          Kind = "wireguard";
          Name = interface;
        };
        wireguardConfig = {
          PrivateKeyFile = config.age.secrets.wg-private-key.path;
          ListenPort = port;
        };
        wireguardPeers = map (user: {
          PublicKey = user.key;
          AllowedIPs = [ (addressFromTemplate user.ip 32) ];
        }) (attrValues users);
      };

      networks."30-${interface}" = {
        name = interface;
        address = [ (addressFromTemplate "10.123.X.1" 24) ];
        linkConfig = {
          RequiredForOnline = "no";
        };
      };
    };

    networking.nftables.tables.vpn-nat = {
      family = "ip";
      content = ''
        chain postrouting {
          type nat hook postrouting priority srcnat; policy accept;
          iifname "${interface}" oifname "${cfg.externalInterface}" masquerade
        }

        chain forward {
          type filter hook forward priority 0; policy accept;
          iifname "${interface}" oifname "${cfg.externalInterface}" accept
          iifname "${cfg.externalInterface}" oifname "${interface}" ct state established,related accept

          # drop vpn-sourced traffic headed anywhere but external
          iifname "${interface}" drop
        }
      '';
    };
  };
}