blob: c0c8c304585048a59ac00e33ba6d274690081393 (
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
|
{
config,
lib,
pkgs,
hosts,
...
}: let
cfg = config.collinux.services.sshd;
anyAttr = attr: cfg.portConfig |> builtins.map (x: x.${attr} != null) |> builtins.any (x: x);
anyOTP = cfg.portConfig |> builtins.map (x: x.otp == true) |> builtins.any (x: x);
authorizedKeys =
hosts
|> builtins.mapAttrs (_: data: data.user_pubkey or null)
|> builtins.attrValues
|> builtins.filter (x: x != null);
in {
config = lib.mkIf cfg.enable {
networking.firewall.allowedTCPPorts = cfg.portConfig |> builtins.map (x: x.port);
services.openssh = {
enable = true;
allowSFTP = false;
hostKeys = [
{
path = "/etc/ssh/ssh_host_ed25519_key";
type = "ed25519";
}
];
listenAddresses =
cfg.portConfig
|> builtins.map (x: {
addr = "0.0.0.0";
port = x.port;
});
# Lock down everything by default
settings = {
PermitRootLogin = "no";
PasswordAuthentication = false;
PubkeyAuthentication = false;
KbdInteractiveAuthentication = false;
AllowAgentForwarding = false;
};
extraConfig =
cfg.portConfig
|> builtins.map (x:
lib.concatStringsSep "\n" [
"Match LocalPort ${toString x.port}"
(
if x.otp
then ''
ChallengeResponseAuthentication yes
PubkeyAuthentication yes
KbdInteractiveAuthentication yes
AuthenticationMethods publickey,keyboard-interactive:pam
''
else ''
PubkeyAuthentication yes
AuthenticationMethods publickey
''
)
(lib.optionalString x.rootLogin "PermitRootLogin yes")
])
|> lib.concatStringsSep "\n\n";
};
security.pam.services = lib.optionalAttrs anyOTP {
login.googleAuthenticator.enable = true;
sshd.text = ''
account required pam_unix.so
auth required ${pkgs.google-authenticator}/lib/security/pam_google_authenticator.so nullok no_increment_hotp
auth sufficient pam_permit.so
session required pam_env.so conffile=/etc/pam/environment readenv=0
session required pam_unix.so
session required pam_loginuid.so
session optional ${pkgs.systemd}/lib/security/pam_systemd.so
'';
};
users.users.${config.collinux.user.name}.openssh.authorizedKeys.keys = authorizedKeys;
users.users."root".openssh.authorizedKeys.keys = lib.mkIf (anyAttr "rootLogin") authorizedKeys;
systemd.services."openssh" = {
after = lib.mkAfter ["network-online.target"];
wants = lib.mkAfter ["network-online.target"];
};
};
}
|