Skip to content

// Engineering Log

Secrets and Zero Trust: Part 5 — Unlocking the vault by touching an FIDO2 key

Published on 2026-11-25 · Author:

// Fast route

This article belongs to the topic Servers and infrastructure.

The Bitwarden CLI on a Linux host is opened with the command bw unlock, and each time it asks for the master password. Typing a long password on the console without a password manager is inconvenient, and placing it in a file next to bw means giving the vault to anyone who copies the disk. Here is a scheme where the master password is stored on disk only in encrypted form, and the decryption key is provided by a FIDO2 hardware key after a touch. The scheme works on a host with a Raspberry Pi, a YubiKey 5, and a Vaultwarden server on the internal network; the scripts in the article have been tested on that hardware.

Prerequisites: an installed and configured bw (“Part 3 — Bitwarden CLI on Linux: bw, session and secure operation”), the fido2-tools package from libfido2 and permissions for the key device (“Part 4 — FIDO2 and YubiKey: hmac-secret, libfido2 and access permissions”), openssl, and the zsh shell.

How the scheme works

The FIDO2 extension hmac-secret allows obtaining a persistent secret from the key. When an account with this extension is created, the key generates two random 32-byte values internally (one for user-verified requests, the other without verification), which never leave the device. The program then gives the key a 32-byte salt, and the key returns an HMAC-SHA-256 of the chosen value and the salt — 32 bytes. For the same account and the same salt the response is always the same, but it can be obtained only with that key and only after a touch.

The whole scheme is built on this:

  1. Binding (once). A non-resident credential is created on the key with hmac-secret for the service RP ID bw.local. A random salt is generated; the key on touch returns the secret. This secret is used as the passphrase to encrypt the master password: openssl enc -aes-256-cbc -pbkdf2 -iter 200000.
  2. Unlocking. The program gives the key the same credential and the same salt, receives the same secret, decrypts the password and calls bw unlock.
  3. Session. The bw session key is stored in tmpfs and lives until reboot or explicit lock. New shells pick it up; no repeated touch of the key is needed.

A non-resident credential does not occupy space on the key: the credential identifier (credential ID) is stored in the file cred, and the key recognizes its credential by it. Therefore, when removing the binding on the key itself there is nothing to erase.

What is stored on disk

Everything is stored in the directory ~/.config/bw-fido/:

FileContentsSecret?
credcredential ID in base64no
salt32 random bytes in base64no
pw.encmaster password encrypted with AES-256-CBCciphertext, useless without the key
—the hmac-secret value inside the keyyes, does not leave the device
$XDG_RUNTIME_DIR/bw-session-<uid>bw session key (tmpfs, mode 0600)yes, until logout of the last session, reboot or bwl

cred and salt by themselves reveal nothing: without the device on which the credential was created they cannot be used to obtain the secret. The actual persistent secret on disk is pw.enc, and it is encrypted. The only thing present in the clear is the session key: it lives in tmpfs, i.e. in RAM (tmpfs pages may end up in swap if it’s enabled).

bw-fido-enroll binding script

bash
#!/usr/bin/env bash
# Bind the Bitwarden master password to a FIDO2 key (hmac-secret).
#   bw-fido-enroll             — create a credential on the key, ask for the master password, store it
#                                encrypted with the key secret (touch the key twice)
#   bw-fido-enroll --selftest  — check that the key returns a stable secret (no password asked)
#   bw-fido-enroll --remove    — erase what was stored
# The password is read from the terminal only; only ciphertext reaches the disk (AES-256, key = FIDO2 reply).
set -euo pipefail
D="${BW_FIDO_DIR:-$HOME/.config/bw-fido}"
RP="bw.local"
b64rand() { head -c 32 /dev/urandom | base64 -w0; }
dev() { fido2-token -L | head -1 | cut -d: -f1; }
die() { echo "bw-fido-enroll: $*" >&2; exit 1; }
# Remove only our own files, never the whole directory (BW_FIDO_DIR may be set by hand)
wipe() { rm -f "$D/cred" "$D/salt" "$D/pw.enc"; rmdir "$D" 2>/dev/null || true; }
command -v fido2-cred >/dev/null || die "package fido2-tools is required"
DEV="$(dev)"; [[ -n "$DEV" ]] || die "no FIDO2 key found"

mkcred() { # mkcred -> prints the credential id
  local cdh; cdh="$(b64rand)"
  printf '%s\n%s\n%s\n%s\n' "$cdh" "$RP" "bw" "$(b64rand)" | fido2-cred -M -h "$DEV" | sed -n 5p
}
secret() { # secret <credid> <salt> -> hmac-secret (base64)
  printf '%s\n%s\n%s\n%s\n' "$(b64rand)" "$RP" "$1" "$2" | fido2-assert -G -h "$DEV" | tail -1
}

