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

YubiKey Onboarding

Interactive script for provisioning one or more YubiKeys with PGP keys, U2F credentials, and age identity for sops-nix. Supports both new key generation and key rotation from an existing backup. Follows drduh’s YubiKey Guide.

Quick Start

# New key generation
just yubikey-onboard

# Key rotation from the backup directory a previous run left
just yubikey-onboard -- --from-backup /mnt/usb/yubikey-backup

# Health check on currently inserted YubiKey
just yubikey-onboard -- --verify

Options

Modes

FlagDescription
(default)Generate new PGP keys and provision YubiKey(s)
--from-backup <path>Import an existing master key and provision YubiKey(s) (key rotation). The path is a backup directory, master-secret.key.age, master-secret.key.pass.age or a plaintext master-secret.key
--verifyCheck the currently inserted YubiKey’s health and config

Key Identity

FlagDescription
--name <name>Real name for the PGP key
--email <email>Email address for the PGP key
--expiry <duration>Subkey expiry period (default: 2y)

Name and email have no defaults. Both are prompted for when the flag is absent, and an empty answer is refused, since the pair becomes a permanent PGP identity.

Provisioning

FlagDescription
--backup-dir <path>Master key backup directory (required, skips the prompt)
--force-volatileAllow a backup directory the host may not persist
--no-passphraseLeave the master key unprotected (escape hatch)
--algo <algorithm>Force key algorithm: ed25519 or rsa4096 (auto-detected by default)
--key-count <n>Number of YubiKeys to provision (skips the “provision another?” prompt)
--allow-default-pinsFinish even when a PIN, PUK or management key was not changed in this run
--age-identity <file>age identity file that opens master-secret.key.age for --from-backup (default: the YubiKey in the reader)
--dry-runWalk through all phases. Touches no YubiKey and no keyring, and writes no file

The backup directory has no default either. It used to offer /tmp/yubikey-backup-<date>, which is predictable, unencrypted, and on most hosts does not survive a reboot, so pressing Enter put the only copy of a master key somewhere it could vanish. The script refuses a target that looks volatile, by filesystem type or by path, and --force-volatile overrides that for an operator who knows the location is kept.

A dry run reads no token, so the serial it prints is the word dry-run and the firmware is assumed to be current. It prints the directory a real run would save its summary under and creates nothing there.

Encrypted Backup

FlagDescription
--age-recipient <r>Extra age recipient for the token copies, repeatable
--no-age-passphraseSkip the passphrase-encrypted copies
--keep-plaintextKeep the plaintext exports after the encrypted copies verify
--no-age-backupDo not produce encrypted copies at all

Examples

# Preview the full workflow without touching the YubiKey
just yubikey-onboard -- --dry-run

# Non-interactive new key generation for 2 YubiKeys
just yubikey-onboard -- --name "alice" --email "alice@example.com" \
  --expiry 2y --backup-dir /mnt/usb/backup --key-count 2

# Rotate from the passphrase copy, which needs no token to open
just yubikey-onboard -- --from-backup /mnt/usb/backup/master-secret.key.pass.age

# Rotate from the token copy, opened by a YubiKey provisioned earlier
just yubikey-onboard -- --from-backup /mnt/usb/backup/master-secret.key.age

# The same, opened by an age identity file instead of a token
just yubikey-onboard -- --from-backup /mnt/usb/backup/master-secret.key.age \
  --age-identity /mnt/usb/offline-identity.txt

# Rotate a token whose PINs were set on an earlier day and stay as they are
just yubikey-onboard -- --from-backup /mnt/usb/backup --allow-default-pins

# Force RSA 4096 for an older YubiKey
just yubikey-onboard -- --algo rsa4096

Nix Package

The script is packaged as a Nix derivation at flake/packages.nix and exposed as packages.<system>.yubikey-onboard for x86_64-linux and aarch64-linux. All runtime dependencies (gnupg, yubikey-manager, pam_u2f, age, age-plugin-yubikey, ssh-to-age, pinentry-curses, openssh, util-linux) are pinned via the flake lockfile. Building the package runs shellcheck over the script, and the yubikey-onboard-builds check builds it in CI.

# Via justfile (recommended)
just yubikey-onboard

# Via nix run directly
nix run .#yubikey-onboard

# With arguments
nix run .#yubikey-onboard -- --verify

Prerequisites

  • A YubiKey 5 series (firmware 5.2.3+ for ed25519, older keys fall back to RSA 4096)
  • Removable media for master key backup (new key mode) or the existing backup (rotation mode)

Workflow

The script generates PGP keys once (or imports from backup), then provisions one or more YubiKeys with the same subkeys for redundancy. After the first YubiKey is provisioned, the script prompts to provision additional keys, restoring the subkeys from backup between each keytocard pass.

PhaseRunsDescription
0OncePreflight, verify tools, detect YubiKey firmware
1OncePGP Key Generation or Import from Backup
2OnceMaster Key Backup (skipped in --from-backup mode)
3-6Per keyProvision YubiKey, reset, keytocard and its verification, PINs for OpenPGP and PIV, U2F, age identity
7OnceSSH Keygrip, extract authentication subkey keygrip
8OncePublic Key Import, import into persistent keyring
9OnceEncrypted Backup, age-encrypt the master key and subkeys exports and remove the plaintext
10OnceSummary, print all values for NixOS config

Phase Details

Phase 0: Preflight Checks

Verifies required tools are available, detects the YubiKey (serial and firmware), and determines the key algorithm. The --algo flag overrides auto-detection.

