summaryrefslogtreecommitdiffstats
path: root/nixos/modules/services/networking/cloudflared.nix
blob: 26662e5633563f404a51fcc4e049323cb7787856 (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
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
{
  config,
  lib,
  pkgs,
  ...
}:
let
  cfg = config.services.cloudflared;

  certificateFile = lib.mkOption {
    type = with lib.types; nullOr path;
    description = ''
      Account certificate file, necessary to create, delete and manage tunnels. It can be obtained by running `cloudflared login`.

      Note that this is **necessary** for a fully declarative set up, as routes can not otherwise be created outside of the Cloudflare interface.

      See [Cert.pem](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-useful-terms/#certpem) for information about the file, and [Tunnel permissions](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/local-management/tunnel-permissions/) for a comparison between the account certificate and the tunnel credentials file.
    '';
    default = null;
  };

  originRequest = {
    connectTimeout = lib.mkOption {
      type = with lib.types; nullOr str;
      default = null;
      example = "30s";
      description = ''
        Timeout for establishing a new TCP connection to your origin server. This excludes the time taken to establish TLS, which is controlled by [tlsTimeout](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/local-management/ingress/#tlstimeout).
      '';
    };

    tlsTimeout = lib.mkOption {
      type = with lib.types; nullOr str;
      default = null;
      example = "10s";
      description = ''
        Timeout for completing a TLS handshake to your origin server, if you have chosen to connect Tunnel to an HTTPS server.
      '';
    };

    tcpKeepAlive = lib.mkOption {
      type = with lib.types; nullOr str;
      default = null;
      example = "30s";
      description = ''
        The timeout after which a TCP keepalive packet is sent on a connection between Tunnel and the origin server.
      '';
    };

    noHappyEyeballs = lib.mkOption {
      type = with lib.types; nullOr bool;
      default = null;
      example = false;
      description = ''
        Disable the “happy eyeballs” algorithm for IPv4/IPv6 fallback if your local network has misconfigured one of the protocols.
      '';
    };

    keepAliveConnections = lib.mkOption {
      type = with lib.types; nullOr int;
      default = null;
      example = 100;
      description = ''
        Maximum number of idle keepalive connections between Tunnel and your origin. This does not restrict the total number of concurrent connections.
      '';
    };

    keepAliveTimeout = lib.mkOption {
      type = with lib.types; nullOr str;
      default = null;
      example = "1m30s";
      description = ''
        Timeout after which an idle keepalive connection can be discarded.
      '';
    };

    httpHostHeader = lib.mkOption {
      type = with lib.types; nullOr str;
      default = null;
      example = "";
      description = ''
        Sets the HTTP `Host` header on requests sent to the local service.
      '';
    };

    originServerName = lib.mkOption {
      type = with lib.types; nullOr str;
      default = null;
      example = "";
      description = ''
        Hostname that `cloudflared` should expect from your origin server certificate.
      '';
    };

    caPool = lib.mkOption {
      type = with lib.types; nullOr (either str path);
      default = null;
      example = "";
      description = ''
        Path to the certificate authority (CA) for the certificate of your origin. This option should be used only if your certificate is not signed by Cloudflare.
      '';
    };

    noTLSVerify = lib.mkOption {
      type = with lib.types; nullOr bool;
      default = null;
      example = false;
      description = ''
        Disables TLS verification of the certificate presented by your origin. Will allow any certificate from the origin to be accepted.
      '';
    };

    disableChunkedEncoding = lib.mkOption {
      type = with lib.types; nullOr bool;
      default = null;
      example = false;
      description = ''
        Disables chunked transfer encoding. Useful if you are running a WSGI server.
      '';
    };

    proxyAddress = lib.mkOption {
      type = with lib.types; nullOr str;
      default = null;
      example = "127.0.0.1";
      description = ''
        `cloudflared` starts a proxy server to translate HTTP traffic into TCP when proxying, for example, SSH or RDP. This configures the listen address for that proxy.
      '';
    };

    proxyPort = lib.mkOption {
      type = with lib.types; nullOr int;
      default = null;
      example = 0;
      description = ''
        `cloudflared` starts a proxy server to translate HTTP traffic into TCP when proxying, for example, SSH or RDP. This configures the listen port for that proxy. If set to zero, an unused port will randomly be chosen.
      '';
    };

    proxyType = lib.mkOption {
      type =
        with lib.types;
        nullOr (enum [
          ""
          "socks"
        ]);
      default = null;
      example = "";
      description = ''
        `cloudflared` starts a proxy server to translate HTTP traffic into TCP when proxying, for example, SSH or RDP. This configures what type of proxy will be started. Valid options are:

        - `""` for the regular proxy
        - `"socks"` for a SOCKS5 proxy. Refer to the [tutorial on connecting through Cloudflare Access using kubectl](https://developers.cloudflare.com/cloudflare-one/tutorials/kubectl/) for more information.
      '';
    };
  };
in
{
  imports = [
    (lib.mkRemovedOptionModule
      [
        "services"
        "cloudflared"
        "user"
      ]
      ''
        Cloudflared now uses a dynamic user, and this option no longer has any effect.

        If the user is still necessary, please define it manually using users.users.cloudflared.
      ''
    )

    (lib.mkRemovedOptionModule
      [
        "services"
        "cloudflared"
        "group"
      ]
      ''
        Cloudflared now uses a dynamic user, and this option no longer has any effect.

        If the group is still necessary, please define it manually using users.groups.cloudflared.
      ''
    )
  ];

  options.services.cloudflared = {
    inherit certificateFile;

    enable = lib.mkEnableOption "Cloudflare Tunnel client daemon (formerly Argo Tunnel)";

    package = lib.mkPackageOption pkgs "cloudflared" { };

    tunnels = lib.mkOption {
      description = ''
        Cloudflare tunnels.
      '';
      type = lib.types.attrsOf (
        lib.types.submodule (
          { name, ... }:
          {
            options = {
              inherit certificateFile originRequest;

              credentialsFile = lib.mkOption {
                type = lib.types.path;
                description = ''
                  Credential file.

                  See [Credentials file](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-useful-terms/#credentials-file).
                '';
              };

              warp-routing = {
                enabled = lib.mkOption {
                  type = with lib.types; nullOr bool;
                  default = null;
                  description = ''
                    Enable warp routing.

                    See [Connect from WARP to a private network on Cloudflare using Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/tutorials/warp-to-tunnel/).
                  '';
                };
              };

              edgeIPVersion = lib.mkOption {
                type = lib.types.enum [
                  "auto"
                  "4"
                  "6"
                ];
                default = "4";
                description = ''
                  Specifies the IP address version (IPv4 or IPv6) used to establish a connection between `cloudflared` and the Cloudflare global network.

                  The value `auto` relies on the host operating system to determine which IP version to select. The first IP version returned from the DNS resolution of the region lookup will be used as the primary set. In dual IPv6 and IPv4 network setups, `cloudflared` will separate the IP versions into two address sets that will be used to fallback in connectivity failure scenarios.

                  See [Tunnel run parameters](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/configure-tunnels/cloudflared-parameters/run-parameters/#edge-ip-version).
                '';
                example = "auto";
              };

              protocol = lib.mkOption {
                type = lib.types.enum [
                  "auto"
                  "http2"
                  "quic"
                ];
                default = "auto";
                description = ''
                  Specifies the protocol used to establish a connection between `cloudflared` and the Cloudflare global network.

                  The value `auto` lets `cloudflared` choose the protocol (currently QUIC, falling back to HTTP/2).
                  Set to `http2` to work around QUIC/UDP connectivity issues, such as restrictive firewalls, broken UDP path MTU, or QUIC interop bugs.
                  Set to `quic` to force QUIC.

                  See [Tunnel run parameters](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/configure-tunnels/cloudflared-parameters/run-parameters/#protocol).
                '';
                example = "http2";
              };

              default = lib.mkOption {
                type = lib.types.str;
                description = ''
                  Catch-all service if no ingress matches.

                  See `service`.
                '';
                example = "http_status:404";
              };

              ingress = lib.mkOption {
                type =
                  with lib.types;
                  attrsOf (
                    either str (
                      submodule (
                        { hostname, ... }:
                        {
                          options = {
                            inherit originRequest;

                            service = lib.mkOption {
                              type = with lib.types; nullOr str;
                              default = null;
                              description = ''
                                Service to pass the traffic.

                                See [Supported protocols](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/local-management/ingress/#supported-protocols).
                              '';
                              example = "http://localhost:80, tcp://localhost:8000, unix:/home/production/echo.sock, hello_world or http_status:404";
                            };

                            path = lib.mkOption {
                              type = with lib.types; nullOr str;
                              default = null;
                              description = ''
                                Path filter.

                                If not specified, all paths will be matched.
                              '';
                              example = "/*.(jpg|png|css|js)";
                            };

                          };
                        }
                      )
                    )
                  );
                default = { };
                description = ''
                  Ingress rules.

                  See [Ingress rules](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configuration/local-management/ingress/).
                '';
                example = {
                  "*.domain.com" = "http://localhost:80";
                  "*.anotherone.com" = "http://localhost:80";
                };
              };
            };
          }
        )
      );

      default = { };
      example = {
        "00000000-0000-0000-0000-000000000000" = {
          credentialsFile = "/tmp/test";
          ingress = {
            "*.domain1.com" = {
              service = "http://localhost:80";
            };
          };
          default = "http_status:404";
        };
      };
    };
  };

  config = lib.mkIf cfg.enable {
    systemd.targets = lib.mapAttrs' (
      name: tunnel:
      lib.nameValuePair "cloudflared-tunnel-${name}" {
        description = "Cloudflare tunnel '${name}' target";
        requires = [ "cloudflared-tunnel-${name}.service" ];
        after = [ "cloudflared-tunnel-${name}.service" ];
        unitConfig.StopWhenUnneeded = true;
      }
    ) config.services.cloudflared.tunnels;

    systemd.services = lib.mapAttrs' (
      name: tunnel:
      let
        filterConfig = lib.attrsets.filterAttrsRecursive (
          _: v:
          !builtins.elem v [
            null
            [ ]
            { }
          ]
        );

        filterIngressSet = lib.filterAttrs (_: v: builtins.typeOf v == "set");
        filterIngressStr = lib.filterAttrs (_: v: builtins.typeOf v == "string");

        ingressesSet = filterIngressSet tunnel.ingress;
        ingressesStr = filterIngressStr tunnel.ingress;

        fullConfig = filterConfig {
          tunnel = name;
          credentials-file = "/run/credentials/cloudflared-tunnel-${name}.service/credentials.json";
          warp-routing = filterConfig tunnel.warp-routing;
          originRequest = filterConfig tunnel.originRequest;
          ingress =
            (map (
              key:
              {
                hostname = key;
              }
              // lib.getAttr key (filterConfig (filterConfig ingressesSet))
            ) (lib.attrNames ingressesSet))
            ++ (map (key: {
              hostname = key;
              service = lib.getAttr key ingressesStr;
            }) (lib.attrNames ingressesStr))
            ++ [ { service = tunnel.default; } ];
        };

        mkConfigFile = pkgs.writeText "cloudflared.yml" (builtins.toJSON fullConfig);
        certFile = if (tunnel.certificateFile != null) then tunnel.certificateFile else cfg.certificateFile;
      in
      lib.nameValuePair "cloudflared-tunnel-${name}" {
        after = [
          "network.target"
          "network-online.target"
        ];
        wants = [
          "network.target"
          "network-online.target"
        ];
        wantedBy = [ "multi-user.target" ];
        serviceConfig = {
          RuntimeDirectory = "cloudflared-tunnel-${name}";
          RuntimeDirectoryMode = "0400";
          LoadCredential = [
            "credentials.json:${tunnel.credentialsFile}"
          ]
          ++ (lib.optional (certFile != null) "cert.pem:${certFile}");

          ExecStart = "${cfg.package}/bin/cloudflared tunnel --config=${mkConfigFile} --no-autoupdate run";
          Restart = "on-failure";
          DynamicUser = true;
        };

        environment = {
          TUNNEL_ORIGIN_CERT = lib.mkIf (certFile != null) "%d/cert.pem";
          TUNNEL_EDGE_IP_VERSION = tunnel.edgeIPVersion;
          TUNNEL_TRANSPORT_PROTOCOL = tunnel.protocol;
        };
      }
    ) config.services.cloudflared.tunnels;
  };

  meta.maintainers = with lib.maintainers; [
    bbigras
    anpin
  ];
}