case "${1:-}" in
  --remove) wipe; echo "Erased (the credential is not resident, nothing is stored on the key)."; exit 0 ;;
  --selftest)
    echo "Touch 1 of 3: creating a test credential"; C="$(mkcred)" || die "the key did not create a credential"; S="$(b64rand)"
    echo "Touch 2 of 3"; A="$(secret "$C" "$S")" || die "the key did not return a secret"
    echo "Touch 3 of 3"; B="$(secret "$C" "$S")" || die "the key did not return a secret"
    [[ "${#A}" -eq 44 && "$A" == "$B" ]] && echo "OK: the key returns a stable secret (${#A} chars)" || die "secrets did not match"
    exit 0 ;;
esac

[[ -t 0 ]] || die "a terminal is required to enter the password"
umask 077; mkdir -p "$D"
[[ -f "$D/cred" ]] && die "already set up ($D); run --remove first"
echo "Touch 1 of 2: creating a credential on the key"
C="$(mkcred)" || die "the key did not create a credential"; [[ -n "$C" ]] || die "the key did not create a credential"
S="$(b64rand)"
echo "Touch 2 of 2: getting the secret"
K="$(secret "$C" "$S")" || die "the key did not return a secret"; [[ "${#K}" -eq 44 ]] || die "the key did not return a secret"
echo "Input is hidden. Check the layout: Caps Lock switches us/ru."
for n in 1 2 3; do
  IFS= read -rsp "Bitwarden master password (attempt $n of 3): " PW </dev/tty; echo
  if ! command -v bw >/dev/null; then echo "warning: bw not found, the password was NOT verified" >&2; break; fi
  BW_PW="$PW" bw unlock --passwordenv BW_PW --raw >/dev/null 2>&1 && break
  PW=""; echo "bw rejected the password (typo, wrong layout? was bw login done?)"
done
[[ -n "${PW:-}" ]] || { wipe; die "password not accepted, nothing saved"; }
printf '%s' "$PW" | openssl enc -aes-256-cbc -pbkdf2 -iter 200000 -salt -pass fd:3 -out "$D/pw.enc" 3< <(printf '%s\n' "$K")
printf '%s\n' "$C" > "$D/cred"; printf '%s\n' "$S" > "$D/salt"
unset PW K
echo "Done: $D. Check with: bwu (asks for a touch)."

Explanation by parts:

  • Device. fido2-token -L outputs a line like /dev/hidraw2: vendor=0x1050, product=0x0402 (…). The device name is the first field up to the colon, so cut -d: -f1. The first found key is used.
  • mkcred. Four lines are fed to fido2-cred -M: client data hash, RP ID, username and user ID. The hash and user ID here are random 32 bytes: there is no one to check the registration signature, only the credential ID is needed, and it appears as the fifth line of output. The -h flag enables hmac-secret; -r is not used, so the credential is non-resident.
  • secret. fido2-assert -G -h receives the client data hash, RP ID, credential ID and salt; the last line of output is the secret in base64, 44 characters.
  • --selftest. Creates a test credential and requests the secret twice with the same salt. Matching responses mean the key supports hmac-secret and returns a stable result. No password is asked and nothing is written to disk.
  • Password verification before saving. The password is read from the terminal without echo and immediately checked with a real bw unlock. Three attempts are allowed; if all fail the directory is removed and nothing is saved. If bw is not present on the host the check is skipped, the script prints a warning and saves the password as entered — install bw before binding.
  • Encryption. The key secret is passed to openssl via file descriptor 3 (-pass fd:3) from a process substitution 3< <(…), and the password is passed via stdin. Neither ends up in the command-line arguments visible in the process list. Process substitution is used instead of a here-string (3<<<): zsh implements here-strings with a temporary file, and the key secret would temporarily be on disk during openssl runtime. umask 077 makes the files accessible only to the owner.
  • --remove. Erases only its own files (cred, salt, pw.enc) and the directory if it is empty. rm -rf is not used here: BW_FIDO_DIR may be set manually, and a typo must not delete someone else’s directory. This is useful for rollback and re-binding: the script does not write over an existing setup.
  • Key errors. Calls to mkcred and secret are wrapped with || die: with set -e and pipefail otherwise the script would exit silently without its own message. The master password is read with IFS= read so spaces at the beginning or end of the password are not trimmed.

bwu and bwl functions

The file bw-session.zsh is sourced from ~/.zshrc (source). It provides two commands and unlocks the vault when a new local interactive shell starts if no existing session is available.

