nixos-config/lib/fudo/ssh.nix

82 lines
2.4 KiB
Nix
Raw Normal View History

2021-09-29 17:55:13 -07:00
{ config, lib, pkgs, ... }:
with lib;
let
2021-09-29 18:44:33 -07:00
hostname = config.instance.hostname;
2021-09-29 17:55:13 -07:00
has-attrs = set: length (attrNames set) > 0;
2021-09-29 18:44:33 -07:00
host-keypairs =
if (hasAttr hostname config.fudo.secrets.files.host-ssh-keypairs) then
config.fudo.secrets.files.host-ssh-keypairs.${hostname}
else [];
2021-09-29 17:55:13 -07:00
sshfp-filename = host: keypair: "ssh-${host}-${keypair.key-type}.sshfp-record";
dns-sshfp-records = host: keypair: let
filename = sshfp-filename host keypair;
2021-09-30 08:40:47 -07:00
in pkgs.stdenv.mkDerivation {
name = "${host}-sshfp-record";
2021-09-29 17:55:13 -07:00
2021-09-30 08:40:47 -07:00
phases = [ "installPhase" ];
buildInputs = with pkgs; [ openssh ];
2021-09-29 17:55:13 -07:00
installPhase = ''
2021-09-30 08:40:47 -07:00
mkdir $out
ssh-keygen -r REMOVEME -f "${keypair.public-key}" | sed 's/^REMOVEME IN SSHFP //' > $out/${filename}
2021-09-29 17:55:13 -07:00
'';
};
2021-09-30 11:30:32 -07:00
host-cfg = config.fudo.hosts.${hostname};
2021-09-29 17:55:13 -07:00
in {
config = {
fudo = {
2021-09-29 18:44:33 -07:00
secrets.host-secrets.${hostname} = listToAttrs
(map
(keypair: nameValuePair "host-${keypair.key-type}-private-key" {
2021-09-29 17:55:13 -07:00
source-file = keypair.private-key;
target-file = "/var/run/ssh/private/host-${keypair.key-type}-private-key";
user = "root";
2021-09-29 18:44:33 -07:00
})
host-keypairs);
2021-09-29 17:55:13 -07:00
hosts = mapAttrs (hostname: keypairs: {
ssh-pubkeys = map (keypair: keypair.public-key) keypairs;
ssh-fingerprints = map (keypair:
let
2021-09-30 08:40:47 -07:00
fingerprint-derivation = dns-sshfp-records hostname keypair;
2021-09-29 17:55:13 -07:00
filename = sshfp-filename hostname keypair;
in builtins.readFile "${fingerprint-derivation}/${filename}") keypairs;
2021-09-29 18:44:33 -07:00
}) config.fudo.secrets.files.host-ssh-keypairs;
2021-09-29 17:55:13 -07:00
};
2021-09-29 18:44:33 -07:00
services.openssh.hostKeys = map (keypair: {
path = "/var/run/ssh/private/host-${keypair.key-type}-private-key";
type = keypair.key-type;
}) host-keypairs;
2021-09-29 17:55:13 -07:00
2021-09-30 08:40:47 -07:00
programs.ssh.knownHosts = let
keyed-hosts =
filterAttrs (h: o: o.ssh-pubkeys != [])
config.fudo.hosts;
crossProduct = f: list0: list1:
concatMap (el0: map (el1: f el0 el1) list1) list0;
2021-09-30 11:30:32 -07:00
all-hostnames = hostname: opts:
[ hostname ] ++
2021-09-30 08:40:47 -07:00
(crossProduct (host: domain: "${host}.${domain}")
2021-09-30 11:30:32 -07:00
([ hostname ] ++ opts.aliases)
2021-09-30 08:40:47 -07:00
([ opts.domain ] ++ opts.extra-domains));
in mapAttrs (hostname: hostOpts: {
publicKeyFile = builtins.head hostOpts.ssh-pubkeys;
2021-09-30 11:30:32 -07:00
hostNames = all-hostnames hostname host-cfg;
2021-09-30 08:40:47 -07:00
}) keyed-hosts;
2021-09-29 17:55:13 -07:00
};
}