summary refs log tree commit diff
path: root/nixos/modules/services/networking/dnscrypt-wrapper.nix
blob: e53fb7a157828f55ec6ca156df387510867eca50 (plain) (blame)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
{ config, lib, pkgs, ... }:
with lib;

let
  cfg     = config.services.dnscrypt-wrapper;
  dataDir = "/var/lib/dnscrypt-wrapper";

  daemonArgs = with cfg; [
    "--listen-address=${address}:${toString port}"
    "--resolver-address=${upstream.address}:${toString upstream.port}"
    "--provider-name=${providerName}"
    "--provider-publickey-file=public.key"
    "--provider-secretkey-file=secret.key"
    "--provider-cert-file=${providerName}.crt"
    "--crypt-secretkey-file=${providerName}.key"
  ];

  genKeys = ''
    # generates time-limited keypairs
    keyGen() {
      dnscrypt-wrapper --gen-crypt-keypair \
        --crypt-secretkey-file=${cfg.providerName}.key

      dnscrypt-wrapper --gen-cert-file \
        --crypt-secretkey-file=${cfg.providerName}.key \
        --provider-cert-file=${cfg.providerName}.crt \
        --provider-publickey-file=public.key \
        --provider-secretkey-file=secret.key \
        --cert-file-expire-days=${toString cfg.keys.expiration}
    }

    cd ${dataDir}

    # generate provider keypair (first run only)
    if [ ! -f public.key ] || [ ! -f secret.key ]; then
      dnscrypt-wrapper --gen-provider-keypair
    fi

    # generate new keys for rotation
    if [ ! -f ${cfg.providerName}.key ] || [ ! -f ${cfg.providerName}.crt ]; then
      keyGen
    fi
  '';

  rotateKeys = ''
    # check if keys are not expired
    keyValid() {
      fingerprint=$(dnscrypt-wrapper --show-provider-publickey | awk '{print $(NF)}')
      dnscrypt-proxy --test=${toString (cfg.keys.checkInterval + 1)} \
        --resolver-address=127.0.0.1:${toString cfg.port} \
        --provider-name=${cfg.providerName} \
        --provider-key=$fingerprint
    }

    cd ${dataDir}

    # archive old keys and restart the service
    if ! keyValid; then
      echo "certificate soon to become invalid; backing up old cert"
      mkdir -p oldkeys
      mv -v ${cfg.providerName}.key oldkeys/${cfg.providerName}-$(date +%F-%T).key
      mv -v ${cfg.providerName}.crt oldkeys/${cfg.providerName}-$(date +%F-%T).crt
      systemctl restart dnscrypt-wrapper
    fi
  '';

in {


  ###### interface

  options.services.dnscrypt-wrapper = {
    enable = mkEnableOption "DNSCrypt wrapper";

    address = mkOption {
      type = types.str;
      default = "127.0.0.1";
      description = ''
        The DNSCrypt wrapper will bind to this IP address.
      '';
    };

    port = mkOption {
      type = types.int;
      default = 5353;
      description = ''
        The DNSCrypt wrapper will listen for DNS queries on this port.
      '';
    };

    providerName = mkOption {
      type = types.str;
      default = "2.dnscrypt-cert.${config.networking.hostName}";
      example = "2.dnscrypt-cert.myresolver";
      description = ''
        The name that will be given to this DNSCrypt resolver.
        Note: the resolver name must start with <literal>2.dnscrypt-cert.</literal>.
      '';
    };

    upstream.address = mkOption {
      type = types.str;
      default = "127.0.0.1";
      description = ''
        The IP address of the upstream DNS server DNSCrypt will "wrap".
      '';
    };

    upstream.port = mkOption {
      type = types.int;
      default = 53;
      description = ''
        The port of the upstream DNS server DNSCrypt will "wrap".
      '';
    };

    keys.expiration = mkOption {
      type = types.int;
      default = 30;
      description = ''
        The duration (in days) of the time-limited secret key.
        This will be automatically rotated before expiration.
      '';
    };

    keys.checkInterval = mkOption {
      type = types.int;
      default = 1440;
      description = ''
        The time interval (in minutes) between key expiration checks.
      '';
    };

  };


  ###### implementation

  config = mkIf cfg.enable {

    users.users.dnscrypt-wrapper = {
      description = "dnscrypt-wrapper daemon user";
      home = "${dataDir}";
      createHome = true;
      isSystemUser = true;
    };
    users.groups.dnscrypt-wrapper = { };

    security.polkit.extraConfig = ''
      // Allow dnscrypt-wrapper user to restart dnscrypt-wrapper.service
      polkit.addRule(function(action, subject) {
          if (action.id == "org.freedesktop.systemd1.manage-units" &&
              action.lookup("unit") == "dnscrypt-wrapper.service" &&
              subject.user == "dnscrypt-wrapper") {
              return polkit.Result.YES;
          }
        });
    '';

    systemd.services.dnscrypt-wrapper = {
      description = "dnscrypt-wrapper daemon";
      after    = [ "network.target" ];
      wantedBy = [ "multi-user.target" ];
      path     = [ pkgs.dnscrypt-wrapper ];

      serviceConfig = {
        User = "dnscrypt-wrapper";
        WorkingDirectory = dataDir;
        Restart   = "on-failure";
        ExecStart = "${pkgs.dnscrypt-wrapper}/bin/dnscrypt-wrapper ${toString daemonArgs}";
      };

      preStart = genKeys;
    };


    systemd.services.dnscrypt-wrapper-rotate = {
      after    = [ "network.target" ];
      requires = [ "dnscrypt-wrapper.service" ];
      description = "Rotates DNSCrypt wrapper keys if soon to expire";

      path   = with pkgs; [ dnscrypt-wrapper dnscrypt-proxy gawk ];
      script = rotateKeys;
      serviceConfig.User = "dnscrypt-wrapper";
    };


    systemd.timers.dnscrypt-wrapper-rotate = {
      description = "Periodically check DNSCrypt wrapper keys for expiration";
      wantedBy = [ "multi-user.target" ];

      timerConfig = {
        Unit = "dnscrypt-wrapper-rotate.service";
        OnBootSec = "1min";
        OnUnitActiveSec = cfg.keys.checkInterval * 60;
      };
    };

  };

  meta.maintainers = with lib.maintainers; [ rnhmjoj ];

}