zsh
# Unlocked Bitwarden after login (sourced from zshrc).
#  - the session key lives in tmpfs (never on disk, but tmpfs pages may reach swap) until logout of the last
#    session, reboot or bwl
#  - in a new local interactive shell without a session: touch the FIDO2 key (if bw-fido-enroll was run),
#    otherwise type the password
#  - over SSH it does not open by itself (the key is in the host, not with you): run bwu
command -v bw >/dev/null 2>&1 || return 0

if [[ -n $XDG_RUNTIME_DIR && -d $XDG_RUNTIME_DIR ]]; then
  _bw_dir=$XDG_RUNTIME_DIR
else
  # no per-user runtime dir: use a private directory we own, never a shared predictable file name
  _bw_dir=/dev/shm/bw-$UID
  mkdir -p -m 700 "$_bw_dir" 2>/dev/null
  [[ -d $_bw_dir && -O $_bw_dir ]] || return 0
fi
_bw_file="$_bw_dir/bw-session-$UID"
_bw_fido="$HOME/.config/bw-fido"

_bw_unlock_raw() { # prints the session key
  local pw s dev k
  if [[ -f $_bw_fido/pw.enc ]] && command -v fido2-assert >/dev/null 2>&1 && [[ -n "$(fido2-token -L 2>/dev/null)" ]]; then
    dev="$(fido2-token -L | head -1 | cut -d: -f1)"
    echo "Touch the FIDO2 key..." >&2
    k="$(printf '%s\n%s\n%s\n%s\n' "$(head -c 32 /dev/urandom | base64 -w0)" bw.local "$(<$_bw_fido/cred)" "$(<$_bw_fido/salt)" \
        | fido2-assert -G -h "$dev" | tail -1)"
    # the key secret goes to openssl through a pipe, not through a here-string (zsh makes a temp file for it)
    [[ -n $k ]] && pw="$(openssl enc -d -aes-256-cbc -pbkdf2 -iter 200000 -pass fd:3 -in "$_bw_fido/pw.enc" 3< <(printf '%s\n' "$k") 2>/dev/null)"
    unset k
  fi
  if [[ -n $pw ]]; then
    if s="$(BW_PW="$pw" bw unlock --passwordenv BW_PW --raw 2>/dev/null)" && [[ -n $s ]]; then
      unset pw; print -r -- "$s"; return 0
    fi
    echo "The stored password was rejected: type the master password." >&2
  fi
  IFS= read -rs "pw?Bitwarden master password: " </dev/tty; echo >&2
  BW_PW="$pw" bw unlock --passwordenv BW_PW --raw 2>/dev/null
  local rc=$?; unset pw
  return $rc
}

bwu() { # unlock (if not yet)
  if [[ -n $BW_SESSION ]] && bw unlock --check >/dev/null 2>&1; then echo "Bitwarden is already unlocked"; return 0; fi
  if [[ "$(bw status 2>/dev/null | grep -o '"status":"[a-z]*"')" == *unauthenticated* ]]; then
    echo "First run: bw login (once)" >&2; return 1
  fi
  local s; s="$(_bw_unlock_raw)" || { echo "Could not unlock" >&2; return 1; }
  # subshell: umask 077 must not leak into the interactive shell; rename so nobody reads a half-written key
  ( umask 077; printf '%s' "$s" > "$_bw_file.$$" ) && mv -f "$_bw_file.$$" "$_bw_file" \
    || { echo "Could not store the session key" >&2; return 1; }
  export BW_SESSION="$s"; echo "Bitwarden unlocked"
}

bwl() { bw lock >/dev/null 2>&1; rm -f "$_bw_file"; unset BW_SESSION; echo "Bitwarden locked"; }

# Ctrl+C during the automatic unlock must not abort the rest of ~/.zshrc
_bw_autounlock() {
  setopt localtraps
  trap 'echo >&2; return 130' INT
  bwu
}

if [[ -o interactive && -z $BW_SESSION ]]; then
  if [[ -s $_bw_file && -O $_bw_file ]]; then
    export BW_SESSION="$(<$_bw_file)"
  elif [[ -t 0 && -z $SSH_CONNECTION ]]; then
    _bw_autounlock || true
  fi
fi

