cryptex 3.0.0

Store and retrieve secrets in OS keyrings, encrypted SQLite or Turso files, in-memory and browser keyrings, or under a YubiHSM 2 or Nitrokey 3
/*
    Copyright Michael Lodder. All Rights Reserved.
    SPDX-License-Identifier: Apache-2.0
*/

//! Nitrokey 3 backed keyring, through FIDO2's `hmac-secret` extension: a
//! thin [`KmsBackend`](crate::kms::KmsBackend) on top of the shared [`kms`](crate::kms) layer.
//!
//! # Design
//!
//! A FIDO2 credential with `hmac-secret` holds a random 32-byte key that the
//! token generates and never exports. For each secret the token returns
//! `HMAC-SHA256(credential key, SHA-256(msg))`, which [`kms`](crate::kms)
//! uses as the per-entry encryption key. The credential is not stored on the
//! token; its ID is kept by the caller and passed in the connection string.
//!
//! Every `get_secret` and `set_secret` needs a touch on the token: the
//! firmware requires user presence for `hmac-secret`. Nothing here is
//! Nitrokey-specific, so any FIDO2 key with `hmac-secret` works, such as a
//! YubiKey or a SoloKey.
//!
//! # Connection string
//!
//! ```text
//! credential=<hex from setup> [pin=<FIDO2 PIN>] [rp_id=cryptex] [service=myapp]
//! ```
//!
//! # One-time setup
//!
//! Create the credential (one touch) and keep the returned ID:
//!
//! ```no_run
//! let credential = cryptex::nitrokey::NitrokeyKeyRing::setup("").unwrap();
//! let conn = format!("credential={} service=myapp", credential);
//! ```

use super::kms::{KmsBackend, KmsKeyRing, parse_pairs};
use super::*;
use crate::error::KeyRingError;
use ::ctap_hid_fido2::fidokey::get_assertion::get_assertion_params::Extension as AssertionExtension;
use ::ctap_hid_fido2::fidokey::make_credential::make_credential_params::Extension as CredentialExtension;
use ::ctap_hid_fido2::fidokey::{GetAssertionArgsBuilder, MakeCredentialArgsBuilder};
use ::ctap_hid_fido2::{Cfg, FidoKeyHid, FidoKeyHidFactory};
use sha2::{Digest, Sha256};
use std::str::FromStr;
use zeroize::Zeroize;

/// Relying party ID the credential is created under unless the connection
/// string names another. It only has to match between setup and use.
const DEFAULT_RP_ID: &str = "cryptex";

/// [`KmsBackend`] implementation backed by a FIDO2 token's `hmac-secret`.
pub struct NitrokeyBackend {
    device: FidoKeyHid,
    credential_id: Vec<u8>,
    rp_id: String,
    pin: Option<String>,
    /// `SHA-256("cryptex-fido2-device" ‖ credential_id)[..16]`. FIDO2 does
    /// not expose a serial number, but a credential ID only works on the
    /// token that issued it.
    device_id_bytes: [u8; 16],
    /// `hex(SHA-256(credential_id)[..8])`.
    key_id_str: String,
}

impl Drop for NitrokeyBackend {
    fn drop(&mut self) {
        self.pin.zeroize();
    }
}

impl KmsBackend for NitrokeyBackend {
    fn backend_name(&self) -> &'static str {
        "nitrokey"
    }

    fn key_id(&self) -> &str {
        &self.key_id_str
    }

    fn device_id(&self) -> [u8; 16] {
        self.device_id_bytes
    }

    /// CTAP has no command for random bytes, so the nonce uses the OS RNG
    /// alone.
    fn get_random(&self, _n: usize) -> Result<Vec<u8>> {
        Ok(Vec::new())
    }

    fn hmac_sha256(&self, msg: Vec<u8>) -> Result<[u8; 32]> {
        let salt: [u8; 32] = Sha256::digest(&msg).into();
        let builder = GetAssertionArgsBuilder::new(&self.rp_id, &salt)
            .credential_id(&self.credential_id)
            .extensions(&[AssertionExtension::HmacSecret(Some(salt))]);
        let args = match &self.pin {
            Some(pin) => builder.pin(pin).build(),
            None => builder.without_pin_and_uv().build(),
        };
        let assertions = self
            .device
            .get_assertion_with_args(&args)
            .map_err(fido_err)?;
        assertions
            .iter()
            .flat_map(|a| a.extensions.iter())
            .find_map(|e| match e {
                AssertionExtension::HmacSecret(Some(out)) => Some(*out),
                _ => None,
            })
            .ok_or_else(|| KeyRingError::GeneralError {
                msg: "the security key returned no hmac-secret output".to_string(),
            })
    }
}

