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;
const DEFAULT_RP_ID: &str = "cryptex";
pub struct NitrokeyBackend {
device: FidoKeyHid,
credential_id: Vec<u8>,
rp_id: String,
pin: Option<String>,
device_id_bytes: [u8; 16],
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
}
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(),
})
}
}
pub type NitrokeyKeyRing = KmsKeyRing<NitrokeyBackend>;
impl KmsKeyRing<NitrokeyBackend> {
pub fn setup(connection_string: &str) -> Result<String> {
let params: ConnectionParams = connection_string.parse()?;
let device = open_device()?;
let builder = MakeCredentialArgsBuilder::new(¶ms.rp_id, &random_challenge()?)
.extensions(&[CredentialExtension::HmacSecret(Some(true))]);
let args = match ¶ms.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()
}
}
#[derive(Zeroize)]
#[zeroize(drop)]
pub struct ConnectionParams {
pub credential: Vec<u8>,
pub pin: Option<String>,
pub rp_id: String,
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 {
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)
}
}
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}");
}
#[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());
}
}