summaryrefslogtreecommitdiff
path: root/modules/vpn.nix
blob: 3f461aa8957378d8f2e23569cc2b59a7a6e1dcb1 (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
{ config, lib, pkgs, ... }:

let
  cfg = config.orbekk.vpn;

  vpn-prefix = "2001:470:8e2e:1000";

  mkConfig = host: ip: {
    ips = [ "${vpn-prefix}::${ip}/128" ];
    publicKey = (builtins.readFile (../secrets + "/${host}-wireguard-key.pub"));
    endpoint = null;
    router = false;
  };

  hosts = {
    dragon = mkConfig "dragon" "d" // {
      endpoint = "dragon.orbekk.com:${toString cfg.listenPort}";
      router = true;
    };
    tiny1 = mkConfig "tiny1" "1001" // {
      endpoint = "tiny1.orbekk.com:${toString cfg.listenPort}";
    };
    firelink = mkConfig "firelink" "2001";
    pincer = mkConfig "pincer" "2002";
    steamdeck = mkConfig "steamdeck" "2003" // {
      ips = [ "${vpn-prefix}::2003/128" "${vpn-prefix}::2004/128" ];
    };
    trygve = mkConfig "trygve" "2004";
  };

  mkPeer = hostConfig: {
    inherit (hostConfig) publicKey endpoint;
    allowedIPs = if hostConfig.router && !cfg.is_server then
      [ "${vpn-prefix}::/64" ]
    else
      hostConfig.ips;
  };

  getPeers = host:
    if host == "dragon" then
      builtins.map mkPeer
      (builtins.attrValues (builtins.removeAttrs hosts [ host ]))
    else
      builtins.map mkPeer [ hosts.dragon ];

in {
  options = {
    orbekk.vpn = {
      enable = lib.mkEnableOption "Enable VPN";

      is_server = lib.mkOption {
        type = lib.types.bool;
        default = false;
      };

      listenPort = lib.mkOption {
        type = lib.types.port;
        default = 40422;
        description = "wireguard local port";
      };
    };
  };

  config = lib.mkIf cfg.enable {
    orbekk.simple-firewall.allowedUDPPorts = [ cfg.listenPort ];

    age.secrets = {
      "${config.networking.hostName}-wireguard-key".file = ./.
        + "/../secrets/${config.networking.hostName}-wireguard-key.age";
    };

    networking.networkmanager.unmanaged = [ "vpn" ];

    networking.wireguard = {
      enable = true;
      interfaces.vpn = {
        ips = hosts.${config.networking.hostName}.ips;
        privateKeyFile =
          "${config.age.secrets."${config.networking.hostName}-wireguard-key".path}";
        allowedIPsAsRoutes = true;
        listenPort = cfg.listenPort;
        peers = getPeers config.networking.hostName;
      };
    };
  };
}