phase_preflight() {
  header "Phase 0: Preflight Checks"

  # Check required tools
  local tools=("gpg" "ykman" "pamu2fcfg" "age" "age-plugin-yubikey" "ssh-to-age")
  local missing=()
  for tool in "${tools[@]}"; do
    if ! command -v "$tool" &>/dev/null; then
      missing+=("$tool")
    fi
  done

  if [[ ${#missing[@]} -gt 0 ]]; then
    error "Missing required tools: ${missing[*]}"
    echo "  These should be available when othrys.services.security.yubikey.enable = true"
    echo "  You can also run: nix shell nixpkgs#{${missing[*]// /,}}"
    exit 1
  fi
  success "All required tools found."

  # Detect initial YubiKey (for firmware/algorithm check)
  check_yubikey
  read_yubikey
  local firmware="$CURRENT_FIRMWARE"

  if $DRY_RUN; then
    dry_run_skip "ykman info (assuming firmware $firmware)"
  else
    info "YubiKey detected:"
    echo "  Serial:   $CURRENT_SERIAL"
    echo "  Firmware: ${firmware:-unreported}"
  fi

  # Determine key algorithm
  if [[ -z $firmware && -z $OPT_ALGO ]]; then
    error "This token reports no firmware version, so the key algorithm cannot be chosen."
    error "Pass --algo ed25519 or --algo rsa4096 to choose one."
    exit 1
  elif [[ -n $OPT_ALGO ]]; then
    KEY_ALGO="$OPT_ALGO"
    info "Algorithm forced via --algo: $KEY_ALGO"
    if [[ $KEY_ALGO == "ed25519" && -n $firmware ]] && ! version_gte "$firmware" "$MIN_ECC_FIRMWARE"; then
      warn "Firmware $firmware may not support ed25519 (requires >= $MIN_ECC_FIRMWARE)."
      warn "Proceeding anyway as --algo was explicitly set."
    fi
  elif version_gte "$firmware" "$MIN_ECC_FIRMWARE"; then
    success "Firmware supports ed25519/cv25519."
    KEY_ALGO="ed25519"
  else
    warn "Firmware $firmware does not support ed25519 (requires >= $MIN_ECC_FIRMWARE)."
    warn "Falling back to RSA 4096."
    KEY_ALGO="rsa4096"
  fi
}

Phase 1: PGP Key Generation

Generates a master key (Certify only) and three subkeys (Sign, Encrypt, Authenticate) in a temporary GNUPGHOME on ramfs, so the key never touches persistent storage or swap. See Security Notes for the fallback when unprivileged user namespaces are unavailable.

The temporary GPG environment uses a hardened gpg.conf matching the settings in modules/services/security/yubikey.nix and pinentry-curses for terminal PIN entry.

The --name, --email, and --expiry flags skip the interactive prompts. Name and email are refused if empty.

The phase ends by setting a passphrase on the master key, through gpg-agent’s own pinentry on the same terminal. It will not advance to the backup phase while the key is unprotected unless --no-passphrase was given.

phase_generate_keys() {
  header "Phase 1: PGP Master Key Generation"

  info "Master key will be generated in a temporary GNUPGHOME held in memory."
  echo ""

  # Prompt for key details (skip if provided via CLI)
  local real_name email expiry
  if [[ -n $OPT_NAME ]]; then
    real_name="$OPT_NAME"
  else
    real_name=$(prompt_required "Real name for the key")
  fi
  if [[ -n $OPT_EMAIL ]]; then
    email="$OPT_EMAIL"
  else
    email=$(prompt_required "Email address")
  fi
  if [[ -n $OPT_EXPIRY ]]; then
    expiry="$OPT_EXPIRY"
  else
    expiry=$(prompt_value "Subkey expiry (e.g., 2y, 1y, 6m)" "$DEFAULT_EXPIRY")
  fi
  info "Key identity: $real_name <$email> (subkey expiry: $expiry)"

  setup_gnupghome

  if $DRY_RUN; then
    dry_run_skip "gpg --quick-gen-key \"$real_name <$email>\" $KEY_ALGO cert never"
    KEY_FINGERPRINT="DRY_RUN_FINGERPRINT_0000000000000000"
    dry_run_skip "gpg --quick-add-key (Sign, Encrypt, Authenticate subkeys)"
    info "Would generate master key + 3 subkeys with algorithm: $KEY_ALGO"
    info "Subkey expiry: $expiry"
    return
  fi

  info "Generating master key (Certify only)..."

  if [[ $KEY_ALGO == "ed25519" ]]; then
    gpg --batch --passphrase '' --quick-gen-key "$real_name <$email>" ed25519 cert never
  else
    gpg --batch --passphrase '' --quick-gen-key "$real_name <$email>" rsa4096 cert never
  fi

  # Get the fingerprint
  KEY_FINGERPRINT=$(gpg --list-keys --with-colons "$email" 2>/dev/null |
    awk -F: '/^fpr:/ {print $10; exit}')

  if [[ -z $KEY_FINGERPRINT ]]; then
    error "Failed to retrieve key fingerprint."
    exit 1
  fi

  success "Master key generated: $KEY_FINGERPRINT"

  # Generate subkeys
  info "Generating subkeys (Sign, Encrypt, Authenticate) with expiry: $expiry..."

  if [[ $KEY_ALGO == "ed25519" ]]; then
    gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" ed25519 sign "$expiry"
    gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" cv25519 encr "$expiry"
    gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" ed25519 auth "$expiry"
  else
    gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" rsa4096 sign "$expiry"
    gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" rsa4096 encr "$expiry"
    gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" rsa4096 auth "$expiry"
  fi

  success "Subkeys generated."
  echo ""
  gpg --list-keys --with-keygrip "$KEY_FINGERPRINT"

  echo ""
  set_master_passphrase
}

# Returns 0 when the master secret key on disk is passphrase-protected.
#
# gpg-agent's KEYINFO reports the protection state in field 8 of its S line,
# `C` for a key stored in the clear and `P` for a protected one. Verified
# against a freshly generated key both ways. This asks the agent about what is
# actually on disk rather than trusting that a passphrase dialog was completed,
# so it holds however the passphrase was set.
master_key_is_protected() {
  local grip
  grip=$(gpg --list-secret-keys --with-keygrip --with-colons "$KEY_FINGERPRINT" 2>/dev/null |
    awk -F: '/^grp/{print $10; exit}')
  [[ -n $grip ]] || return 1
  gpg-connect-agent "KEYINFO $grip" /bye 2>/dev/null |
    awk '/^S KEYINFO/{exit ($8 == "P") ? 0 : 1}'
}

# The master key and its subkeys are generated with --passphrase '', so until
# this runs the only copy of the identity is unprotected. This used to print a
# command to run in a second terminal followed by "Press Enter when done (or
# skip)", which advanced to the backup phase whether or not anything happened.
#
# Entry goes through gpg-agent's own pinentry on this terminal, so the
# passphrase lives in the agent's mlocked memory and never reaches a shell
# variable, the process environment or a trace. The gate below re-reads the
# on-disk state afterwards, so a cancelled or failed dialog cannot pass.
set_master_passphrase() {
  if $OPT_NO_PASSPHRASE; then
    warn "--no-passphrase given: the master key backup will be unprotected."
    warn "Anyone who reads the backup file holds your identity."
    return 0
  fi

  if $DRY_RUN; then
    dry_run_skip "gpg --edit-key $KEY_FINGERPRINT passwd"
    return 0
  fi

  warn "The master key is currently unprotected. Set a passphrase now."
  warn "It protects the backup, which is the only copy once subkeys move to the"
  warn "YubiKey and cannot be extracted again."
  echo ""

  while ! master_key_is_protected; do
    gpg --edit-key "$KEY_FINGERPRINT" passwd || true
    if master_key_is_protected; then
      break
    fi
    error "The master key is still unprotected."
    if prompt_yn "Try again?" "y"; then
      continue
    fi
    if prompt_yn "Continue with an UNPROTECTED master key?"; then
      warn "Proceeding with an unprotected master key at your request."
      return 0
    fi
    error "Refusing to continue to backup with an unprotected master key."
    error "Re-run with --no-passphrase if that is genuinely what you want."
    exit 1
  done

  success "Master key is passphrase-protected."
}

Phase 1 (alternate): Import from Backup

When --from-backup is used, the script imports an existing master key instead of generating a new one. It offers to generate fresh subkeys (recommended for rotation) or reuse the existing ones from the backup.

A default run leaves no plaintext behind, so the usual input is one of the two encrypted copies. The path may name either file, or the directory that holds them:

InputOpened with
master-secret.key.pass.agethe backup passphrase, which age asks for
master-secret.key.agean identity file given with --age-identity or at the prompt, or the YubiKey in the reader through age-plugin-yubikey
master-secret.keynothing, since it is plaintext

Given a directory, the script takes a plaintext master-secret.key when one is there, and otherwise asks which encrypted copy to open when both exist. The token copy opens only with a YubiKey that was provisioned when the backup was written, so a rotation onto a blank replacement token starts from the passphrase copy, or from the token copy with an older token in the reader first. The script pauses after decryption so that the tokens can be swapped.

An encrypted backup is decrypted into the ramfs GNUPGHOME and nowhere else. When fresh subkeys are generated, the new exports are written in the ramfs as well, and the encrypted backup phase writes the new copies to the backup directory. No plaintext reaches the medium in that flow. A plaintext input stays where it is during the run, and the encrypted backup phase encrypts and removes it at the end.

Every file the rotation replaces is written beside its target as <target>.new, read back, and moved into place only after that. A failed or cancelled export leaves the existing backup as it was. The new token copy is encrypted to the YubiKeys provisioned in this run and to any --age-recipient, and the recipients of the copy it replaces are not carried over, so a token from an earlier run keeps opening the backup only when its recipient is passed again.

This mode is intended for:

  • Key rotation. Expired subkeys, generate new ones from the same master
  • Replacement YubiKey. Lost/damaged key, provision a new one with existing subkeys
# What a backup file is. age opens a file with a text header whose second line
# names the first recipient stanza, and `scrypt` there means a passphrase.
backup_form() {
  local file="$1" first="" second=""
  {
    IFS= read -r first || true
    IFS= read -r second || true
  } <"$file" 2>/dev/null
  if [[ $first == "age-encryption.org/v1" || $file == *.age ]]; then
    if [[ $second == "-> scrypt "* || $file == *.pass.age ]]; then
      echo "age-passphrase"
    else
      echo "age-recipient"
    fi
  else
    echo "plaintext"
  fi
}

# Decrypt an encrypted backup to a file inside the ramfs GNUPGHOME. The
# passphrase copy needs nothing but the passphrase. The token copy needs an
# identity, which is a file named with --age-identity or at the prompt, or the
# YubiKey in the reader through age-plugin-yubikey.
decrypt_backup() {
  local source="$1" form="$2" dest="$3"
  local idfile="$OPT_AGE_IDENTITY" rc=0

  if [[ $form == "age-passphrase" ]]; then
    info "Decrypting $source. age asks for the backup passphrase."
    age -d -o "$dest" "$source"
    return
  fi

  if [[ -z $idfile ]]; then
    idfile=$(prompt_value "age identity file that opens it (empty to use the YubiKey in the reader)" "")
  fi
  if [[ -n $idfile ]]; then
    if [[ ! -f $idfile ]]; then
      error "No such identity file: $idfile"
      return 1
    fi
    age -d -i "$idfile" -o "$dest" "$source"
    return
  fi

  idfile="$GNUPGHOME/age-identities"
  release_card
  age-plugin-yubikey --identity >"$idfile" 2>/dev/null || true
  if ! grep -q "^AGE-PLUGIN-YUBIKEY-" "$idfile"; then
    rm -f "$idfile"
    error "The YubiKey in the reader holds no age identity."
    return 1
  fi
  info "Decrypting $source (this needs the inserted YubiKey's PIN and a touch)..."
  age -d -i "$idfile" -o "$dest" "$source" || rc=$?
  rm -f "$idfile"
  return "$rc"
}

phase_import_from_backup() {
  header "Importing Master Key from Backup"

  local backup_path="$OPT_FROM_BACKUP"

  # Validate backup path
  if [[ ! -f $backup_path && ! -d $backup_path ]]; then
    error "Backup path does not exist: $backup_path"
    exit 1
  fi

  # If a directory was given, look for the master key file inside it. A
  # plaintext export comes first because it needs nothing to open. A default
  # run leaves only the two encrypted copies.
  local key_file="$backup_path"
  if [[ -d $backup_path ]]; then
    if [[ -f "$backup_path/master-secret.key" ]]; then
      key_file="$backup_path/master-secret.key"
    elif [[ -f "$backup_path/master-secret.key.pass.age" && -f "$backup_path/master-secret.key.age" ]]; then
      if prompt_yn "Open the passphrase copy? Answer no to open the YubiKey copy." "y"; then
        key_file="$backup_path/master-secret.key.pass.age"
      else
        key_file="$backup_path/master-secret.key.age"
      fi
    elif [[ -f "$backup_path/master-secret.key.pass.age" ]]; then
      key_file="$backup_path/master-secret.key.pass.age"
    elif [[ -f "$backup_path/master-secret.key.age" ]]; then
      key_file="$backup_path/master-secret.key.age"
    else
      error "No master-secret.key, master-secret.key.age or master-secret.key.pass.age in $backup_path"
      error "Expected a file produced by a previous onboarding run."
      exit 1
    fi
    # The directory takes the updated backup and the summary.
    BACKUP_DIR="$backup_path"
  else
    BACKUP_DIR="$(dirname "$backup_path")"
  fi

  local form
  form=$(backup_form "$key_file")

  info "Importing master key from: $key_file"

  setup_gnupghome

  # An encrypted backup is decrypted into the ramfs, and every plaintext export
  # of this run stays there. A plaintext backup is already on the medium, so its
  # exports stay beside it until the encrypted backup phase removes them.
  local source="$key_file"
  if [[ $form == "plaintext" ]]; then
    MASTER_PLAINTEXT="$BACKUP_DIR/master-secret.key"
    SUBKEYS_PLAINTEXT="$BACKUP_DIR/subkeys-secret.key"
  else
    MASTER_PLAINTEXT="$GNUPGHOME/master-secret.key"
    SUBKEYS_PLAINTEXT="$GNUPGHOME/subkeys-secret.key"
    key_file="$MASTER_PLAINTEXT"
  fi

  if $DRY_RUN; then
    if [[ $form != "plaintext" ]]; then
      dry_run_skip "age -d $source (into the ramfs)"
    fi
    dry_run_skip "gpg --import $key_file"
    KEY_FINGERPRINT="DRY_RUN_FINGERPRINT_0000000000000000"
    info "Would import master key and list existing subkeys."
    return
  fi

  if [[ $form == "plaintext" ]]; then
    warn "$source is not encrypted. It stays on the medium until the encrypted"
    warn "backup phase at the end of this run."
  else
    if ! decrypt_backup "$source" "$form" "$key_file" || [[ ! -s $key_file ]]; then
      error "Could not decrypt $source. Nothing was changed."
      exit 1
    fi
    success "Backup decrypted into the temporary GNUPGHOME."
    if [[ $form == "age-recipient" ]]; then
      info "If the YubiKey to provision is not the one in the reader, insert it now."
      read -rp "$(echo -e "${BOLD}Press Enter to continue...${NC}")" || true
    fi
  fi

  # Import the master key
  gpg --batch --import "$key_file" 2>/dev/null || {
    error "Failed to import master key from $key_file"
    exit 1
  }

  # Get the fingerprint (first key in the keyring)
  KEY_FINGERPRINT=$(gpg --list-keys --with-colons 2>/dev/null |
    awk -F: '/^fpr:/ {print $10; exit}')

  if [[ -z $KEY_FINGERPRINT ]]; then
    error "Failed to retrieve key fingerprint after import."
    exit 1
  fi

  success "Master key imported: $KEY_FINGERPRINT"
  echo ""
  gpg --list-keys --with-keygrip "$KEY_FINGERPRINT"

  # Check if subkeys exist and offer to generate new ones
  local subkey_count regenerated=false
  subkey_count=$(gpg --list-keys --with-colons "$KEY_FINGERPRINT" 2>/dev/null |
    grep -c "^sub:" || true)

  if [[ $subkey_count -ge 3 ]]; then
    info "Found $subkey_count existing subkeys."
    if prompt_yn "Generate fresh subkeys (recommended for rotation)?" "y"; then
      local expiry
      if [[ -n $OPT_EXPIRY ]]; then
        expiry="$OPT_EXPIRY"
      else
        expiry=$(prompt_value "New subkey expiry (e.g., 2y, 1y, 6m)" "$DEFAULT_EXPIRY")
      fi

      info "Generating new subkeys with expiry: $expiry..."
      if [[ $KEY_ALGO == "ed25519" ]]; then
        gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" ed25519 sign "$expiry"
        gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" cv25519 encr "$expiry"
        gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" ed25519 auth "$expiry"
      else
        gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" rsa4096 sign "$expiry"
        gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" rsa4096 encr "$expiry"
        gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" rsa4096 auth "$expiry"
      fi
      success "New subkeys generated."
      regenerated=true
      echo ""
      gpg --list-keys --with-keygrip "$KEY_FINGERPRINT"
    else
      info "Using existing subkeys from backup."
    fi
  elif [[ $subkey_count -eq 0 ]]; then
    warn "No subkeys found in backup. Generating new subkeys..."
    local expiry
    if [[ -n $OPT_EXPIRY ]]; then
      expiry="$OPT_EXPIRY"
    else
      expiry=$(prompt_value "Subkey expiry (e.g., 2y, 1y, 6m)" "$DEFAULT_EXPIRY")
    fi

    if [[ $KEY_ALGO == "ed25519" ]]; then
      gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" ed25519 sign "$expiry"
      gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" cv25519 encr "$expiry"
      gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" ed25519 auth "$expiry"
    else
      gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" rsa4096 sign "$expiry"
      gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" rsa4096 encr "$expiry"
      gpg --batch --passphrase '' --quick-add-key "$KEY_FINGERPRINT" rsa4096 auth "$expiry"
    fi
    success "Subkeys generated."
    regenerated=true
    echo ""
    gpg --list-keys --with-keygrip "$KEY_FINGERPRINT"
  else
    info "Found $subkey_count subkey(s). Proceeding with existing subkeys."
  fi

  if $regenerated; then
    # The key has changed, so the exports follow it. Each is written beside its
    # target as <target>.new and moved into place after it has been read back,
    # so a failed export leaves the existing backup as it was.
    export_verified master "$MASTER_PLAINTEXT" || abort_run "The updated master key could not be exported."
    export_verified subkeys "$SUBKEYS_PLAINTEXT" || abort_run "The updated subkeys could not be exported."
    export_verified public "$BACKUP_DIR/public.key" || abort_run "The updated public key could not be exported."
    if [[ $form == "plaintext" && $source != "$MASTER_PLAINTEXT" ]]; then
      IMPORTED_PLAINTEXT="$source"
    fi
  else
    # Nothing changed, so the imported file is the export and is not rewritten.
    MASTER_PLAINTEXT="$key_file"
    # A plaintext subkeys export from an earlier run is taken through the
    # encrypted backup phase too, provided it belongs to this key.
    if [[ -f "$BACKUP_DIR/subkeys-secret.key" ]] && export_is_covered "$BACKUP_DIR/subkeys-secret.key"; then
      SUBKEYS_PLAINTEXT="$BACKUP_DIR/subkeys-secret.key"
    else
      SUBKEYS_PLAINTEXT=""
    fi
  fi
}

Phase 2: Master Key Backup

Exports the master secret key, subkeys, public key, and revocation certificate to a user-specified directory (or the path from --backup-dir). Each export is written as <target>.new, listed with gpg, and compared with the fingerprints in the keyring before it takes its final name. Displays SHA256 checksums for verification. Both secret exports are plaintext from this point until the encrypted backup phase. The script will not proceed until backups are confirmed – this is a hard gate because keytocard in Phase 3 is irreversible.

This phase is skipped in --from-backup mode since the backup already exists.

# Warn when the backup target looks like somewhere the host will not persist.
#
# A filesystem-type test for tmpfs is not enough on its own. On a host using
# othrys.system.impermanence, /tmp is not a separate mount at all, it sits on a
# root filesystem that the boot wipe clears, and a tmpfs check sees nothing. So
# this looks at both the filesystem type and the well-known volatile paths, and
# still only warns, because no heuristic can enumerate what a given host keeps.
check_backup_target() {
  local target="$1" fstype="" volatile=false
  local parent="$target"
  # findmnt needs a path that exists, so walk up to the nearest one.
  while [[ -n $parent && ! -e $parent ]]; do parent=$(dirname "$parent"); done
  if command -v findmnt >/dev/null 2>&1 && [[ -e $parent ]]; then
    fstype=$(findmnt -no FSTYPE --target "$parent" 2>/dev/null || true)
  fi

  case "$fstype" in
  tmpfs | ramfs) volatile=true ;;
  esac
  case "$target" in
  /tmp/* | /tmp | /var/tmp/* | /var/tmp | /dev/shm/*) volatile=true ;;
  esac

  $volatile || return 0

  error "The backup directory looks volatile: $target"
  [[ -n $fstype ]] && error "  filesystem: $fstype"
  error "This is the only copy of a master key whose subkeys cannot be extracted"
  error "from the YubiKey again. If this location is cleared on reboot, the"
  error "identity is gone."
  if ! $OPT_FORCE_VOLATILE; then
    error "Pass --force-volatile if you know this location is kept."
    exit 1
  fi
  warn "--force-volatile given: continuing anyway."
}

# The fingerprints of the key in the keyring, primary and subkeys, one a line.
keyring_fingerprints() {
  gpg --list-keys --with-colons "$KEY_FINGERPRINT" 2>/dev/null |
    awk -F: '$1 == "fpr" {print $10}' | sort -u || true
}

# The fingerprints gpg finds in an export file. Nothing is imported.
file_fingerprints() {
  gpg --batch --show-keys --with-colons "$1" 2>/dev/null |
    awk -F: '$1 == "fpr" {print $10}' | sort -u || true
}

# True when every key in an export file is also in the keyring, which makes
# the file a subset of what a fresh export of the keyring holds.
export_is_covered() {
  local in_file
  in_file=$(file_fingerprints "$1")
  [[ -n $in_file ]] &&
    [[ -z $(comm -23 <(printf '%s\n' "$in_file") <(keyring_fingerprints)) ]]
}

# True for a path inside the temporary GNUPGHOME, which is memory and goes
# when the script exits. Everything else is treated as the backup medium.
in_gnupghome() {
  [[ -n $TEMP_GNUPGHOME && $1 == "$TEMP_GNUPGHOME"/* ]]
}

# Remove a plaintext export. shred overwrites the blocks of a file in place,
# which removes the data on the ramfs and on a filesystem that writes in place.
# Flash media remap blocks and copy-on-write filesystems write new ones, so the
# old contents can stay readable there and nothing run from here changes that.
# The operator is told once.
SHRED_WARNED=false
remove_plaintext() {
  local file="$1"
  [[ -e $file ]] || return 0
  shred -u "$file" 2>/dev/null || rm -f "$file"
  if in_gnupghome "$file"; then
    return 0
  fi
  if ! $SHRED_WARNED; then
    SHRED_WARNED=true
    warn "shred overwrites a file in place. Flash media and copy-on-write"
    warn "filesystems such as btrfs keep the old blocks, so treat the medium"
    warn "holding $(dirname "$file") as one that has carried the plaintext."
  fi
}

# Export one part of the key to <target>.new, read the new file back, and only
# then move it over <target>. A redirect straight onto the target truncates it
# before gpg has produced anything, and on a rotation the target is the only
# backup.
#
# Reading back means asking gpg to list the new file and comparing the
# fingerprints in it with the keyring. An export that stopped early, or one a
# cancelled passphrase prompt left empty, replaces nothing.
export_verified() {
  local kind="$1" target="$2"
  local new="$target.new"
  local block="-----BEGIN PGP PRIVATE KEY BLOCK-----" # gitleaks:allow (the armor header an export is compared with, not a key)
  local -a export_args=(--export-secret-keys)
  local want got first_line=""

  case "$kind" in
  subkeys) export_args=(--export-secret-subkeys) ;;
  public)
    export_args=(--export)
    block="-----BEGIN PGP PUBLIC KEY BLOCK-----"
    ;;
  esac

  rm -f "$new"
  if ! gpg --armor "${export_args[@]}" "$KEY_FINGERPRINT" >"$new"; then
    remove_plaintext "$new"
    error "gpg could not export the $kind key. $target was not changed."
    return 1
  fi

  want=$(keyring_fingerprints)
  got=$(file_fingerprints "$new")
  IFS= read -r first_line <"$new" || true
  if [[ $first_line != "$block" || -z $want || $got != "$want" ]]; then
    remove_plaintext "$new"
    error "The $kind export did not read back as the key in the keyring."
    error "$target was not changed."
    return 1
  fi

  mv -f "$new" "$target"
}

# Stop the run and say what it leaves behind. Every hard stop after the backup
# phase goes through here, so the operator always learns whether plaintext
# exports are still on the backup medium.
abort_run() {
  error "$1"
  if [[ -n $MASTER_PLAINTEXT && -e $MASTER_PLAINTEXT ]] && ! in_gnupghome "$MASTER_PLAINTEXT"; then
    error "Nothing was removed. The exports in $BACKUP_DIR are still plaintext."
    error "Encrypt them or remove them before the medium leaves your hands."
  elif [[ -n $BACKUP_DIR ]]; then
    error "Nothing was removed from $BACKUP_DIR."
  fi
  exit 1
}

phase_backup() {
  header "Phase 2: Master Key Backup"

  warn "After moving subkeys to the YubiKey, they CANNOT be extracted."
  warn "You MUST back up the master key now."
  echo ""

  if [[ -n $OPT_BACKUP_DIR ]]; then
    BACKUP_DIR="$OPT_BACKUP_DIR"
    info "Using backup directory from --backup-dir: $BACKUP_DIR"
  else
    # No default. This used to offer /tmp/yubikey-backup-<date>, which is
    # predictable, unencrypted, and on most hosts does not survive a reboot, so
    # pressing Enter put the only copy of a master key somewhere it could
    # vanish. The script cannot know what a given host persists, so the operator
    # names the destination.
    echo "Use removable media you can store somewhere safe, e.g. /run/media/you/backup."
    BACKUP_DIR=$(prompt_required "Backup directory")
  fi

  check_backup_target "$BACKUP_DIR"

  MASTER_PLAINTEXT="$BACKUP_DIR/master-secret.key"
  SUBKEYS_PLAINTEXT="$BACKUP_DIR/subkeys-secret.key"

  if $DRY_RUN; then
    dry_run_skip "mkdir -p $BACKUP_DIR"
    dry_run_skip "gpg --export-secret-keys -> $BACKUP_DIR/master-secret.key"
    dry_run_skip "gpg --export-secret-subkeys -> $BACKUP_DIR/subkeys-secret.key"
    dry_run_skip "gpg --export -> $BACKUP_DIR/public.key"
    dry_run_skip "cp revocation.cert -> $BACKUP_DIR/revocation.cert"
    info "Would export master key, subkeys, public key, and revocation cert."
    return
  fi

  mkdir -p "$BACKUP_DIR"
  chmod 700 "$BACKUP_DIR"

  info "Exporting keys to $BACKUP_DIR ..."

  # Master + subkeys, subkeys only, and the public key. Both secret exports
  # are plaintext until the encrypted backup phase has run.
  export_verified master "$MASTER_PLAINTEXT" || exit 1
  export_verified subkeys "$SUBKEYS_PLAINTEXT" || exit 1
  export_verified public "$BACKUP_DIR/public.key" || exit 1

  # Copy revocation cert
  local rev_cert="$GNUPGHOME/openpgp-revocs.d/$KEY_FINGERPRINT.rev"
  if [[ -f $rev_cert ]]; then
    cp "$rev_cert" "$BACKUP_DIR/revocation.cert"
  fi

  echo ""
  info "Backup checksums (SHA256):"
  sha256sum "$BACKUP_DIR"/*.key "$BACKUP_DIR"/*.cert 2>/dev/null || true

  echo ""
  echo -e "${RED}${BOLD}WARNING: Move these backups to secure offline storage NOW.${NC}"
  echo -e "${RED}${BOLD}The master key allows creating new subkeys and revoking old ones.${NC}"
  echo ""

  if ! prompt_yn "Have you saved the backups to secure storage?"; then
    error "Cannot continue without confirmed backups. Aborting."
    exit 1
  fi
}

Phase 3: Move Subkeys to YubiKey

The script runs keytocard itself. The temporary GNUPGHOME sits on a ramfs inside a mount namespace that only the script’s own process tree can see, so a gpg --edit-key typed into a second terminal finds an empty directory and no key. Everything that touches the keyring therefore runs from inside the script.

The subkey for each slot is chosen by capability, and the newest usable one wins. Position in the key listing is not used, since a rotated key carries its expired subkeys ahead of the new ones. One gpg --edit-key session runs for each subkey, selected by fingerprint. The script answers gpg’s questions by the keyword gpg announces on its status channel, and a question it has no answer for ends the session with the key unchanged. gpg-agent asks for the master key passphrase and the OpenPGP admin PIN through pinentry on the same terminal, and neither passes through the script. When the applet already holds keys, the script lists them and asks before anything is replaced.

After the three sessions the script reads gpg --card-status and compares the fingerprint in each slot with the subkey chosen for it. An empty slot or a slot holding another key is a hard failure. The script then offers an interactive gpg --edit-key session on the same terminal, inside the same namespace, prints the three key <fingerprint> commands with their slots, and checks the card again afterwards. Declining stops the run before any PIN is changed and before any export is removed, and the error says whether plaintext exports are still on the backup medium.

# The newest usable subkey with one capability, read from a colon listing on
# stdin. A rotated key carries its expired subkeys beside the new ones, so the
# position in the listing says nothing about which subkey belongs in a slot.
subkey_for_capability() {
  awk -F: -v cap="$1" '
    $1 == "sub" { want = ($2 !~ /^[rei]$/ && index($12, cap) > 0); created = $6 + 0; next }
    $1 == "fpr" && want { if (created >= best) { best = created; fpr = $10 }; want = 0 }
    END { print fpr }'
}

select_card_subkeys() {
  local listing
  listing=$(gpg --list-keys --with-colons "$KEY_FINGERPRINT" 2>/dev/null || true)
  SUBKEY_FPR_SIGN=$(subkey_for_capability s <<<"$listing")
  SUBKEY_FPR_ENCR=$(subkey_for_capability e <<<"$listing")
  SUBKEY_FPR_AUTH=$(subkey_for_capability a <<<"$listing")
  if [[ -z $SUBKEY_FPR_SIGN || -z $SUBKEY_FPR_ENCR || -z $SUBKEY_FPR_AUTH ]]; then
    abort_run "The key lacks a usable signing, encryption or authentication subkey, so nothing was moved to the YubiKey."
  fi
}

# The fingerprints in the three card slots, as the card reports them. An empty
# slot reads as an empty string.
read_card_slots() {
  local line
  line=$(gpg --card-status --with-colons 2>/dev/null |
    awk -F: '$1 == "fpr" {print $2 ":" $3 ":" $4; exit}' || true)
  IFS=: read -r CARD_FPR_SIGN CARD_FPR_ENCR CARD_FPR_AUTH <<<"${line:-::}" || true
  CARD_FPR_SIGN="${CARD_FPR_SIGN^^}"
  CARD_FPR_ENCR="${CARD_FPR_ENCR^^}"
  CARD_FPR_AUTH="${CARD_FPR_AUTH^^}"
  [[ $CARD_FPR_SIGN =~ ^0+$ ]] && CARD_FPR_SIGN=""
  [[ $CARD_FPR_ENCR =~ ^0+$ ]] && CARD_FPR_ENCR=""
  [[ $CARD_FPR_AUTH =~ ^0+$ ]] && CARD_FPR_AUTH=""
  return 0
}

check_card_slot() {
  local label="$1" on_card="$2" expected="${3^^}"
  if [[ -z $on_card ]]; then
    error "$label slot is empty."
    return 1
  fi
  if [[ $on_card != "$expected" ]]; then
    error "$label slot holds $on_card, expected $expected."
    return 1
  fi
  success "$label slot holds $expected."
}

# True only when each slot holds the subkey chosen for it.
verify_card_slots() {
  local ok=true
  read_card_slots
  check_card_slot "Signature" "$CARD_FPR_SIGN" "$SUBKEY_FPR_SIGN" || ok=false
  check_card_slot "Encryption" "$CARD_FPR_ENCR" "$SUBKEY_FPR_ENCR" || ok=false
  check_card_slot "Authentication" "$CARD_FPR_AUTH" "$SUBKEY_FPR_AUTH" || ok=false
  $ok
}

# Run one `gpg --edit-key` session and answer its questions by the keyword gpg
# announces on its status channel. Feeding it lines in a fixed order goes wrong
# as soon as gpg asks one question more or fewer than expected, since every
# later answer then lands on the wrong question. Here a question with no known
# answer ends the session, and gpg leaves the key as it was.
#
# The first two arguments are the card slot and the answer to "replace the key
# in this slot". The rest are the commands for the edit prompt, in order.
#
# gpg runs in the foreground and keeps the terminal. gpg-agent asks for the key
# passphrase and the admin PIN through pinentry there, so neither passes
# through this script.
edit_key_scripted() {
  local slot="$1" replace="$2"
  shift 2
  local cmd_fifo="$GNUPGHOME/edit-commands" status_fifo="$GNUPGHOME/edit-status"
  local responder rc=0

  rm -f "$cmd_fifo" "$status_fifo"
  mkfifo "$cmd_fifo" "$status_fifo"

  (
    trap '' PIPE
    exec 3>"$cmd_fifo" 4<"$status_fifo"
    answered=0
    while IFS= read -r line <&4; do
      case "$line" in
      "[GNUPG:] GET_LINE keyedit.prompt")
        if [[ $# -gt 0 ]]; then
          reply="$1"
          shift
        else
          reply="quit"
        fi
        ;;
      "[GNUPG:] GET_LINE cardedit.genkeys.storekeytype") reply="$slot" ;;
      "[GNUPG:] GET_BOOL cardedit.genkeys.replace_key") reply="$replace" ;;
      "[GNUPG:] GET_BOOL keyedit.save.okay") reply="n" ;;
      "[GNUPG:] GET_"*)
        error "gpg asked a question this script has no answer for: ${line#\[GNUPG:\] }"
        exit 3
        ;;
      *) continue ;;
      esac
      # gpg repeats a question whose answer it did not accept. One subkey takes
      # five answers, so a dozen means the session is going in circles.
      answered=$((answered + 1))
      if ((answered > 12)); then
        error "gpg kept repeating its questions, so the session was ended."
        exit 3
      fi
      printf '%s\n' "$reply" >&3 || exit 3
    done
  ) &
  responder=$!

  gpg --command-fd 3 --status-fd 4 --edit-key "$KEY_FINGERPRINT" \
    3<"$cmd_fifo" 4>"$status_fifo" || rc=$?
  wait "$responder" || rc=$?
  rm -f "$cmd_fifo" "$status_fifo"
  return "$rc"
}

move_subkey_to_card() {
  local label="$1" slot="$2" fpr="$3" on_card="$4" replace="$5"
  if [[ $on_card == "${fpr^^}" ]]; then
    info "$label slot already holds this subkey."
    return 0
  fi
  info "Moving the $label subkey to slot $slot..."
  if ! edit_key_scripted "$slot" "$replace" "key $fpr" "keytocard" "save"; then
    warn "gpg did not finish moving the $label subkey."
  fi
}

phase_keytocard() {
  header "Phase 3: Move Subkeys to YubiKey"

  check_yubikey

  info "This step moves your subkeys to the YubiKey. This is IRREVERSIBLE."
  info "The subkeys in GNUPGHOME will be replaced with stubs."
  echo ""

  if $DRY_RUN; then
    dry_run_skip "gpg --edit-key $KEY_FINGERPRINT keytocard (3 subkeys)"
    dry_run_skip "gpg --card-status (compare the three slots with the subkeys)"
    info "Would move Sign, Encrypt, and Authenticate subkeys to YubiKey."
    return
  fi

  select_card_subkeys

  # gpg asks before it overwrites a slot, and the answer has to be decided
  # before the session starts.
  local replace="n"
  read_card_slots
  if [[ -n $CARD_FPR_SIGN$CARD_FPR_ENCR$CARD_FPR_AUTH ]]; then
    warn "The OpenPGP applet already holds keys:"
    echo "  Signature:      ${CARD_FPR_SIGN:-(empty)}"
    echo "  Encryption:     ${CARD_FPR_ENCR:-(empty)}"
    echo "  Authentication: ${CARD_FPR_AUTH:-(empty)}"
    if ! prompt_yn "Replace them with the subkeys of $KEY_FINGERPRINT?"; then
      abort_run "The slots were left as they are, so the YubiKey does not hold this key."
    fi
    replace="y"
  fi

  info "gpg asks for the master key passphrase and for the OpenPGP admin PIN."
  info "The factory admin PIN is 12345678."
  echo ""

  move_subkey_to_card "Signature" 1 "$SUBKEY_FPR_SIGN" "$CARD_FPR_SIGN" "$replace"
  move_subkey_to_card "Encryption" 2 "$SUBKEY_FPR_ENCR" "$CARD_FPR_ENCR" "$replace"
  move_subkey_to_card "Authentication" 3 "$SUBKEY_FPR_AUTH" "$CARD_FPR_AUTH" "$replace"

  # The card is asked what it holds, and the answer is compared with the
  # subkeys chosen above. An empty slot or another key stops the run here,
  # before any PIN is changed and long before an export is removed.
  echo ""
  info "Verifying keys are on the YubiKey..."
  until verify_card_slots; do
    echo ""
    error "The YubiKey does not hold all three subkeys."
    if ! prompt_yn "Open gpg --edit-key here to move the missing ones by hand?" "y"; then
      abort_run "The subkeys are not on the YubiKey."
    fi
    echo ""
    echo "  For each line, enter the key command, then keytocard, then the slot"
    echo "  number, then the same key command again to deselect the subkey."
    echo "  Leave out a slot the check above reported as holding its subkey."
    echo ""
    echo "    key $SUBKEY_FPR_SIGN    slot 1 (Signature key)"
    echo "    key $SUBKEY_FPR_ENCR    slot 2 (Encryption key)"
    echo "    key $SUBKEY_FPR_AUTH    slot 3 (Authentication key)"
    echo ""
    echo "  Finish with: save"
    echo ""
    gpg --edit-key "$KEY_FINGERPRINT" || true
    echo ""
    info "Verifying keys are on the YubiKey..."
  done
  success "All three subkeys are on the YubiKey."
}

Per-YubiKey Provisioning (Phases 3-6)

For each YubiKey, the script runs:

  • Reset. Optionally factory reset the OpenPGP and FIDO2 applets
  • Phase 3: keytocard for each subkey, then the fingerprint check against the card
  • Phase 4: Change the OpenPGP user PIN (123456) and admin PIN (12345678), then the PIV PIN (123456), PUK (12345678) and management key, all via ykman
  • Phase 5: Register a U2F credential with pamu2fcfg -n -o pam://yubi
  • Phase 6: Generate an age identity with age-plugin-yubikey --generate (touch: always, PIN: once)

Every prompt in Phase 4 defaults to yes. The script cannot ask a token whether a PIN is still the factory one without spending a retry, so it tracks which changes ran. A credential that was not changed stops the run, unless --allow-default-pins is given, which is meant for a token whose PINs were set on an earlier day. The credentials left alone are then listed at the end of the run. Two failed attempts at one credential also stop the run, since a third wrong entry of the current value can block it.

The PIV applet is changed in Phase 4 so that the age identity Phase 6 writes into it is never guarded by the factory PIN. The management key is replaced with a random one stored on the token behind the PIN, which is the form age-plugin-yubikey accepts.

After the first YubiKey is provisioned, the script asks whether to provision another (or provisions exactly --key-count keys). It restores the subkeys from the master key export between each keytocard pass.

Post-Provisioning (Phases 7-9)

  • Phase 7: Extract the authentication subkey’s keygrip for SSH and export the SSH public key (same for all keys since they share the same GPG key)
  • Phase 8: Import the public key into the persistent ~/.gnupg keyring and set ultimate trust

Encrypted Key Backup

Runs after every YubiKey is provisioned, and the ordering is forced rather than chosen. The plaintext backup has to exist before keytocard in Phase 3, since that move is irreversible, and it has to survive the provisioning loop because subkeys are re-imported from it between each key. The age recipients do not exist until Phase 6 has run for a token. There is no earlier point at which both are true.

Both secret exports go through the same function, master-secret.key first and subkeys-secret.key after it. Two files are written for each, because age refuses -p and -r together:

FileOpens with
master-secret.key.age, subkeys-secret.key.ageany provisioned YubiKey, or an extra --age-recipient
master-secret.key.pass.age, subkeys-secret.key.pass.agethe passphrase entered during this phase

age asks for the passphrase twice to encrypt each export and once more to verify it, which makes six entries in a default run.

The passphrase copy is not redundancy for its own sake. A master key backup exists precisely to survive losing every token, so encrypting it only to those tokens makes it worthless in the situation it was created for. --no-age-passphrase declines it.

Each copy is written as <name>.new, decrypted, compared byte for byte with the plaintext, and moved into place only after that, so a copy from an earlier run is never replaced by one that has not been opened. A plaintext export is removed only once one of its copies has passed that comparison in the same run. A failed verification keeps the plaintext and says so, and the run then ends with a non-zero exit status and the list of exports that are still plaintext. --keep-plaintext retains the plaintext even on success, and --no-age-backup skips the phase entirely.

A plaintext subkeys-secret.key that an earlier run left in the backup directory is handled here too. It is encrypted with the rest, or removed once the new encrypted copy holds every key in it.

What shred Removes

The plaintext is removed with shred -u, which overwrites the blocks of a file in place before unlinking it. That removes the data only where an overwrite lands on the blocks that held it:

  • On the ramfs the temporary GNUPGHOME lives on, the overwrite is effective, and the pages are freed when the script exits.
  • On flash media, which covers USB sticks, SD cards and SSDs, the controller remaps writes for wear levelling. The old blocks stay on the device until the controller reuses them, and they can be read from the raw flash.
  • On a copy-on-write filesystem such as btrfs, an overwrite is written to new blocks and the old ones are released without being cleared. Snapshots keep them for as long as the snapshot exists.

shred reports success in all three cases. The recommendation follows from that. Key material that must not persist is worked on in the ramfs, which the script already does for the keyring and for everything a --from-backup run decrypts. A first run cannot avoid plaintext exports on the backup medium, since they have to exist before keytocard and the age recipients do not exist until after it. A plaintext copy that has touched a USB stick is therefore treated as exposed to anyone who later holds that stick. The backup medium should be an encrypted volume, such as a LUKS container, or a stick that is kept or destroyed and never reused for anything else. The master key passphrase from Phase 1 is what protects the export while it sits there, which is one more reason not to pass --no-passphrase.

Verifying the token copy needs the inserted YubiKey’s PIN and a touch, and can only test the token currently in the reader, which after a multi-key run is the last one provisioned. The other tokens are the same mechanism and the same ciphertext, but this phase has not proved them.

# Encrypt the plaintext exports, verify the results, and remove the plaintext.
#
# This runs after every YubiKey is provisioned rather than inside phase_backup,
# and the ordering is forced rather than chosen. The backup has to exist before
# `keytocard` in Phase 3, since that move is irreversible, and the plaintext has
# to survive the provisioning loop because subkeys are re-imported from it
# between each key. The age recipients do not exist until Phase 6 has run for a
# token. Encrypting earlier is therefore impossible in both directions.
#
# Two files for each export, because `age` refuses -p together with -r. The
# token copy is encrypted to the age recipients this run provisioned plus
# anything given with --age-recipient. The passphrase copy exists so that losing
# every token does not lose the identity, which is the exact case the master key
# backup is for.
BACKUP_RECIPIENTS=()
BACKUP_IDFILE=""

# One export through the whole sequence. $1 is the plaintext, which sits in the
# backup directory on a first run and in the ramfs after an encrypted import.
# $2 is the path in the backup directory the encrypted copies are named after.
#
# Each copy is written as <name>.new, decrypted, compared byte for byte with the
# plaintext, and only then moved into place, so a copy from an earlier run is
# never replaced by one that has not been opened.
protect_export() {
  local plaintext="$1" dest="$2"
  local name enc="$2.age" pass_enc="$2.pass.age"
  local check="$GNUPGHOME/verify.tmp"
  local token_ok=false pass_ok=false on_medium=false
  name=$(basename "$dest")
  in_gnupghome "$plaintext" || on_medium=true

  if [[ ${#BACKUP_RECIPIENTS[@]} -gt 0 ]]; then
    local -a args=()
    local r
    for r in "${BACKUP_RECIPIENTS[@]}"; do args+=(-r "$r"); done
    info "Encrypting $name to ${#BACKUP_RECIPIENTS[@]} age recipient(s)..."
    if age "${args[@]}" -o "$enc.new" "$plaintext"; then
      # Decrypting a YubiKey recipient needs the token in the reader, its PIN
      # and a touch, so this proves the file opens with hardware rather than
      # only that age wrote something. It can only test the token currently
      # inserted, which after a multi-key run is the last one provisioned.
      info "Verifying $enc (this needs the inserted YubiKey's PIN and a touch)..."
      if [[ -s $BACKUP_IDFILE ]] &&
        age -d -i "$BACKUP_IDFILE" -o "$check" "$enc.new" &&
        cmp -s "$plaintext" "$check"; then
        mv -f "$enc.new" "$enc"
        token_ok=true
        success "Token-encrypted backup verified: $enc"
      elif [[ -e $enc ]]; then
        warn "Could not verify the new token-encrypted copy of $name."
        warn "$enc from an earlier run was kept. The new copy is $enc.new."
      else
        mv -f "$enc.new" "$enc"
        warn "Could not verify $enc against the inserted token."
        warn "The file was written, but nothing here has proved it opens."
      fi
      rm -f "$check"
    else
      error "Encrypting $name to age recipients failed."
      rm -f "$enc.new"
    fi
  else
    warn "No age recipients captured, so no token-encrypted copy of $name was made."
  fi

  if ! $OPT_NO_AGE_PASSPHRASE; then
    echo ""
    info "Now a passphrase-encrypted copy of $name, so losing every YubiKey does"
    info "not lose the identity. Use a passphrase you can recover without this host."
    if age -p -o "$pass_enc.new" "$plaintext"; then
      info "Verifying $pass_enc (re-enter the same passphrase)..."
      if age -d -o "$check" "$pass_enc.new" &&
        cmp -s "$plaintext" "$check"; then
        mv -f "$pass_enc.new" "$pass_enc"
        pass_ok=true
        success "Passphrase-encrypted backup verified: $pass_enc"
      else
        error "Could not verify the passphrase-encrypted copy of $name."
        rm -f "$pass_enc.new"
      fi
      rm -f "$check"
    else
      error "Passphrase encryption failed or was cancelled."
      rm -f "$pass_enc.new"
    fi
  fi

  # The plaintext goes only against a copy that has been decrypted and compared
  # byte for byte in this run. Removing the only copy of a key on the strength
  # of a write that returned zero is the one mistake this must not make, so an
  # unverified encrypt keeps the plaintext and says why.
  if $pass_ok || $token_ok; then
    if $OPT_KEEP_PLAINTEXT && $on_medium; then
      warn "--keep-plaintext given: $plaintext left in place."
      warn "It is unencrypted key material. Store it accordingly."
      return 0
    fi
    remove_plaintext "$plaintext"
    success "Plaintext $name removed; encrypted copies remain."
    # A plaintext file of the same name that an earlier run left behind. It
    # goes only when every key in it is in the export just encrypted.
    if [[ $dest != "$plaintext" && -e $dest ]]; then
      if ! $OPT_KEEP_PLAINTEXT && export_is_covered "$dest"; then
        remove_plaintext "$dest"
        info "Removed $dest from an earlier run. The new encrypted copy holds every key in it."
      else
        PLAINTEXT_LEFT+=("$dest")
      fi
    fi
    if ! $pass_ok; then
      warn "Only the token-encrypted copy of $name verified. Losing every YubiKey"
      warn "now means losing it. Consider re-running with a passphrase copy."
    fi
    return 0
  fi

  if $on_medium; then
    warn "No encrypted copy verified, so $plaintext was left in place."
    warn "Do not delete it until you have a copy you have opened."
    PLAINTEXT_LEFT+=("$plaintext")
    return 0
  fi

  # The plaintext is in the ramfs and goes when the script exits. Without a
  # verified copy, anything generated in this run would exist nowhere else.
  error "No encrypted copy of $name verified, and the plaintext is held in memory only."
  if prompt_yn "Write it to $dest unencrypted so it is not lost?" "y"; then
    if cp "$plaintext" "$dest.new" && cmp -s "$plaintext" "$dest.new"; then
      mv -f "$dest.new" "$dest"
      PLAINTEXT_LEFT+=("$dest")
    else
      rm -f "$dest.new"
      error "Could not write $dest."
    fi
  else
    warn "$name was not saved. The backup in $BACKUP_DIR is as it was before this run."
  fi
  return 0
}

phase_age_backup() {
  [[ -n $BACKUP_DIR && -n $MASTER_PLAINTEXT ]] || return 0

  local master_dest="$BACKUP_DIR/master-secret.key"
  local subkeys_dest="$BACKUP_DIR/subkeys-secret.key"

  if $OPT_NO_AGE_BACKUP; then
    if in_gnupghome "$MASTER_PLAINTEXT"; then
      warn "--no-age-backup given: the backup in $BACKUP_DIR was not updated."
      warn "Subkeys generated in this run exist only on the YubiKeys."
    fi
    return 0
  fi

  if $DRY_RUN; then
    header "Encrypted Key Backup"
    dry_run_skip "age -r <recipients> -o $master_dest.age.new, verify, mv to $master_dest.age"
    dry_run_skip "age -p -o $master_dest.pass.age.new, verify, mv to $master_dest.pass.age"
    dry_run_skip "the same two copies of $subkeys_dest"
    dry_run_skip "shred the plaintext exports once a copy of each has verified"
    return 0
  fi

  [[ -f $MASTER_PLAINTEXT ]] || return 0

  header "Encrypted Key Backup"

  # Recipients: the tokens provisioned in this run, plus anything supplied.
  local r
  BACKUP_RECIPIENTS=()
  for r in "${AGE_RECIPIENTS[@]}"; do
    [[ -n $r ]] && BACKUP_RECIPIENTS+=("$r")
  done
  for r in "${OPT_AGE_RECIPIENTS[@]+"${OPT_AGE_RECIPIENTS[@]}"}"; do
    [[ -n $r ]] && BACKUP_RECIPIENTS+=("$r")
  done

  # A real file rather than process substitution, since age reads the identity
  # file directly and /dev/fd paths are not seekable. It lives in the ramfs
  # GNUPGHOME and goes with it.
  BACKUP_IDFILE="$GNUPGHOME/age-identities"
  : >"$BACKUP_IDFILE"
  for r in "${AGE_IDENTITIES[@]}"; do
    [[ -n $r ]] && printf '%s\n' "$r" >>"$BACKUP_IDFILE"
  done

  if [[ -e $master_dest.age && ${#BACKUP_RECIPIENTS[@]} -gt 0 ]]; then
    warn "$master_dest.age exists and is replaced once the new copy verifies."
    warn "The new copy opens with the YubiKeys provisioned in this run and with"
    warn "any --age-recipient. Recipients of the old copy are not carried over."
  fi
  if ! $OPT_NO_AGE_PASSPHRASE; then
    info "age asks for the passphrase twice to encrypt each export and once to"
    info "verify it. Use the same passphrase for both exports."
  fi

  protect_export "$MASTER_PLAINTEXT" "$master_dest"
  if [[ -n $SUBKEYS_PLAINTEXT && -f $SUBKEYS_PLAINTEXT ]]; then
    echo ""
    protect_export "$SUBKEYS_PLAINTEXT" "$subkeys_dest"
  fi

  # The plaintext file a rotation started from, when it was not the file the
  # new export replaced. It goes on the same terms as any older plaintext.
  if [[ -n $IMPORTED_PLAINTEXT && -e $IMPORTED_PLAINTEXT ]] && ! $OPT_KEEP_PLAINTEXT; then
    if [[ ! -e $MASTER_PLAINTEXT ]] && export_is_covered "$IMPORTED_PLAINTEXT"; then
      remove_plaintext "$IMPORTED_PLAINTEXT"
      info "Removed $IMPORTED_PLAINTEXT. The new encrypted copy holds every key in it."
    else
      PLAINTEXT_LEFT+=("$IMPORTED_PLAINTEXT")
    fi
  fi

  rm -f "$BACKUP_IDFILE"
}

Phase 10: Summary Output

Prints all values ready to paste into the NixOS host configurations:

  • sshKeygrips, GPG keygrip for SSH authentication (shared across all keys)
  • u2fMappings, one U2F credential per YubiKey
  • ageIdentityStubs, age identity block for sops-nix (primary key)
  • Git signing key fingerprint
  • SSH public key for GitHub/servers
  • age recipients for all provisioned keys (add all to .sops.yaml for redundancy)

A copy is saved in the backup directory as yubikey-onboard-summary-*.txt, since it carries the keygrip, the age recipients and the U2F credential lines that the host configuration needs later. In a --from-backup run the backup directory is the one the backup was read from.

The summary is never written to the working directory, which is often a public checkout. When the backup directory is no longer there at the end of the run, as when the medium was unmounted, the file goes to a new directory with mode 0700 under $XDG_RUNTIME_DIR, or under /tmp when that is unset, and the script prints its path. That directory does not survive a reboot. A dry run writes no summary and prints the directory a real run would use.

Verify Mode

The --verify flag runs a standalone health check on the currently inserted YubiKey:

  • Detects the YubiKey (serial, firmware)
  • Checks all three OpenPGP card slots (Signature, Encryption, Authentication)
  • Checks FIDO2 applet accessibility
  • Lists age identities in PIV slots
  • Checks gpg-agent for SSH key availability
  • Cross-references the YubiKey serial against the NixOS host configs
mode_verify() {
  header "YubiKey Verification"

  # Check tools
  local tools=("gpg" "ykman" "age-plugin-yubikey")
  local missing=()
  for tool in "${tools[@]}"; do
    if ! command -v "$tool" &>/dev/null; then
      missing+=("$tool")
    fi
  done
  if [[ ${#missing[@]} -gt 0 ]]; then
    error "Missing tools: ${missing[*]}"
    exit 1
  fi

  # YubiKey detection
  if ! ykman info &>/dev/null; then
    error "No YubiKey detected."
    exit 1
  fi

  local serial firmware
  serial=$(yubikey_info_field "Serial number")
  firmware=$(yubikey_info_field "Firmware version")
  success "YubiKey detected (serial: ${serial:-$NO_SERIAL}, firmware: ${firmware:-unreported})"

  # OpenPGP card status
  echo ""
  info "OpenPGP card status:"
  local card_status
  card_status=$(gpg --card-status 2>/dev/null || true)

  if [[ -z $card_status ]]; then
    warn "  Could not read OpenPGP card status."
  else
    local sig_key enc_key auth_key
    sig_key=$(echo "$card_status" | grep "Signature key" | head -1 || true)
    enc_key=$(echo "$card_status" | grep "Encryption key" | head -1 || true)
    auth_key=$(echo "$card_status" | grep "Authentication key" | head -1 || true)

    if echo "$sig_key" | grep -q "none"; then
      warn "  Signature slot: empty"
    else
      success "  Signature slot: populated"
    fi
    if echo "$enc_key" | grep -q "none"; then
      warn "  Encryption slot: empty"
    else
      success "  Encryption slot: populated"
    fi
    if echo "$auth_key" | grep -q "none"; then
      warn "  Authentication slot: empty"
    else
      success "  Authentication slot: populated"
    fi
  fi

  # FIDO2/U2F status
  echo ""
  info "FIDO2 status:"
  local fido_info
  fido_info=$(ykman fido info 2>/dev/null || true)
  if [[ -n $fido_info ]]; then
    success "  FIDO2 applet accessible"
  else
    warn "  FIDO2 applet not accessible"
  fi

  # PIV/age status
  echo ""
  info "PIV slots (age-plugin-yubikey):"
  local age_identities
  age_identities=$(age-plugin-yubikey --identity 2>/dev/null || true)
  if [[ -n $age_identities ]]; then
    local slot_count
    slot_count=$(echo "$age_identities" | grep -c "^AGE-PLUGIN-YUBIKEY-" || true)
    success "  $slot_count age identity/identities found"
    echo "$age_identities" | grep "^#" | sed 's/^/    /'
  else
    warn "  No age identities found on this YubiKey"
  fi

  # GPG agent SSH
  echo ""
  info "GPG-agent SSH support:"
  local ssh_keys
  ssh_keys=$(ssh-add -L 2>/dev/null || true)
  if echo "$ssh_keys" | grep -q "cardno:"; then
    success "  SSH key from YubiKey available via gpg-agent"
  else
    warn "  No YubiKey SSH key in agent (may need: gpg --card-status)"
  fi

  # Check against NixOS config (best-effort)
  echo ""
  info "Config cross-reference:"
  local config_files=(hosts/*/default.nix)
  # An empty pattern matches every line, so a token without a serial would be
  # reported as found in every file.
  if [[ -z $serial ]]; then
    warn "  This token reports no serial number, so there is nothing to look up."
    config_files=()
  fi
  for cfg in "${config_files[@]+"${config_files[@]}"}"; do
    if [[ -f $cfg ]]; then
      if grep -qF -- "$serial" "$cfg" 2>/dev/null; then
        success "  Serial $serial found in $cfg"
      else
        warn "  Serial $serial NOT found in $cfg"
      fi
    fi
  done

  echo ""
  success "Verification complete."
}

After Onboarding

  1. Update your fleet’s host configurations with the output values
  2. Update .sops.yaml in the secrets repo with all age recipients
  3. Re-encrypt secrets: sops updatekeys <secret-files>
  4. Upload public key to GitHub: gpg --armor --export <FINGERPRINT>
  5. Rebuild: just switch <hostname>

Script Entrypoint

main() {
  # Handle --verify mode separately
  if $VERIFY_MODE; then
    mode_verify
    exit 0
  fi

  header "YubiKey Onboarding Script"
  echo "This script will guide you through provisioning a new YubiKey for use"
  echo "with this NixOS configuration (PGP, U2F, SSH, sops-nix)."
  echo ""
  echo "Following drduh's YubiKey guide: https://github.com/drduh/YubiKey-Guide"
  echo ""

  if $DRY_RUN; then
    warn "DRY-RUN MODE: No destructive operations will be performed."
    echo ""
  fi

  if [[ -n $OPT_FROM_BACKUP ]]; then
    info "Mode: key rotation (importing from existing backup)"
  else
    info "Mode: new key generation"
  fi
  echo ""

  if ! prompt_yn "Ready to begin?" "y"; then
    echo "Aborted."
    exit 0
  fi

  # gpg-agent starts pinentry on the terminal named here. Without it, a gpg
  # that is fed its commands on another descriptor has no terminal to name.
  if [[ -t 0 ]]; then
    GPG_TTY=$(tty)
    export GPG_TTY
  fi

  # One-time phases: preflight always runs
  phase_preflight

  # Either generate new keys or import from backup
  if [[ -n $OPT_FROM_BACKUP ]]; then
    phase_import_from_backup
  else
    phase_generate_keys
    phase_backup
  fi

  # Determine how many YubiKeys to provision
  local target_count="${OPT_KEY_COUNT:-}"

  # Provision first YubiKey
  provision_yubikey 0
  NUM_KEYS=1

  # Provision additional YubiKeys
  if [[ -n $target_count ]]; then
    # Non-interactive: provision exactly the requested count
    while [[ $NUM_KEYS -lt $target_count ]]; do
      echo ""
      info "Restoring subkeys so they can be moved to the next YubiKey..."
      restore_subkeys
      echo ""
      warn "Remove the current YubiKey and insert YubiKey #$((NUM_KEYS + 1))."
      read -rp "$(echo -e "${BOLD}Press Enter when the new YubiKey is inserted...${NC}")"
      echo ""

      provision_yubikey "$NUM_KEYS"
      NUM_KEYS=$((NUM_KEYS + 1))
    done
  else
    # Interactive: ask after each key
    while prompt_yn "Provision another YubiKey with the same PGP key (redundancy)?"; do
      echo ""
      info "Restoring subkeys so they can be moved to the next YubiKey..."
      restore_subkeys
      echo ""
      warn "Remove the current YubiKey and insert the next one."
      read -rp "$(echo -e "${BOLD}Press Enter when the new YubiKey is inserted...${NC}")"
      echo ""

      provision_yubikey "$NUM_KEYS"
      NUM_KEYS=$((NUM_KEYS + 1))
    done
  fi

  # One-time post-provisioning phases
  phase_ssh_keygrip
  phase_import_pubkey
  phase_age_backup
  phase_summary

  local item
  if [[ ${#UNCHANGED_CREDENTIALS[@]} -gt 0 ]]; then
    warn "Not changed in this run, as --allow-default-pins permits:"
    for item in "${UNCHANGED_CREDENTIALS[@]}"; do
      warn "  $item"
    done
  fi

  # Provisioning is done at this point, but a run that leaves key material
  # unencrypted on the backup medium does not end as a success.
  if [[ ${#PLAINTEXT_LEFT[@]} -gt 0 ]]; then
    error "$NUM_KEYS YubiKey(s) provisioned, but these exports are still plaintext:"
    for item in "${PLAINTEXT_LEFT[@]}"; do
      error "  $item"
    done
    error "Encrypt them or remove them. Each holds secret key material."
    exit 1
  fi

  if $DRY_RUN; then
    success "Dry run complete. Nothing was provisioned and nothing was written."
    return 0
  fi

  success "All done! $NUM_KEYS YubiKey(s) provisioned."
  success "Remember to clean up backup files from insecure locations."
}

Security Notes

  • The script runs with umask 077, so every file it writes is owned by the caller and readable by nobody else
  • The master key lives in a temporary GNUPGHOME on ramfs and is cleaned up on exit via an EXIT trap. ramfs pages are never written to disk or swap. The script re-execs itself under unshare -Urm --propagation slave to mount it, which needs no privilege, and the mount dies with the process rather than needing an unmount that could fail. Where unprivileged user namespaces are disabled it falls back to /dev/shm and says so. That fallback is tmpfs, whose pages are swappable, so on a host with active swap the key can reach disk while it exists, and the script warns when it sees swap
  • The master key is generated unprotected and a passphrase is set before the backup phase. Entry runs through gpg-agent’s own pinentry on the same terminal, so the passphrase stays in the agent’s mlocked memory and never reaches a shell variable. A gate re-reads the on-disk protection state afterwards, so a cancelled dialog cannot pass. --no-passphrase is the explicit escape hatch
  • The backup directory has no default and a volatile target is refused unless --force-volatile is given, since the backup is the only copy of a master key whose subkeys cannot be extracted from the YubiKey again
  • Phase 4 changes the OpenPGP and PIV credentials and refuses to finish with one left unchanged unless --allow-default-pins is given. The FIDO2 applet ships without a PIN, and the script does not set one
  • shred cannot promise removal on flash media or on a copy-on-write filesystem. See What shred Removes
  • Names, email addresses, paths and every other prompted or flag value are refused when they contain a newline or another control character, since some of them are fed to gpg as commands
  • The GPG configuration follows drduh’s hardened settings
  • In --from-backup mode, the master key is loaded into the same ramfs GNUPGHOME from the backup, so it still never persists to disk. An encrypted backup is decrypted there and nowhere else