summaryrefslogtreecommitdiff
path: root/modules/nixfiles/openssh.nix
blob: bf470ca290f7b026adc077339c3c853ef79ebcde (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
{
  config,
  lib,
  pkgs,
  ...
}:
with lib; let
  cfg = config.nixfiles.modules.openssh;
in {
  options.nixfiles.modules.openssh = {
    client.enable = mkEnableOption "OpenSSH client";
    server.enable = mkEnableOption "OpenSSH server";
  };

  config = let
    port = 22022; # Port 22 should be occupied by endlessh.
  in
    mkMerge [
      (mkIf cfg.client.enable {
        hm = {
          home.packages = with pkgs; [mosh sshfs];

          programs.ssh = {
            enable = true;

            hashKnownHosts = true;

            controlMaster = "auto";
            controlPersist = "24H";

            serverAliveCountMax = 30;
            serverAliveInterval = 60;

            matchBlocks = let
              mkBlock = name: {
                hostname ? name,
                port ? 22,
                user ? my.username,
                identityFile ? "${config.my.home}/.ssh/id_ed25519",
                extraAttrs ? {},
              }:
                nameValuePair name ({inherit hostname port user identityFile;}
                  // extraAttrs);

              internalServers =
                mapAttrs' mkBlock
                (mapAttrs (name: _: {
                    hostname = "${name}.${my.domain.shire}";
                    inherit port;
                  }) (filterAttrs (_: attr:
                    hasAttr "wireguard" attr
                    && attr.isHeadless)
                  my.configurations));
            in
              internalServers
              // (mapAttrs' mkBlock {
                gitolite = {
                  user = "git";
                  hostname = "git.${my.domain.shire}";
                  inherit port;
                };
              });
          };
        };
      })
      (mkIf cfg.server.enable {
        programs.mosh.enable = true;

        services = {
          openssh = {
            enable = true;
            ports = [port];
            logLevel = "VERBOSE"; # Required by fail2ban.
            permitRootLogin = "no";
            passwordAuthentication = false;
          };

          fail2ban.jails.sshd = ''
            enabled = true
            mode = aggressive
            port = ${toString port}
          '';
        };
      })
    ];
}