2024-08-26 17:38:47 +02:00
|
|
|
# This setups a SSH server.
|
|
|
|
{
|
|
|
|
outputs,
|
|
|
|
config,
|
|
|
|
lib,
|
|
|
|
...
|
|
|
|
}:
|
2023-01-10 02:38:06 +01:00
|
|
|
let
|
|
|
|
# Record containing all the hosts
|
|
|
|
hosts = outputs.nixosConfigurations;
|
|
|
|
|
|
|
|
# Name of the current hostname
|
|
|
|
hostname = config.networking.hostName;
|
|
|
|
|
|
|
|
# Function from hostname to relative path to public ssh key
|
2023-08-17 09:31:46 +02:00
|
|
|
pubKey = host: ../../${host}/keys/ssh_host_ed25519_key.pub;
|
2023-01-10 02:38:06 +01:00
|
|
|
in
|
|
|
|
{
|
|
|
|
services.openssh = {
|
|
|
|
enable = true;
|
|
|
|
|
2023-06-15 20:08:20 +02:00
|
|
|
settings = {
|
2024-08-26 17:38:47 +02:00
|
|
|
PermitRootLogin = lib.mkDefault "no"; # Forbid root login through SSH.
|
|
|
|
PasswordAuthentication = lib.mkDefault false; # Use keys only.
|
2023-06-15 20:08:20 +02:00
|
|
|
};
|
2023-01-10 02:38:06 +01:00
|
|
|
|
|
|
|
# Automatically remove stale sockets
|
|
|
|
extraConfig = ''
|
|
|
|
StreamLocalBindUnlink yes
|
|
|
|
'';
|
|
|
|
|
|
|
|
# Generate ssh key
|
2023-04-27 01:08:20 +02:00
|
|
|
hostKeys =
|
2024-08-26 17:38:47 +02:00
|
|
|
let
|
|
|
|
mkKey =
|
|
|
|
type: path: extra:
|
|
|
|
{ inherit type path; } // extra;
|
2023-04-27 01:08:20 +02:00
|
|
|
in
|
|
|
|
[
|
2023-06-09 13:17:34 +02:00
|
|
|
(mkKey "ed25519" "/persist/state/etc/ssh/ssh_host_ed25519_key" { })
|
|
|
|
(mkKey "rsa" "/persist/state/etc/ssh/ssh_host_rsa_key" { bits = 4096; })
|
2023-04-27 01:08:20 +02:00
|
|
|
];
|
2023-01-10 02:38:06 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
# Add each host in this repo to the knownHosts list
|
|
|
|
programs.ssh = {
|
2023-05-28 02:00:10 +02:00
|
|
|
knownHosts = lib.pipe hosts [
|
|
|
|
# attrsetof host -> attrsetof { ... }
|
|
|
|
(builtins.mapAttrs
|
|
|
|
# string -> host -> { ... }
|
2024-08-26 17:38:47 +02:00
|
|
|
(
|
|
|
|
name: _: {
|
|
|
|
publicKeyFile = pubKey name;
|
|
|
|
extraHostNames = lib.optional (name == hostname) "localhost";
|
|
|
|
}
|
|
|
|
)
|
|
|
|
)
|
2023-05-28 02:00:10 +02:00
|
|
|
|
|
|
|
# attrsetof { ... } -> attrsetof { ... }
|
2023-05-28 05:24:36 +02:00
|
|
|
(lib.attrsets.filterAttrs
|
2023-05-28 02:00:10 +02:00
|
|
|
# string -> { ... } -> bool
|
2024-08-26 17:38:47 +02:00
|
|
|
(_: { publicKeyFile, ... }: builtins.pathExists publicKeyFile)
|
|
|
|
)
|
2023-05-28 02:00:10 +02:00
|
|
|
];
|
2023-01-10 02:38:06 +01:00
|
|
|
};
|
2024-01-18 07:44:16 +01:00
|
|
|
|
2024-04-13 22:42:29 +02:00
|
|
|
# By default, this will ban failed ssh attempts
|
2024-11-09 13:19:49 +01:00
|
|
|
services.fail2ban.enable = lib.mkDefault true;
|
2024-04-13 22:42:29 +02:00
|
|
|
|
2024-01-18 07:44:16 +01:00
|
|
|
# Makes it easy to copy host keys at install time without messing up permissions
|
2024-08-26 23:30:04 +02:00
|
|
|
systemd.tmpfiles.rules = [
|
|
|
|
"d /persist/state/etc/ssh"
|
|
|
|
] ++ (lib.lists.forEach config.services.openssh.hostKeys (key: "e ${key.path} 0700"));
|
2023-01-10 02:38:06 +01:00
|
|
|
}
|