Self-host your own digital island
1{ pkgs, config, lib, ... }:
2
3with lib;
4
5let cfg = config.wireguard; in
6{
7 options.wireguard = {
8 enable = mkEnableOption "wireguard";
9 server = mkOption {
10 type = with types; bool;
11 default =
12 if cfg.hosts ? config.networking.hostName then
13 cfg.hosts.${config.networking.hostName}.server
14 else false;
15 };
16 hosts =
17 let hostOps = { ... }: {
18 options = {
19 ip = mkOption {
20 type = types.str;
21 };
22 publicKey = mkOption {
23 type = types.str;
24 };
25 server = mkOption {
26 type = types.bool;
27 default = false;
28 };
29 endpoint = mkOption {
30 type = with types; nullOr str;
31 default = null;
32 # should not be null when server = true
33 };
34 persistentKeepalive = mkOption {
35 type = with types; nullOr int;
36 default = null;
37 };
38 };
39 };
40 in mkOption {
41 type = with types; attrsOf (submodule hostOps);
42 };
43 };
44
45 config = mkIf cfg.enable {
46 environment.systemPackages = with pkgs; [ wireguard-tools ];
47 networking = {
48 # populate /etc/hosts with hostnames and IPs
49 extraHosts = builtins.concatStringsSep "\n" (
50 attrsets.mapAttrsToList (
51 hostName: values: "${values.ip} ${hostName}"
52 ) cfg.hosts
53 );
54
55 firewall = {
56 allowedUDPPorts = [ 51820 ];
57 checkReversePath = false;
58 };
59
60 wireguard = {
61 enable = true;
62 interfaces.wg0 = let hostName = config.networking.hostName; in {
63 ips =
64 if cfg.hosts ? hostname then
65 [ "${cfg.hosts."${hostName}".ip}/24" ]
66 else [ ];
67 listenPort = 51820;
68 privateKeyFile = "${config.eilean.secretsDir}/wireguard-key-${hostName}";
69 peers =
70 let
71 serverPeers = attrsets.mapAttrsToList
72 (hostName: values:
73 if values.server then
74 {
75 allowedIPs = [ "10.0.0.0/24" ];
76 publicKey = values.publicKey;
77 endpoint = "${values.endpoint}:51820";
78 persistentKeepalive = values.persistentKeepalive;
79 }
80 else {})
81 cfg.hosts;
82 # remove empty elements
83 cleanedServerPeers = lists.remove { } serverPeers;
84 in mkIf (!cfg.server) cleanedServerPeers;
85 };
86 };
87 };
88 };
89}