Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Security

Platforms: The YubiKey module runs on NixOS and nix-darwin, with the U2F login on NixOS alone. CrowdSec, fail2ban, polkit and sudo are NixOS only. See Darwin.

Security modules under othrys.services.security.*. Located in modules/services/security/.

Available Modules

ModuleOptionDescription
Sudoothrys.services.security.sudosudo with a password for wheel, use_pty and a credential timeout
Polkitothrys.services.security.polkitTurns on polkit and adds no rules
YubiKeyothrys.services.security.yubikeyU2F PAM, GPG agent, SSH keygrips
fail2banothrys.services.security.fail2banIntrusion prevention
CrowdSecothrys.services.security.crowdsecCrowdSec engine + nftables firewall bouncer

YubiKey

  • U2F PAM: password and touch for login, sudo, the greeter, polkit and the lockers
  • GPG agent: YubiKey-backed GPG with SSH support
  • SSH keygrips: Specific GPG keygrips for SSH authentication
  • age-plugin-yubikey: For manual sops secret editing

What the U2F factor actually proves

pam_u2f is inserted into the services named in u2fServices, which are login, sudo, greetd, polkit-1, hyprlock and swaylock by default, and into no other. su and sshd are left out on purpose: su is how root is reached from a console with no key at hand, and sshd authenticates with keys of its own. nixpkgs’ global switch, which puts pam_u2f into every PAM service on the host, is not used.

By default the control is required: the password and the touch must both succeed, and the key is a second factor. That applies to the whole PAM service and not to one user, so every account that authenticates through a listed service needs an enrolled credential, and an account with none is locked out of those services while other accounts keep working. The module refuses the setting while any normal user of the host has no mapping, the primary user and every other account declared with isNormalUser alike. An account that never authenticates through a listed service, such as one reached over SSH alone, is named in u2fExemptUsers and the check passes it over. root is not checked, since su stays off the list as the way to it. Enrol and test a key for every account that logs in, and count service and recovery accounts among them.

othrys.services.security.yubikey.u2fRequirePassword = false switches the control to sufficient: a touch on an enrolled key satisfies the service on its own and no password is asked for. That is authentication by possession alone, so whoever holds the token can become root, and a token left in a laptop is a token in somebody else’s hand. It is a reasonable choice for a personal workstation where the token lives on a keyring and the wrong one for a machine left unattended. An account with no mapping falls through to its password, so nothing is locked out.

On nix-darwin

darwinModules.default carries the module. The GnuPG configuration, the sshcontrol keygrips and the gpg-agent with SSH support are the same Home Manager configuration as on NixOS, and Home Manager runs the agent as the user’s launchd agent. pinentryPackage defaults to pinentry_mac there, and to pinentry-curses on a Mac with othrys.desktop.graphical off. macOS reads the token through its own smart card stack, so there is no pcscd or udev rule to set up. The tools are installed system-wide, without pam_u2f.

The U2F login is NixOS only, and a darwin host with a u2fMappings entry is refused. Touch ID for sudo stays the host’s own choice through security.pam.services.sudo_local.touchIdAuth, since it lets a fingerprint alone pass sudo while u2fRequirePassword defaults to two factors.