How this works:

  • _bw_unlock_raw tries the key only if pw.enc exists, fido2-assert is installed, and the key is visible in the system. If the key is absent, decryption fails, or bw rejects the decrypted password (for example, after a password change), the function asks for the master password from the keyboard. The password is passed to bw via an environment variable for a single command (--passwordenv BW_PW), and the function outputs only the session key (--raw).
  • bwu first checks whether the vault is already unlocked, then whether bw login was performed. If bw status shows unauthenticated, there is nothing to unlock and the function asks you to log in once. The session key is written to a file with mode 0600 (writing happens in a subshell so umask 077 does not persist in your shell, and first to a temporary file which is then renamed) and exported to BW_SESSION.
  • Session in tmpfs. The $XDG_RUNTIME_DIR directory (usually /run/user/<uid>) resides in memory and is removed on logout of the last user session or at reboot. If the variable is not set, the script creates its own directory /dev/shm/bw-<uid> with mode 700 and checks that the owner is you; a shared predictable file under /dev/shm is not used. The session key is not written to persistent storage, but tmpfs pages may go to swap if it is enabled (on Raspberry Pi OS swap is enabled by default).
  • bwl runs bw lock, removes the session file and unsets the variable.
  • Automatic invocation. When an interactive shell starts the block at the end of the file first looks for an existing session in tmpfs and checks that the file is owned by you. If none is found, bwu is called automatically, but only in a local shell: there must be a terminal and no SSH_CONNECTION. This condition describes any local interactive shell (including a terminal in a graphical session and a tmux pane without a session), not just the tty1 console. If you do not touch the key, each such shell will prompt for the password; you can interrupt the prompt with Ctrl+C: the trap on INT prevents truncating the rest of ~/.zshrc (without it the interrupt would stop loading the whole file).
  • Over SSH the vault does not open by itself. If a session already exists in tmpfs the shell will pick it up. If not, run bwu manually; if the key is inserted you will need to touch it physically, on the host. If the USB key is absent bwu will ask for the password.

Step-by-step setup

All commands are run on the host itself, as the user for whom unlocking is needed, with the key in USB:

bash
bw config server https://vault.example.ru   # once
bw login                                    # once, with two-step login if enabled
bw-fido-enroll --selftest                   # 3 touches: test the key, no password asked
bw-fido-enroll                              # 2 touches + master password (hidden input)
exec zsh                                    # re-read ~/.zshrc
bwu                                         # touch → "Bitwarden unlocked"
bw status                                   # shows "status":"unlocked" in the output

Order matters. bw login is needed before binding: without it bw unlock will reject any password, and all three attempts will fail. exec zsh is needed if the shell was started before bw-session.zsh was sourced in ~/.zshrc: the file is read only at shell start.

Touch the key immediately after the command starts and the key blinks. If you touch with a delay (on the order of several seconds; the exact threshold was not tested), fido2-assert will fail with FIDO_ERR_RX or 0x27.

To check that the session survives new shells: open a second terminal or a new tmux tab and run bw status — no touch needed. After bwl or a reboot bw status will show locked.

When diagnosing, do not print the password itself or the key’s response. Check lengths and return codes: the response of fido2-assert -G -h is 44 base64 characters, openssl enc -d outputs a string the length of your password, and bw unlock returns 0.

Threat model

The scheme protects against:

  • theft of a memory card or a disk copy: pw.enc is ciphertext, and the decryption key is provided only by the device;
  • reading ~/.config/bw-fido/ by another user on the host: mode 0600 and ciphertext protect it;
  • storing the master password on disk in cleartext and in shell history. While unlocked the password exists in the environment of the bw process (BW_PW) and in the shell variable; it can be read by another process of the same user or by root.

The scheme does not protect against:

  • a process of the same user or root while a session is open. The session key is in tmpfs and in BW_SESSION of each shell, and the session key means an unlocked vault. Therefore do not use this scheme on hosts where multiple people have root.
  • a person with physical access to the host and the key simultaneously. The secret is released on touch and PIN is not required;
  • substituted programs. If an attacker can modify ~/.zshrc, bw or openssl they will intercept the password on the next unlock;
  • a request you do not notice. Touching does not show which program and why accessed the key. A process of the same user can call fido2-assert with your cred and salt and obtain the secret at the moment you touch the key for another reason;
  • a long open session. There is no automatic timeout: the session is open until you run bwl or log out of the last session, and BW_SESSION is inherited by all child processes of the shell;
  • theft of the host with the key permanently inserted. Together with the host an attacker gets the key and cred, salt, pw.enc; touch does not require a PIN. The key by itself without those files is useless;
  • lack of a second factor when unlocking. bw unlock does not use the second factor: it is used only at login (bw login).

About PIN. hmac-secret exists in two variants on the key: with user verification (PIN) and without, and these secrets are different. The scripts request the touch-only secret. If you add the -v flag to fido2-assert, the key will require a PIN, but the response will be different, and pw.enc encrypted without the PIN will not decrypt. Switching to PIN requires editing both scripts and re-binding.

