From 49af74ed544e65f7235169f8dd5ceddaa9f18cdb Mon Sep 17 00:00:00 2001 From: Felix Stupp Date: Fri, 16 Aug 2024 13:16:22 +0000 Subject: [PATCH] nixos-mods/improvedDefaults: auto authorize root if no other user is --- .../improvedDefaults/default.nix | 1 + .../improvedDefaults/sshAuthorize.nix | 71 +++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 nix/nixos-modules/improvedDefaults/sshAuthorize.nix diff --git a/nix/nixos-modules/improvedDefaults/default.nix b/nix/nixos-modules/improvedDefaults/default.nix index bb81c16..135606d 100644 --- a/nix/nixos-modules/improvedDefaults/default.nix +++ b/nix/nixos-modules/improvedDefaults/default.nix @@ -12,6 +12,7 @@ in imports = [ ./command-not-found.nix ./powertop-tlp.nix + ./sshAuthorize.nix ./wayland.nix ]; diff --git a/nix/nixos-modules/improvedDefaults/sshAuthorize.nix b/nix/nixos-modules/improvedDefaults/sshAuthorize.nix new file mode 100644 index 0000000..efb743e --- /dev/null +++ b/nix/nixos-modules/improvedDefaults/sshAuthorize.nix @@ -0,0 +1,71 @@ +{ config +, lib +, pkgs +, ... +}: +let + myOpts = config.x-banananetwork; + cfg = config.x-banananetwork.improvedDefaults; +in +{ + + + options = { + + x-banananetwork.improvedDefaults = { + + autoSshAuthorizeRoot = lib.mkEnableOption '' + automatically add option{x-banananetwork.sshPublicKeys} to root’s authorized keys + and enable option{services.openssh.settings.PermitRootLogin} + if no other user has "wheel" power & SSH authorized keys defined. + + Also, option{services.openssh.settings.PermitRootLogin} will be disabled + if this module does not require it. + '' // { default = true; }; + + }; + + }; + + + config = lib.mkIf + (lib.lists.all (x: x) [ + cfg.enable + cfg.autoSshAuthorizeRoot + config.services.openssh.enable + ] + ) + ( + let + inherit (lib.attrsets) attrValues filterAttrs; + inherit (lib.lists) any; + # variables + users = config.users.users; + wheelUsers = lib.trivial.pipe users [ + (filterAttrs (n: v: n != "root")) + (filterAttrs (n: v: builtins.elem "wheel" v.extraGroups)) + ]; + areKeysSet = authKeysOpts: any (x: true) (authKeysOpts.keys ++ authKeysOpts.keyFiles); + isUserAuthed = userOpts: areKeysSet userOpts.openssh.authorizedKeys; + # used facts + isNonRootAuthed = any isUserAuthed (attrValues wheelUsers); + isRootAuthed = isUserAuthed users."root"; + doRootAuth = !isNonRootAuthed; + in + { + + services.openssh.settings.PermitRootLogin = if isRootAuthed then true else lib.mkDefault false; + + users.users.root.openssh.authorizedKeys = lib.mkIf doRootAuth (lib.mkDefault myOpts.sshPublicKeys); + warnings = lib.mkIf doRootAuth [ + '' + root’s authorized keys were automatically configured + because no other user with wheel permission has authorized keys configured + '' + ]; + + } + ); + + +}