Options

  options.othrys.services.security.yubikey = {
    enable = lib.mkEnableOption "YubiKey authentication (U2F + GPG + SSH)";

    # U2F PAM options
    u2fMappings = lib.mkOption {
      # One pamu2fcfg credential: key handle, public key, COSE type and an
      # options field, comma-separated. A colon or a newline would start
      # another user's line in the mappings file.
      type = lib.types.attrsOf (lib.types.listOf (lib.types.strMatching "[A-Za-z0-9+/=_.-]+(,[A-Za-z0-9+/=_.-]*)+"));
      default = {};
      description = ''
        U2F key mappings per user. Generated with:
          pamu2fcfg -n -o pam://yubi

        That command prints each credential with a leading colon, which
        joins it to a user's line in a mappings file. Leave the colon out
        here, since each list entry is one credential.

        Keys are stored in /nix/store (read-only) for security. Any
        non-empty mapping turns pam_u2f on for the services in
        `u2fServices`. NixOS only, and a darwin host refuses a mapping,
        since nix-darwin manages the sudo service alone and othrys puts no
        pam_u2f line there.
      '';
      example = {
        alice = [
          "<KeyHandle1>,<UserKey1>,<CoseType1>,<Options1>"
          "<KeyHandle2>,<UserKey2>,<CoseType2>,<Options2>"
        ];
      };
    };

    u2fOrigin = lib.mkOption {
      type = lib.types.str;
      default = "pam://yubi";
      description = "U2F origin for cross-machine portability.";
    };

    u2fRequirePassword = lib.mkOption {
      type = lib.types.bool;
      default = true;
      description = ''
        Require a password in addition to the touch, rather than accepting the
        touch alone.

        With this on, pam_u2f is inserted as `required` in every service in
        `u2fServices`, so both the password and the touch must succeed and the
        key is a second factor. The control applies to the whole PAM service
        and not to one user, so every account that authenticates through one
        of those services needs an enrolled credential, and an account with
        none is locked out of them while other accounts keep working. Enrol
        and test a key for every such account before turning it on. The
        module refuses the setting while any normal user of the host has no
        mapping, apart from the accounts named in `u2fExemptUsers`.

        With this off, pam_u2f is `sufficient`: a touch on an enrolled key
        satisfies the service with no password, which is authentication by
        possession alone. Whoever holds the token holds root, and a token
        left in a laptop is a token in someone's hand. An account with no
        mapping falls through to its password, so nothing is locked out.
      '';
    };

    u2fExemptUsers = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      default = [];
      example = ["deploy"];
      description = ''
        Normal users that have no entry in `u2fMappings` on purpose. With
        `u2fRequirePassword` on, the module refuses a host where a normal
        user has no mapping, since that account fails every service in
        `u2fServices`. An account that never authenticates through them, such
        as one reached over SSH alone, is named here and the check passes it
        over. It stays locked out of those services.
      '';
    };

    u2fServices = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      default = ["login" "sudo" "greetd" "polkit-1" "hyprlock" "swaylock"];
      description = ''
        PAM services that take the YubiKey, by their names under
        `security.pam.services`. Console login, sudo, the greeter, polkit
        prompts and the two screen lockers by default. `su` and `sshd` are
        left out on purpose: `su` is how root is reached from a console with
        no key at hand, and `sshd` authenticates with keys of its own. A
        service listed here that the host does not run is harmless.
      '';
    };

    # GPG/SSH options
    sshKeygrips = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      default = [];
      description = "GPG keygrips to authorize for SSH authentication.";
      example = ["0123456789ABCDEF0123456789ABCDEF01234567"];
    };

    pinentryPackage = lib.mkOption {
      type = lib.types.package;
      default =
        if !config.othrys.desktop.graphical
        then pkgs.pinentry-curses
        else if pkgs.stdenv.hostPlatform.isDarwin
        then pkgs.pinentry_mac
        else pkgs.pinentry-qt;
      defaultText = lib.literalExpression "pkgs.pinentry-curses unless othrys.desktop.graphical, and on a graphical host pkgs.pinentry_mac on nix-darwin and pkgs.pinentry-qt otherwise";
      description = ''
        Pinentry program for GPG/SSH PIN prompts. A graphical pinentry on a
        headless host cannot render, silently breaking every GPG and SSH
        authentication, which is why the terminal fallback is the default.
      '';
    };
  };

Onboarding & Key Rotation

# New key generation
just yubikey-onboard

# Rotate onto a replacement YubiKey from existing backup
just yubikey-onboard -- --from-backup /mnt/usb/yubikey-backup

# Verify current YubiKey health
just yubikey-onboard -- --verify

The onboarding script handles new key generation, key rotation from backup, multi-key redundancy, and outputs all values needed for the NixOS configuration. See the YubiKey Onboarding guide for full details.

fail2ban

One jail, sshd, which is defined only on a host that runs the OpenSSH server. It reads the journal with the aggressive filter mode and bans an address after maxretry failures within ten minutes. The ban lasts bantime the first time and grows with each repeat up to 48 hours.

The jail names no port of its own. It bans on the ports in services.openssh.ports, so a server moved off port 22 through othrys.services.ssh.server.ports is covered without further configuration. The filter matches more failed logins when sshd logs at VERBOSE, which is the level the SSH module sets.

bantime takes a number of seconds or a number with one of the suffixes s, m, h, d, w, mo and y. Any other string is rejected at evaluation.

The ban database at /var/lib/fail2ban is persisted under impermanence. It holds the active bans and the per-address count that bantime-increment escalates from, so a reboot neither lifts a ban nor resets an offender to the base bantime.

Options

  options.othrys.services.security.fail2ban = {
    enable = lib.mkEnableOption "Fail2ban intrusion prevention";

    maxretry = lib.mkOption {
      type = lib.types.ints.positive;
      default = 5;
      description = "Failures before a ban (applies to the base config and the sshd jail).";
    };

    bantime = lib.mkOption {
      type = lib.types.strMatching "[0-9]+(s|m|h|d|w|mo|y)?";
      default = "10m";
      example = "1h";
      description = ''
        Base ban duration, escalated by bantime-increment up to 48h. A number
        of seconds, or a number with one of the suffixes `s`, `m`, `h`, `d`,
        `w`, `mo` and `y`.
      '';
    };

    ignoreIP = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      default = [
        "127.0.0.1/8"
        "::1"
      ];
      example = [
        "127.0.0.1/8"
        "::1"
        "100.64.0.0/10"
      ];
      description = ''
        Addresses exempt from banning. Loopback only by default. Tailnet
        peers are NOT exempt, since exempting the Tailscale CGNAT range
        (100.64.0.0/10) would let every tailnet node bypass fail2ban (shared
        Headscale, third-party devices). Hosts that fully trust their tailnet
        can add it explicitly.
      '';
    };
  };

