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

let
  cfg = config.orbekk.vpn;

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

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

  hosts = {
    dragon = mkConfig "dragon" "d" // {
      endpoint = "dragon.orbekk.com:${toString cfg.listenPort}";
      server = true;
    };
    tiny1 = mkConfig "tiny1" "1001" // {
      endpoint = "tiny1.orbekk.com:${toString cfg.listenPort}";
      server = true;
    };
    firelink = mkConfig "firelink" "2001";
    pincer = mkConfig "pincer" "2002";
  };

  mkPeer = hostConfig: {
    inherit (hostConfig) publicKey endpoint;
    allowedIPs = (lib.optionals (!hostConfig.server && !cfg.is_server) [ "0.0.0.0/0" "::/0" ]);
  };

  getPeers = host:
    builtins.map mkPeer (builtins.attrValues (builtins.removeAttrs hosts [host]));
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 = false;
        listenPort = cfg.listenPort;
        peers = getPeers config.networking.hostName;
      };
    };
  };
}