/// Nitrokey (FIDO2 `hmac-secret`) keyring: one credential on the token,
/// unlimited AES-256-GCM encrypted secrets stored as local files under
/// `~/.cryptex/nitrokey/<service>/`.
pub type NitrokeyKeyRing = KmsKeyRing<NitrokeyBackend>;

impl KmsKeyRing<NitrokeyBackend> {
    /// One-time setup: create an `hmac-secret` credential on the token and
    /// return its ID as hex, for the `credential=` parameter.
    ///
    /// `connection_string` may set `pin` and `rp_id`; `credential` and
    /// `service` are ignored. The token asks for a touch.
    pub fn setup(connection_string: &str) -> Result<String> {
        let params: ConnectionParams = connection_string.parse()?;
        let device = open_device()?;
        let builder = MakeCredentialArgsBuilder::new(&params.rp_id, &random_challenge()?)
            .extensions(&[CredentialExtension::HmacSecret(Some(true))]);
        let args = match &params.pin {
            Some(pin) => builder.pin(pin).build(),
            None => builder.without_pin_and_uv().build(),
        };
        let attestation = device.make_credential_with_args(&args).map_err(fido_err)?;
        let enabled = attestation
            .extensions
            .iter()
            .any(|e| matches!(e, CredentialExtension::HmacSecret(Some(true))));
        if !enabled {
            return Err(KeyRingError::GeneralError {
                msg: "the security key did not enable hmac-secret for the credential".to_string(),
            });
        }
        Ok(hex::encode(attestation.credential_descriptor.id))
    }
}

impl NewKeyRing for KmsKeyRing<NitrokeyBackend> {
    fn new<S: AsRef<str>>(connection_string: S) -> Result<Self> {
        connection_string
            .as_ref()
            .parse::<ConnectionParams>()?
            .open()
    }
}

/// Connection parameters for [`NitrokeyKeyRing`].
///
/// ```text
/// credential=<hex> [pin=<FIDO2 PIN>] [rp_id=cryptex] [service=myapp]
/// ```
#[derive(Zeroize)]
#[zeroize(drop)]
pub struct ConnectionParams {
    /// The credential ID returned by [`NitrokeyKeyRing::setup`].
    pub credential: Vec<u8>,
    /// The token's FIDO2 PIN, if one is set.
    pub pin: Option<String>,
    /// Relying party ID the credential was created under (default
    /// `"cryptex"`).
    pub rp_id: String,
    /// Service / application name used to namespace entry files (default:
    /// `"default"`).
    pub service: String,
}

impl Default for ConnectionParams {
    fn default() -> Self {
        Self {
            credential: Vec::new(),
            pin: None,
            rp_id: DEFAULT_RP_ID.to_string(),
            service: "default".to_string(),
        }
    }
}

impl ConnectionParams {
    /// Open a [`NitrokeyKeyRing`] using these parameters.
    pub fn open(mut self) -> Result<NitrokeyKeyRing> {
        if self.credential.is_empty() {
            return Err(KeyRingError::GeneralError {
                msg: "credential= is required; create one with NitrokeyKeyRing::setup".to_string(),
            });
        }
        let credential_id = std::mem::take(&mut self.credential);
        let mut device_hash = Sha256::new();
        device_hash.update(b"cryptex-fido2-device");
        device_hash.update(&credential_id);
        let mut device_id_bytes = [0u8; 16];
        device_id_bytes.copy_from_slice(&device_hash.finalize()[..16]);
        let key_id_str = hex::encode(&Sha256::digest(&credential_id)[..8]);

        let backend = NitrokeyBackend {
            device: open_device()?,
            credential_id,
            rp_id: self.rp_id.clone(),
            pin: self.pin.take(),
            device_id_bytes,
            key_id_str,
        };
        KmsKeyRing::open(backend, &self.service)
    }