CrowdSec

CrowdSec security engine plus its nftables firewall bouncer (both from nixpkgs, with no extra flake input). The engine parses logs and decides, while the bouncer enforces those decisions in nftables. registerBouncer wires the two automatically, so no manual cscli bouncers add is required. A complement to fail2ban: fail2ban bans locally, CrowdSec adds crowd-sourced blocklists.

Central-console enrollment (to pull community blocklists) is a one-time runtime step, cscli console enroll <key> with a key from your secrets provider, left to the fleet. Advanced engine/bouncer configuration is available through the upstream services.crowdsec.* / services.crowdsec-firewall-bouncer.* options.

Under impermanence the module persists /var/lib/crowdsec, which holds the hub, the decision database and the machine credentials, together with /var/lib/crowdsec-firewall-bouncer-register, which holds the bouncer’s API key. The two go together, since the engine database records the bouncer as registered and the register unit refuses to start when that record exists and the key file does not.

The engine runs its own Local API on loopback (127.0.0.1:8080), which is what the agent authenticates against and what the bouncer reads decisions from, machine credentials are minted on first start under /var/lib/crowdsec/state/. On a router host the bouncer’s own chains hook input only, so the module adds a forward hook to the bouncer’s tables there and a banned address is no longer forwarded to the LAN. The engine watches the sshd journal by default and Traefik’s access log when that module is on, which the crowdsec module turns on in JSON; Tailscale SSH has no CrowdSec parser and is not watched, and the module warns when othrys.services.tailscale.ssh is on beside it. Enable openFirewall only if a remote bouncer or a second engine has to reach that API.

Options

  options.othrys.services.security.crowdsec = {
    enable = lib.mkEnableOption "CrowdSec security engine + firewall bouncer";

    collections = lib.mkOption {
      type = lib.types.listOf lib.types.str;
      default = ["crowdsecurity/linux" "crowdsecurity/sshd"];
      description = "CrowdSec hub collections to install (bundle parsers + scenarios).";
    };

    acquisitions = lib.mkOption {
      type = lib.types.listOf (lib.types.attrsOf lib.types.anything);
      default = [
        {
          source = "journalctl";
          journalctl_filter = ["_SYSTEMD_UNIT=sshd.service"];
          labels.type = "syslog";
        }
      ];
      description = ''
        Log sources CrowdSec parses (see the CrowdSec data-sources docs).
        Setting this replaces the curated default outright, including the sshd
        journal source, so list every source the host should watch rather than
        only the ones being added. Traefik's access log is added beside this
        list on a host with `othrys.services.traefik`, and the module turns
        that log on. Tailscale SSH has no CrowdSec parser and is not watched.
      '';
    };

    autoUpdate = lib.mkOption {
      type = lib.types.bool;
      default = true;
      description = "Run `cscli hub update` daily.";
    };

    openFirewall = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = "Open the CrowdSec LAPI port in the firewall.";
    };

    firewallBouncer.enable = lib.mkOption {
      type = lib.types.bool;
      default = true;
      description = "Enable the nftables firewall bouncer that enforces CrowdSec decisions (auto-registered with the local engine).";
    };
  };

Usage

othrys.services.security.crowdsec = {
  enable = true;
  collections = ["crowdsecurity/linux" "crowdsecurity/sshd"];   # default
  firewallBouncer.enable = true;                                 # default
};

Upstream module

nixpkgs rewrote services.crowdsec in October 2026. The rewrite starts on a fresh host without help, so the workarounds this module carried for the old one are gone. Three things remain.

The rewrite moved the data directory from /var/lib/crowdsec/state to /var/lib/crowdsec/data. The module pins the old path, which keeps the decision database, the hub and the machine credentials of a host that ran the old module.

The rewrite also dropped services.crowdsec.openFirewall. The othrys option of that name now opens the port of services.crowdsec.settings.config.api.server.listen_uri itself. Since that address is on loopback by default, the option matters only beside a changed listen_uri.

The hub index is fetched by crowdsec-setup.service, and the engine waits on that unit. After=network-online.target protects boot and nothing else. On a host that resolves through its own othrys.services.unbound, a switch can restart the resolver and the setup unit in one transaction, and the fetch then lands while the resolver is down. The module orders crowdsec-setup.service after unbound.service whenever othrys Unbound is on, which a restart transaction honours. eval-router-services reads that ordering back.

The crowdsec-test VM check boots a fresh machine, runs the update timer and reboots.