fork/home-manager

git clone https://git.julia.blue/fork/home-manager

Robert HelgessonMerge PR #421575790441

master
16.3 KiB547 linesraw
1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7  cfg = config.programs.ssh;
8
9  isPath = x: builtins.substring 0 1 (toString x) == "/";
10
11  addressPort = entry:
12    if isPath entry.address
13    then " ${entry.address}"
14    else " [${entry.address}]:${toString entry.port}";
15
16  unwords = builtins.concatStringsSep " ";
17
18  mkSetEnvStr = envStr: unwords
19    (mapAttrsToList
20      (name: value: ''${name}="${escape [ "\"" "\\" ] (toString value)}"'')
21      envStr
22    );
23
24  bindOptions = {
25    address = mkOption {
26      type = types.str;
27      default = "localhost";
28      example = "example.org";
29      description = "The address where to bind the port.";
30    };
31
32    port = mkOption {
33      type = types.nullOr types.port;
34      default = null;
35      example = 8080;
36      description = "Specifies port number to bind on bind address.";
37    };
38  };
39
40  dynamicForwardModule = types.submodule {
41    options = bindOptions;
42  };
43
44  forwardModule = types.submodule {
45    options = {
46      bind = bindOptions;
47
48      host = {
49        address = mkOption {
50          type = types.nullOr types.str;
51          default = null;
52          example = "example.org";
53          description = "The address where to forward the traffic to.";
54        };
55
56        port = mkOption {
57          type = types.nullOr types.port;
58          default = null;
59          example = 80;
60          description = "Specifies port number to forward the traffic to.";
61        };
62      };
63    };
64  };
65
66  matchBlockModule = types.submodule ({ dagName, ... }: {
67    options = {
68      host = mkOption {
69        type = types.nullOr types.str;
70        default = null;
71        example = "*.example.org";
72        description = ''
73          `Host` pattern used by this conditional block.
74          See
75          {manpage}`ssh_config(5)`
76          for `Host` block details.
77          This option is ignored if
78          {option}`ssh.matchBlocks.*.match`
79          if defined.
80        '';
81      };
82
83      match = mkOption {
84        type = types.nullOr types.str;
85        default = null;
86        example = "host <hostname> canonical\nhost <hostname> exec \"ping -c1 -q 192.168.17.1\"";
87        description = ''
88          `Match` block conditions used by this block. See
89          {manpage}`ssh_config(5)`
90          for `Match` block details.
91          This option takes precedence over
92          {option}`ssh.matchBlocks.*.host`
93          if defined.
94        '';
95      };
96
97      port = mkOption {
98        type = types.nullOr types.port;
99        default = null;
100        description = "Specifies port number to connect on remote host.";
101      };
102
103      forwardAgent = mkOption {
104        default = null;
105        type = types.nullOr types.bool;
106        description = ''
107          Whether the connection to the authentication agent (if any)
108          will be forwarded to the remote machine.
109        '';
110      };
111
112      forwardX11 = mkOption {
113        type = types.bool;
114        default = false;
115        description = ''
116          Specifies whether X11 connections will be automatically redirected
117          over the secure channel and {env}`DISPLAY` set.
118        '';
119      };
120
121      forwardX11Trusted = mkOption {
122        type = types.bool;
123        default = false;
124        description = ''
125          Specifies whether remote X11 clients will have full access to the
126          original X11 display.
127        '';
128      };
129
130      identitiesOnly = mkOption {
131        type = types.bool;
132        default = false;
133        description = ''
134          Specifies that ssh should only use the authentication
135          identity explicitly configured in the
136          {file}`~/.ssh/config` files or passed on the
137          ssh command-line, even if {command}`ssh-agent`
138          offers more identities.
139        '';
140      };
141
142      identityFile = mkOption {
143        type = with types; either (listOf str) (nullOr str);
144        default = [];
145        apply = p:
146          if p == null then []
147          else if isString p then [p]
148          else p;
149        description = ''
150          Specifies files from which the user identity is read.
151          Identities will be tried in the given order.
152        '';
153      };
154
155      user = mkOption {
156        type = types.nullOr types.str;
157        default = null;
158        description = "Specifies the user to log in as.";
159      };
160
161      hostname = mkOption {
162        type = types.nullOr types.str;
163        default = null;
164        description = "Specifies the real host name to log into.";
165      };
166
167      serverAliveInterval = mkOption {
168        type = types.int;
169        default = 0;
170        description =
171          "Set timeout in seconds after which response will be requested.";
172      };
173
174      serverAliveCountMax = mkOption {
175        type = types.ints.positive;
176        default = 3;
177        description = ''
178          Sets the number of server alive messages which may be sent
179          without SSH receiving any messages back from the server.
180        '';
181      };
182
183      sendEnv = mkOption {
184        type = types.listOf types.str;
185        default = [];
186        description = ''
187          Environment variables to send from the local host to the
188          server.
189        '';
190      };
191
192      setEnv = mkOption {
193        type = with types; attrsOf (oneOf [ str path int float ]);
194        default = {};
195        description = ''
196          Environment variables and their value to send to the server.
197        '';
198      };
199
200      compression = mkOption {
201        type = types.nullOr types.bool;
202        default = null;
203        description = ''
204          Specifies whether to use compression. Omitted from the host
205          block when `null`.
206        '';
207      };
208
209      checkHostIP = mkOption {
210        type = types.bool;
211        default = true;
212        description = ''
213          Check the host IP address in the
214          {file}`known_hosts` file.
215        '';
216      };
217
218      proxyCommand = mkOption {
219        type = types.nullOr types.str;
220        default = null;
221        description = "The command to use to connect to the server.";
222      };
223
224      proxyJump = mkOption {
225        type = types.nullOr types.str;
226        default = null;
227        description = "The proxy host to use to connect to the server.";
228      };
229
230      certificateFile = mkOption {
231        type = with types; either (listOf str) (nullOr str);
232        default = [];
233        apply = p:
234          if p == null then []
235          else if isString p then [p]
236          else p;
237        description = ''
238          Specifies files from which the user certificate is read.
239        '';
240      };
241
242      addressFamily = mkOption {
243        default = null;
244        type = types.nullOr (types.enum ["any" "inet" "inet6"]);
245        description = ''
246          Specifies which address family to use when connecting.
247        '';
248      };
249
250      localForwards = mkOption {
251        type = types.listOf forwardModule;
252        default = [];
253        example = literalExpression ''
254          [
255            {
256              bind.port = 8080;
257              host.address = "10.0.0.13";
258              host.port = 80;
259            }
260          ];
261        '';
262        description = ''
263          Specify local port forwardings. See
264          {manpage}`ssh_config(5)` for `LocalForward`.
265        '';
266      };
267
268      remoteForwards = mkOption {
269        type = types.listOf forwardModule;
270        default = [];
271        example = literalExpression ''
272          [
273            {
274              bind.port = 8080;
275              host.address = "10.0.0.13";
276              host.port = 80;
277            }
278          ];
279        '';
280        description = ''
281          Specify remote port forwardings. See
282          {manpage}`ssh_config(5)` for `RemoteForward`.
283        '';
284      };
285
286      dynamicForwards = mkOption {
287        type = types.listOf dynamicForwardModule;
288        default = [];
289        example = literalExpression ''
290          [ { port = 8080; } ];
291        '';
292        description = ''
293          Specify dynamic port forwardings. See
294          {manpage}`ssh_config(5)` for `DynamicForward`.
295        '';
296      };
297
298      extraOptions = mkOption {
299        type = types.attrsOf types.str;
300        default = {};
301        description = "Extra configuration options for the host.";
302      };
303    };
304
305#    config.host = mkDefault dagName;
306  });
307
308  matchBlockStr = key: cf: concatStringsSep "\n" (
309    let
310      hostOrDagName = if cf.host != null then cf.host else key;
311      matchHead = if cf.match != null
312        then "Match ${cf.match}"
313        else "Host ${hostOrDagName}";
314    in [ "${matchHead}" ]
315    ++ optional (cf.port != null)            "  Port ${toString cf.port}"
316    ++ optional (cf.forwardAgent != null)    "  ForwardAgent ${lib.hm.booleans.yesNo cf.forwardAgent}"
317    ++ optional cf.forwardX11                "  ForwardX11 yes"
318    ++ optional cf.forwardX11Trusted         "  ForwardX11Trusted yes"
319    ++ optional cf.identitiesOnly            "  IdentitiesOnly yes"
320    ++ optional (cf.user != null)            "  User ${cf.user}"
321    ++ optional (cf.hostname != null)        "  HostName ${cf.hostname}"
322    ++ optional (cf.addressFamily != null)   "  AddressFamily ${cf.addressFamily}"
323    ++ optional (cf.sendEnv != [])           "  SendEnv ${unwords cf.sendEnv}"
324    ++ optional (cf.setEnv != {})            "  SetEnv ${mkSetEnvStr cf.setEnv}"
325    ++ optional (cf.serverAliveInterval != 0)
326      "  ServerAliveInterval ${toString cf.serverAliveInterval}"
327    ++ optional (cf.serverAliveCountMax != 3)
328      "  ServerAliveCountMax ${toString cf.serverAliveCountMax}"
329    ++ optional (cf.compression != null)     "  Compression ${lib.hm.booleans.yesNo cf.compression}"
330    ++ optional (!cf.checkHostIP)            "  CheckHostIP no"
331    ++ optional (cf.proxyCommand != null)    "  ProxyCommand ${cf.proxyCommand}"
332    ++ optional (cf.proxyJump != null)       "  ProxyJump ${cf.proxyJump}"
333    ++ map (file: "  IdentityFile ${file}") cf.identityFile
334    ++ map (file: "  CertificateFile ${file}") cf.certificateFile
335    ++ map (f: "  LocalForward" + addressPort f.bind + addressPort f.host) cf.localForwards
336    ++ map (f: "  RemoteForward" + addressPort f.bind + addressPort f.host) cf.remoteForwards
337    ++ map (f: "  DynamicForward" + addressPort f) cf.dynamicForwards
338    ++ mapAttrsToList (n: v: "  ${n} ${v}") cf.extraOptions
339  );
340
341in
342
343{
344  meta.maintainers = [ maintainers.rycee ];
345
346  options.programs.ssh = {
347    enable = mkEnableOption "SSH client configuration";
348
349    package = mkPackageOption pkgs "openssh" {
350      nullable = true;
351      default = null;
352      extraDescription = "By default, the client provided by your system is used.";
353    };
354
355    forwardAgent = mkOption {
356      default = false;
357      type = types.bool;
358      description = ''
359        Whether the connection to the authentication agent (if any)
360        will be forwarded to the remote machine.
361      '';
362    };
363
364    compression = mkOption {
365      default = false;
366      type = types.bool;
367      description = "Specifies whether to use compression.";
368    };
369
370    serverAliveInterval = mkOption {
371      type = types.int;
372      default = 0;
373      description = ''
374        Set default timeout in seconds after which response will be requested.
375      '';
376    };
377
378    serverAliveCountMax = mkOption {
379      type = types.ints.positive;
380      default = 3;
381      description = ''
382        Sets the default number of server alive messages which may be
383        sent without SSH receiving any messages back from the server.
384      '';
385    };
386
387    hashKnownHosts = mkOption {
388      default = false;
389      type = types.bool;
390      description = ''
391        Indicates that
392        {manpage}`ssh(1)`
393        should hash host names and addresses when they are added to
394        the known hosts file.
395      '';
396    };
397
398    userKnownHostsFile = mkOption {
399      type = types.str;
400      default = "~/.ssh/known_hosts";
401      description = ''
402        Specifies one or more files to use for the user host key
403        database, separated by whitespace. The default is
404        {file}`~/.ssh/known_hosts`.
405      '';
406    };
407
408    controlMaster = mkOption {
409      default = "no";
410      type = types.enum ["yes" "no" "ask" "auto" "autoask"];
411      description = ''
412        Configure sharing of multiple sessions over a single network connection.
413      '';
414    };
415
416    controlPath = mkOption {
417      type = types.str;
418      default = "~/.ssh/master-%r@%n:%p";
419      description = ''
420        Specify path to the control socket used for connection sharing.
421      '';
422    };
423
424    controlPersist = mkOption {
425      type = types.str;
426      default = "no";
427      example = "10m";
428      description = ''
429        Whether control socket should remain open in the background.
430      '';
431    };
432
433    extraConfig = mkOption {
434      type = types.lines;
435      default = "";
436      description = ''
437        Extra configuration.
438      '';
439    };
440
441    extraOptionOverrides = mkOption {
442      type = types.attrsOf types.str;
443      default = {};
444      description = ''
445        Extra SSH configuration options that take precedence over any
446        host specific configuration.
447      '';
448    };
449
450    includes = mkOption {
451      type = types.listOf types.str;
452      default = [];
453      description = ''
454        File globs of ssh config files that should be included via the
455        `Include` directive.
456
457        See
458        {manpage}`ssh_config(5)`
459        for more information.
460      '';
461    };
462
463    matchBlocks = mkOption {
464      type = hm.types.dagOf matchBlockModule;
465      default = {};
466      example = literalExpression ''
467        {
468          "john.example.com" = {
469            hostname = "example.com";
470            user = "john";
471          };
472          foo = lib.hm.dag.entryBefore ["john.example.com"] {
473            hostname = "example.com";
474            identityFile = "/home/john/.ssh/foo_rsa";
475          };
476        };
477      '';
478      description = ''
479        Specify per-host settings. Note, if the order of rules matter
480        then use the DAG functions to express the dependencies as
481        shown in the example.
482
483        See
484        {manpage}`ssh_config(5)`
485        for more information.
486      '';
487    };
488  };
489
490  config = mkIf cfg.enable {
491    assertions = [
492      {
493        assertion =
494          let
495            # `builtins.any`/`lib.lists.any` does not return `true` if there are no elements.
496            any' = pred: items: if items == [] then true else any pred items;
497            # Check that if `entry.address` is defined, and is a path, that `entry.port` has not
498            # been defined.
499            noPathWithPort =  entry: entry.address != null && isPath entry.address -> entry.port == null;
500            checkDynamic = block: any' noPathWithPort block.dynamicForwards;
501            checkBindAndHost = fwd: noPathWithPort fwd.bind && noPathWithPort fwd.host;
502            checkLocal = block: any' checkBindAndHost block.localForwards;
503            checkRemote = block: any' checkBindAndHost block.remoteForwards;
504            checkMatchBlock = block: all (fn: fn block) [ checkLocal checkRemote checkDynamic ];
505          in any' checkMatchBlock (map (block: block.data) (builtins.attrValues cfg.matchBlocks));
506        message = "Forwarded paths cannot have ports.";
507      }
508    ];
509
510    home.packages = optional (cfg.package != null) cfg.package;
511
512    home.file.".ssh/config".text =
513      let
514        sortedMatchBlocks = hm.dag.topoSort cfg.matchBlocks;
515        sortedMatchBlocksStr = builtins.toJSON sortedMatchBlocks;
516        matchBlocks =
517          if sortedMatchBlocks ? result
518          then sortedMatchBlocks.result
519          else abort "Dependency cycle in SSH match blocks: ${sortedMatchBlocksStr}";
520      in ''
521      ${concatStringsSep "\n" (
522        (mapAttrsToList (n: v: "${n} ${v}") cfg.extraOptionOverrides)
523        ++ (optional (cfg.includes != [ ]) ''
524          Include ${concatStringsSep " " cfg.includes}
525        '')
526        ++ (map (block: matchBlockStr block.name block.data) matchBlocks)
527      )}
528
529      Host *
530        ForwardAgent ${lib.hm.booleans.yesNo cfg.forwardAgent}
531        Compression ${lib.hm.booleans.yesNo cfg.compression}
532        ServerAliveInterval ${toString cfg.serverAliveInterval}
533        ServerAliveCountMax ${toString cfg.serverAliveCountMax}
534        HashKnownHosts ${lib.hm.booleans.yesNo cfg.hashKnownHosts}
535        UserKnownHostsFile ${cfg.userKnownHostsFile}
536        ControlMaster ${cfg.controlMaster}
537        ControlPath ${cfg.controlPath}
538        ControlPersist ${cfg.controlPersist}
539
540        ${replaceStrings ["\n"] ["\n  "] cfg.extraConfig}
541    '';
542
543    warnings = mapAttrsToList
544      (n: v: "The SSH config match block `programs.ssh.matchBlocks.${n}` sets both of the host and match options.\nThe match option takes precedence.")
545      (filterAttrs (n: v: v.data.host != null && v.data.match != null) cfg.matchBlocks);
546  };
547}