    fn set_param(&mut self, key: &str, value: &str) -> Result<()> {
        match key {
            "credential" => {
                self.credential = hex::decode(value).map_err(|_| KeyRingError::GeneralError {
                    msg: "credential must be hex".to_string(),
                })?
            }
            "pin" => self.pin = Some(value.to_string()),
            "rp_id" => self.rp_id = value.to_string(),
            "service" => self.service = value.to_string(),
            _ => {
                return Err(KeyRingError::GeneralError {
                    msg: format!("unknown parameter: '{}'", key),
                });
            }
        }
        Ok(())
    }
}

impl FromStr for ConnectionParams {
    type Err = KeyRingError;

    fn from_str(s: &str) -> Result<Self> {
        let mut params = Self::default();
        parse_pairs(s, |key, value| params.set_param(key, value))?;
        Ok(params)
    }
}

/// Open the one FIDO2 token plugged in. Touch prompts go to stderr.
fn open_device() -> Result<FidoKeyHid> {
    let mut cfg = Cfg::init().with_keep_alive_msg_to_stderr(true);
    cfg.keep_alive_msg = "Touch your security key".to_string();
    FidoKeyHidFactory::create(&cfg).map_err(fido_err)
}

fn random_challenge() -> Result<[u8; 32]> {
    let mut challenge = [0u8; 32];
    getrandom::fill(&mut challenge).map_err(|e| KeyRingError::GeneralError {
        msg: format!("unable to generate a challenge: {}", e),
    })?;
    Ok(challenge)
}

fn fido_err(e: impl std::fmt::Display) -> KeyRingError {
    KeyRingError::GeneralError {
        msg: format!("security key: {}", e),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_connection_strings() {
        let p: ConnectionParams = "credential=0aff pin='12 34' rp_id=example service=myapp"
            .parse()
            .unwrap();
        assert_eq!(p.credential, vec![0x0a, 0xff]);
        assert_eq!(p.pin.as_deref(), Some("12 34"));
        assert_eq!((p.rp_id.as_str(), p.service.as_str()), ("example", "myapp"));

        let d: ConnectionParams = "".parse().unwrap();
        assert_eq!(
            (d.rp_id.as_str(), d.service.as_str()),
            ("cryptex", "default")
        );
        assert!(d.pin.is_none());

        for bad in ["credential=xyz", "unknown=1", "pin='open"] {
            assert!(bad.parse::<ConnectionParams>().is_err(), "accepted: {bad}");
        }
    }

    #[test]
    fn open_needs_a_credential() {
        let err = "service=x"
            .parse::<ConnectionParams>()
            .unwrap()
            .open()
            .err()
            .unwrap();
        assert!(err.to_string().contains("credential="), "{err}");
    }

    /// Needs a FIDO2 token with hmac-secret plugged in: one touch for setup,
    /// then one for each get or set.
    #[test]
    #[ignore = "requires a FIDO2 security key and touches"]
    fn lifecycle_on_a_real_token() {
        let credential = NitrokeyKeyRing::setup("").expect("setup");
        let conn = format!("credential={} service=cryptex-nitrokey-test", credential);
        let mut ring = NitrokeyKeyRing::new(&conn).expect("open");
        DynKeyRing::set_secret(&mut ring, "k", b"nitro secret").expect("set");
        assert_eq!(
            DynKeyRing::get_secret(&mut ring, "k")
                .expect("get")
                .as_slice(),
            b"nitro secret"
        );
        DynKeyRing::delete_secret(&mut ring, "k").expect("delete");
        assert!(DynKeyRing::get_secret(&mut ring, "k").is_err());
    }
}