The Bitwarden vault is client-side encrypted, so the Vaultwarden server does not see this scheme and knows nothing about the key (“Password managers: Part 3 — Bitwarden and Vaultwarden”). The hardware key here caches the master password on a specific host and does not replace two-factor login to the vault itself.

Password change, lost key, updates

Changed the master password. pw.enc still contains the old password: bw will reject it, and bwu will ask you to type the master password manually (“The stored password was rejected”). To make touch work again, re-bind:

bash
bw-fido-enroll --remove
bw-fido-enroll

Lost or replaced the key. You cannot decrypt pw.enc without the old key, but you do not need to: you still have the master password in memory, and the key only kept a copy of it on this host. Keep a backup copy of the master password separate from the vault itself (for example on paper): if the “main password manager” is this vault, loss of the password means loss of the vault. If a copy of ~/.config/bw-fido (backup, memory card) might have gone with the lost key, change the master password. Until a new key is available, bwu will ask the password from the keyboard. With a new key perform the same --remove and bind again.

Spare key. The script works with the first found key and a single directory. A YubiKey cannot be cloned, so bind a spare key separately: the BW_FIDO_DIR variable lets bw-fido-enroll write data into another directory, for example BW_FIDO_DIR=~/.config/bw-fido-spare bw-fido-enroll when only the spare key is in USB. The _bw_unlock_raw function reads only ~/.config/bw-fido, so when switching to a spare key rename the directories or simply re-bind — it takes two touches and one password entry.

Updating scripts. The ~/.config/bw-fido/ directory is independent of script versions as long as the RP ID bw.local and the openssl parameters do not change. After updating bw-session.zsh run exec zsh.

Common errors

All these errors were encountered during setup:

SymptomCauseWhat to do
FIDO_ERR_INTERNAL immediately when creating the credentialthe device name was taken with the tail /dev/hidraw2: vendor=…take only the first field: cut -d: -f1
FIDO_ERR_RX or FIDO_ERR_OPERATION_DENIED (0x27) when obtaining the secretthe touch did not occur in time after the command startedtouch the key immediately when it blinks and retry
bw rejected the password (the script’s message) or The decryption operation failed (from bw)the wrong password was entered: typo or us/ru layoutcheck the keyboard layout; during binding you have three attempts
already set up (…); run --remove firstthe directory ~/.config/bw-fido already existsbw-fido-enroll --remove, then bind again; without --remove the password will not be updated
The stored password was rejected: type the master password.pw.enc contains the old password (after password change) or the decryption result is wrongtype the master password manually, then --remove and re-bind
bwu: command not foundthe shell was started before bw-session.zsh was sourced, or bw was not found in PATH at the moment of source (the file exits silently then)exec zsh; source the file after PATH is set up
First run: bw login (once), bw status shows unauthenticatedbw login was not performedbw login, then bwu
key not visible, fido2-token -L prints nothingkey not inserted or the user lacks permissions for the devicecheck USB, membership in plugdev (in an SSH session) and the udev rules from “Part 4 — FIDO2 and YubiKey: hmac-secret, libfido2 and access permissions”

Note on layout: password input is hidden on the Linux console and switching us/ru via Caps Lock is easy to miss. If a password “suddenly stopped working”, first check the keyboard layout.

When the scheme is appropriate

The scripts are intended for Linux with GNU base64 (uses base64 -w0; they will not work on macOS). The scheme is designed for a host with a single user and a local console, to which a FIDO2 key is permanently connected or inserted at login: a home server, Raspberry Pi, or an administrator’s workstation. It removes the need to type a long password while not leaving it on disk in cleartext. It is not suitable for shared servers where multiple people have root, nor for automated jobs without a person nearby: those cases require user isolation or separate accounts with minimal access to the necessary secrets.

// Similar task

If you are dealing with something similar

This article belongs to one of the main working topics. You can keep reading on the topic, go to the homepage to understand what I do, or open the service pages directly.

Article topic

Servers and infrastructure

VPS, Linux, web stack, migrations, hosting, databases, and core operations.

Typical tasks behind this topic

  • Move a site or service to a new server
  • Set up Linux, Nginx, databases, and backups
  • Figure out why the system behaves unstably

// Next step

If you need help with this topic, not just another article, it is better to go straight to the service page. The homepage and topic collection stay available as secondary routes.

Open services

// Contact

Need help?

Get in touch with me and I'll help solve the problem

I reply within one business day (03:00-13:00 GMT)

Or leave a request here:

Confirm that you are not a bot.

Write and get a quick reply