Something went wrong. Try again.
forked from nix-community/disko
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399{ config, options, lib, diskoLib, parent, device, ...}:let # These options will automatically generate a temporary password and remove it later on. autogeneratedPassword = config.enrollFido2; luksProbeTarget = if config.settings ? "header" && config.settings.header != null then config.settings.header else config.device;
keyFile = if config.settings ? "keyFile" then config.settings.keyFile else if config.askPassword then ''<(set +x; echo -n "$password"; set -x)'' else if config.passwordFile != null # do not print the password to the console then ''<(set +x; echo -n "$(cat ${config.passwordFile})"; set -x)'' else if config.keyFile != null then lib.warn ( "The option `keyFile` is deprecated." + "Use passwordFile instead if you want to use interactive login or settings.keyFile if you want to use key file login" ) config.keyFile else null;
formatKeyFile = if autogeneratedPassword then ''<(set +x; echo -n "$password"; set -x)'' else keyFile;
generateKeyFileArgs = keyFile: '' ${lib.optionalString (keyFile != null) "--key-file ${keyFile}"} \ ${lib.optionalString (lib.hasAttr "keyFileSize" config.settings) "--keyfile-size ${builtins.toString config.settings.keyFileSize}"} \ ${lib.optionalString (lib.hasAttr "keyFileOffset" config.settings) "--keyfile-offset ${builtins.toString config.settings.keyFileOffset}"} \ '';
# This is the one used for standard one shot formatting and mounting. keyFileArgs = generateKeyFileArgs keyFile; # This is the one used for 2-staged formatting like FIDO2 and NEVER for mounting. formatKeyFileArgs = generateKeyFileArgs formatKeyFile;
# --token-only forces to try FIRST the token then passphrase. createOpenCommand = { keyFileArgs, tokenType ? null, }: '' cryptsetup open "${config.device}" "${config.name}" \ ${lib.optionalString (tokenType != null) "--token-type ${tokenType}"} \ ${lib.optionalString (config.settings.allowDiscards or false) "--allow-discards"} \ ${ lib.optionalString (config.settings.bypassWorkqueues or false ) "--perf-no_read_workqueue --perf-no_write_workqueue" } \ ${toString config.extraOpenArgs} \ ${keyFileArgs} \ '';
# Use this open command when you want to open it after full enrollment, e.g. at mount time or in standard enrollments. cryptsetupOpen = '' ${lib.optionalString config.askPassword '' if [ -z "''${password:-}" ]; then if [ -z ''${IN_DISKO_TEST+x} ]; then set +x echo "Enter password for ${config.device}" IFS= read -r -s password export password set -x else export password=disko fi fi ''} ${createOpenCommand { inherit keyFileArgs; tokenType = if config.enrollFido2 then "systemd-fido2" else null; }} '';
# Use this open command when you want to open it immediately after the formatting and before the stage 2 process is finished (i.e. the wipe slot). formatCryptsetupOpen = createOpenCommand { keyFileArgs = formatKeyFileArgs; };in{ options = { type = lib.mkOption { type = lib.types.enum [ "luks" ]; internal = true; description = "Type"; }; device = lib.mkOption { type = lib.types.str; description = "Device to encrypt"; default = device; }; name = lib.mkOption { type = lib.types.str; description = "Name of the LUKS"; }; keyFile = lib.mkOption { type = lib.types.nullOr diskoLib.optionTypes.absolute-pathname; default = null; description = "DEPRECATED use passwordFile or settings.keyFile. Path to the key for encryption"; example = "/tmp/disk.key"; }; passwordFile = lib.mkOption { type = lib.types.nullOr diskoLib.optionTypes.absolute-pathname; default = null; description = "Path to the file which contains the password for initial encryption"; example = "/tmp/disk.key"; }; askPassword = lib.mkOption { type = lib.types.bool; default = config.keyFile == null && config.passwordFile == null && (!config.settings ? "keyFile") && !autogeneratedPassword; defaultText = "true if neither keyFile nor passwordFile nor enrollFido2 are set"; description = "Whether to ask for a password for initial encryption"; }; enrollFido2 = lib.mkOption { type = lib.types.bool; default = false; description = "Whether to enroll a FIDO2 token and use it"; }; extraFido2EnrollArgs = lib.mkOption { type = lib.types.listOf lib.types.str; default = [ ]; example = [ "--fido2-parameters-in-header=false" ]; description = "Extra arguments to pass to `systemd-cryptenroll` when enrolling the FIDO2 device"; }; enrollRecovery = lib.mkOption { type = lib.types.bool; default = config.enrollFido2; defaultText = "true if fido2 is enabled"; description = "Whether to enroll an automatic (keyboard layout independent) recovery passphrase with high entropy and print a QR code on screen to take it"; }; settings = lib.mkOption { type = lib.types.attrsOf lib.types.anything; default = { }; description = "LUKS settings (as defined in configuration.nix in boot.initrd.luks.devices.<name>)"; example = '' { keyFile = "/tmp/disk.key"; keyFileSize = 2048; keyFileOffset = 1024; fallbackToPassword = true; allowDiscards = true; }; ''; }; additionalKeyFiles = lib.mkOption { type = lib.types.listOf diskoLib.optionTypes.absolute-pathname; default = [ ]; description = "Path to additional key files for encryption"; example = [ "/tmp/disk2.key" ]; }; initrdUnlock = lib.mkOption { type = lib.types.bool; default = true; description = "Whether to add a boot.initrd.luks.devices entry for the specified disk."; }; extraFormatArgs = lib.mkOption { type = lib.types.listOf lib.types.str; default = [ ]; description = "Extra arguments to pass to `cryptsetup luksFormat` when formatting"; example = [ "--pbkdf argon2id" ]; }; extraOpenArgs = lib.mkOption { type = lib.types.listOf lib.types.str; default = [ ]; description = "Extra arguments to pass to `cryptsetup luksOpen` when opening"; example = [ "--timeout 10" ]; }; content = diskoLib.deviceType { parent = config; device = "/dev/mapper/${config.name}"; }; _parent = lib.mkOption { internal = true; default = parent; }; _meta = lib.mkOption { internal = true; readOnly = true; type = lib.types.functionTo diskoLib.jsonType; default = dev: lib.optionalAttrs (config.content != null) (config.content._meta dev); description = "Metadata"; }; _create = diskoLib.mkCreateOption { inherit config options; default = '' if ! cryptsetup isLuks "${luksProbeTarget}"; then ${lib.optionalString config.askPassword '' promptSecret() { prompt=$1 var=$2
echo -n "$prompt" IFS= read -r -s "''${var?}" echo }
askPassword() { if [ -z ''${IN_DISKO_TEST+x} ]; then set +x promptSecret "Enter password for ${config.device}: " password promptSecret "Enter password for ${config.device} again to be safe: " password_check export password # shellcheck disable=SC2154 if [ "$password" != "$password_check" ]; then return 1 fi set -x else export password=disko fi } attempts=0 until askPassword; do attempts=$((attempts + 1)) if [ "$attempts" -ge 3 ]; then echo "Too many mismatched password attempts for ${config.device}, aborting." >&2 exit 1 fi echo "Passwords did not match, please try again." done ''} ${lib.optionalString autogeneratedPassword '' # Generate a random throwable key that will be removed later on. set +x password=$(openssl rand -hex 32) export password set -x
# We have the guarantee that slot 0 needs to be deleted later on. # If the user had set its own password, we wouldn't create this variable # and the script later will not wipe the slot zero. The user keep his password. export SLOT_ZERO_TO_DELETE=true ''} cryptsetup -q luksFormat "${config.device}" ${toString config.extraFormatArgs} ${formatKeyFileArgs}
${formatCryptsetupOpen} \ --persistent fi
# Unlock without relying on the autogenerated password when someone # calls this script after unmounting or rebooting if ! cryptsetup status "${config.name}" >/dev/null; then ${cryptsetupOpen} fi
${toString ( lib.forEach config.additionalKeyFiles (keyFile: '' if ! cryptsetup open --test-passphrase --key-file=${keyFile} "${config.device}" 2>/dev/null; then cryptsetup luksAddKey "${config.device}" ${keyFile} ${formatKeyFileArgs} fi '') )}
${lib.optionalString config.enrollRecovery '' if ! systemd-cryptenroll "${config.device}" 2>/dev/null | grep -qw recovery; then systemd-cryptenroll \ --recovery-key \ --unlock-key-file=${formatKeyFile} \ "${config.device}" if [ -z ''${IN_DISKO_TEST+x} ]; then set +x; read -p "Press Enter when you scanned the QR code offscreen or that the recovery key is stored securely."; set -x fi fi ''} ${lib.optionalString config.enrollFido2 '' if ! systemd-cryptenroll "${config.device}" 2>/dev/null | grep -qw fido2; then wait_for_token() { set +f echo "Waiting for FIDO2 token insertion..."
# Check if any FIDO2 device is available via /dev/hidraw* while true; do if ls /dev/hidraw* &>/dev/null; then echo "FIDO2 device detected." break else echo "FIDO2 device not detected, waiting..." sleep 2 fi done set -f }
wait_for_token systemd-cryptenroll \ --fido2-device=auto \ ''${SLOT_ZERO_TO_DELETE:+--wipe-slot=0} \ --unlock-key-file=${formatKeyFile} \ ${toString config.extraFido2EnrollArgs} \ "${config.device}" fi ''} ${lib.optionalString (config.content != null) config.content._create} ''; }; _mount = diskoLib.mkMountOption { inherit config options; default = let contentMount = config.content._mount; in { dev = '' if ! cryptsetup status "${config.name}" >/dev/null 2>/dev/null; then ${cryptsetupOpen} fi ${lib.optionalString (config.content != null) contentMount.dev or ""} ''; fs = lib.optionalAttrs (config.content != null) contentMount.fs or { }; }; }; _unmount = diskoLib.mkUnmountOption { inherit config options; default = let contentUnmount = config.content._unmount; in { dev = '' ${lib.optionalString (config.content != null) contentUnmount.dev or ""} if cryptsetup status "${config.name}" >/dev/null 2>/dev/null; then cryptsetup close "${config.name}" fi ''; fs = lib.optionalAttrs (config.content != null) contentUnmount.fs or { }; }; }; _config = lib.mkOption { internal = true; readOnly = true; default = [ ] # If initrdUnlock is true, then add a device entry to the initrd.luks.devices config. ++ (lib.optional config.initrdUnlock [ { boot.initrd.luks.devices.${config.name} = { inherit (config) device; crypttabExtraOpts = lib.mkIf config.enrollFido2 [ "fido2-device=auto" ]; } // config.settings;
# If FIDO2 is used, systemd stage 1 is absolutely necessary. # Should we turn this into an assertion? boot.initrd.systemd.enable = lib.mkIf config.enrollFido2 true; } ]) ++ (lib.optional (config.content != null) config.content._config); description = "NixOS configuration"; }; _pkgs = lib.mkOption { internal = true; readOnly = true; type = lib.types.functionTo (lib.types.listOf lib.types.package); default = pkgs: [ pkgs.gnugrep pkgs.openssl pkgs.systemd # We make cryptsetup aware of token libraries from systemd. # We do not have a lot of nice ways to do this... (pkgs.runCommand pkgs.cryptsetup.name { nativeBuildInputs = [ pkgs.makeWrapper ]; } '' mkdir -p $out/bin/ makeWrapper ${pkgs.cryptsetup.bin}/bin/cryptsetup $out/bin/cryptsetup \ --prefix LD_LIBRARY_PATH : ${pkgs.systemd}/lib/cryptsetup '' ) ] ++ (lib.optionals (config.content != null) (config.content._pkgs pkgs)); description = "Packages"; }; };}