{ config, lib, pkgs, ... }: let cfg = config.nixfiles.modules.openssh; in { options.nixfiles.modules.openssh = { client.enable = lib.mkEnableOption "OpenSSH client"; server = { enable = lib.mkEnableOption "OpenSSH server"; port = lib.mkOption { description = "OpenSSH server port."; type = lib.types.port; default = 22022; # Port 22 should be occupied by a tarpit. }; }; }; config = lib.mkMerge [ (lib.mkIf cfg.client.enable { hm = { home.packages = with pkgs; [ mosh sshfs sshpass ]; programs.ssh = { enable = true; hashKnownHosts = true; controlMaster = "auto"; controlPersist = "24H"; serverAliveCountMax = 30; serverAliveInterval = 60; matchBlocks = let mkBlock = name: { hostname ? name, port ? 22022, # NOTE This is not the default OpenSSH port. user ? lib.my.username, identityFile ? "${config.my.home}/.ssh/${lib.my.username}_${lib.my.ssh.type}", extraAttrs ? { }, }: lib.nameValuePair name ( { inherit hostname port user identityFile ; } // extraAttrs ); internalServers = lib.mapAttrs' mkBlock ( lib.mapAttrs (name: _: { hostname = "${name}.${lib.my.domain.shire}"; }) ( lib.filterAttrs (_: attr: lib.hasAttr "wireguard" attr && attr.isHeadless) lib.my.configurations ) ); in internalServers // (lib.mapAttrs' mkBlock { gitolite = { user = "git"; hostname = "git.${lib.my.domain.shire}"; }; }); }; }; }) (lib.mkIf cfg.server.enable { ark.files = [ "/etc/ssh/ssh_host_ed25519_key" "/etc/ssh/ssh_host_ed25519_key.pub" "/etc/ssh/ssh_host_rsa_key" "/etc/ssh/ssh_host_rsa_key.pub" ]; programs.mosh.enable = true; services = { openssh = { enable = true; ports = [ cfg.server.port ]; settings = { ClientAliveCountMax = 3; ClientAliveInterval = 60; KbdInteractiveAuthentication = false; MaxAuthTries = 3; PasswordAuthentication = false; PermitRootLogin = lib.mkForce "no"; }; }; fail2ban.jails.sshd = { enabled = true; settings = { mode = "aggressive"; inherit (cfg.server) port; }; }; }; }) ]; }