diff --git a/crates/rns-ratkey/HARDWARE_STATUS.md b/crates/rns-ratkey/HARDWARE_STATUS.md index 2dfc8d9..5557c15 100644 --- a/crates/rns-ratkey/HARDWARE_STATUS.md +++ b/crates/rns-ratkey/HARDWARE_STATUS.md @@ -1,21 +1,48 @@ # RatKey Hardware Status -RatKey hardware identity support is intentionally not release-grade until it is -verified against real devices. The mock-backed tests cover public identity -shape, signing, ECDH, decrypt flow, and fail-closed key mismatch behavior, but -they do not prove PIV transport, touch/PIN policy, or X.509 chain verification. +RatKey hardware identity support is experimental. The runtime path (sign, ECDH, +decrypt, metadata pubkey read) is now validated on a real device; provisioning +on-device and attestation-chain verification are not yet implemented. -Required before hardware RatKey is documented as supported: +## Architecture (done) -- Replace the mock-only `HardwareIdentity` session storage with a real PIV - backend abstraction and YubiKey/Nitrokey implementations. -- Verify signing and ECDH against physical YubiKeys, including disconnect, - wrong PIN, touch timeout, and slot mismatch cases. -- Implement cryptographic attestation certificate chain verification against - the bundled Yubico roots and intermediates. -- Decide and document the ratchet policy for hardware identities. PIV cannot - hold Reticulum ratchet private keys, so enforced-ratchet decrypt currently - fails closed. +- `PivTransport` is the platform seam: APDU bytes in, response bytes out. + `PivSession` builds every PIV operation on `apdu` over that seam and is + transport-agnostic (compiles with no features). +- `PcscTransport` (behind the `hardware` feature) is the desktop PC/SC + implementation; `PivSession::::connect()` is the entry point. + Mobile NFC/USB transports implement `PivTransport` from the application layer. +- `HardwareIdentity` holds a `Box`, implemented by both + `PivSession` (real token, any transport) and `MockPivSession`. +- `PivSession::lock()` / `HardwareIdentity::lock()` re-select the PIV applet to + drop the on-card PIN cache (mechanism for app-side session timeout / lock-on-quit). + +## Validated on hardware (YubiKey 5, firmware 5.7.4) + +Via `rnid-rs hw verify` / `hw test` against PIN-once + touch-never Ed25519 (9A) +and X25519 (9D) keys: + +- `parse_metadata_public_key` reads the correct pubkey from GET METADATA + (confirmed against ykman-exported ground truth — the layout assumption held). +- Ed25519 signing on slot 9A; signature verifies against the slot pubkey. +- X25519 ECDH on slot 9D; shared secret symmetric with a software peer. +- `HardwareIdentity` decrypt end-to-end (on-device ECDH → HKDF → AES token). + +## Still required before hardware RatKey is documented as supported + +- **Implement PIV management-key authentication.** `hw provision` only does + `verify_pin`, but PIV key *generation* (GENERATE ASYMMETRIC) requires admin + auth via GENERAL AUTHENTICATE on slot 9B. Hardware validation above used + ykman-generated keys; our own provisioning cannot create keys on-device yet. + YubiKey 5.7 defaults the management key to AES-192. Required for in-app + provisioning in Ratspeak. +- Cryptographic attestation certificate chain verification against the bundled + Yubico roots (`attestation.rs` is metadata/OID extraction only; `chain_verified` + is always false). +- Edge cases on a real device: disconnect mid-operation, wrong PIN / lockout, + touch timeout (if touch is ever enabled), and the `from_hwid` key-mismatch guard. +- Decide and document the ratchet policy for hardware identities. PIV cannot hold + Reticulum ratchet private keys, so enforced-ratchet decrypt fails closed. - Add hardware-gated tests that are skipped by default but run when a device is explicitly selected by environment/config. diff --git a/crates/rns-ratkey/src/apdu.rs b/crates/rns-ratkey/src/apdu.rs index c342ea6..11b4b38 100644 --- a/crates/rns-ratkey/src/apdu.rs +++ b/crates/rns-ratkey/src/apdu.rs @@ -48,6 +48,8 @@ const TAG_PIN_POLICY: u8 = 0xAA; const TAG_TOUCH_POLICY: u8 = 0xAB; const TAG_OBJECT_ID: u8 = 0x5C; const TAG_ECC_POINT: u8 = 0x86; +/// GET METADATA public-key field (Yubico). +const TAG_METADATA_PUBLIC_KEY: u8 = 0x04; /// Cert object ID for slot 9A (Authentication). pub const OBJ_ID_9A: &[u8] = &[0x5F, 0xC1, 0x05]; @@ -293,6 +295,31 @@ pub fn parse_ecdh_response(data: &[u8]) -> Result<[u8; 32], RatkeyError> { Ok(out) } +/// GET METADATA public key: field tag 0x04, then EC point tag 0x86 → 32 bytes. +/// `find_tlv_value` recurses into a `7F49` wrapper if present, so both the +/// bare (`86 20 ..`) and wrapped (`7F49 .. 86 20 ..`) encodings resolve. +/// Yubico 5.3+ extension; Nitrokey 3 does not implement GET METADATA. +pub fn parse_metadata_public_key(metadata: &[u8]) -> Result<[u8; 32], RatkeyError> { + let pubkey_field = + find_tlv_value(metadata, TAG_METADATA_PUBLIC_KEY).ok_or(RatkeyError::Apdu { + sw1: 0x6A, + sw2: 0x80, + })?; + let point = find_tlv_value(pubkey_field, TAG_ECC_POINT).ok_or(RatkeyError::Apdu { + sw1: 0x6A, + sw2: 0x80, + })?; + if point.len() != 32 { + return Err(RatkeyError::InvalidHwid(format!( + "expected 32-byte public key in metadata, got {} bytes", + point.len() + ))); + } + let mut out = [0u8; 32]; + out.copy_from_slice(point); + Ok(out) +} + // Recurse into 7C / AC / 53 / any 2-byte tag (7F49 etc) to find a single-byte tag. fn find_tlv_value(data: &[u8], target_tag: u8) -> Option<&[u8]> { let mut pos = 0; @@ -632,6 +659,47 @@ mod tests { assert_eq!(secret, [0xCC; 32]); } + #[test] + fn test_parse_metadata_public_key_bare() { + // Slot metadata: 01(algo) 02(policy) 03(origin) 04(pubkey = 86 20 <32>). + // Layout pending confirmation against a real YubiKey GET METADATA response. + let mut meta = vec![ + 0x01, + 0x01, + ALG_ED25519, + 0x02, + 0x02, + PIN_POLICY_ONCE, + TOUCH_POLICY_ALWAYS, + 0x03, + 0x01, + 0x01, + 0x04, + 0x22, + 0x86, + 0x20, + ]; + meta.extend_from_slice(&[0xAB; 32]); + assert_eq!(parse_metadata_public_key(&meta).unwrap(), [0xAB; 32]); + } + + #[test] + fn test_parse_metadata_public_key_7f49_wrapped() { + // Same, but the point is wrapped in a 7F49 template (04 25 7F49 22 86 20 <32>). + let mut meta = vec![ + 0x01, 0x01, ALG_X25519, 0x04, 0x25, 0x7F, 0x49, 0x22, 0x86, 0x20, + ]; + meta.extend_from_slice(&[0xCD; 32]); + assert_eq!(parse_metadata_public_key(&meta).unwrap(), [0xCD; 32]); + } + + #[test] + fn test_parse_metadata_public_key_missing_field() { + // No 0x04 field present. + let meta = vec![0x01, 0x01, ALG_ED25519, 0x03, 0x01, 0x01]; + assert!(parse_metadata_public_key(&meta).is_err()); + } + #[test] fn test_parse_generate_response_wrong_size() { let mut response = vec![0x7F, 0x49, 0x12, 0x86, 0x10]; diff --git a/crates/rns-ratkey/src/detect.rs b/crates/rns-ratkey/src/detect.rs index 55fd5bc..1e69a15 100644 --- a/crates/rns-ratkey/src/detect.rs +++ b/crates/rns-ratkey/src/detect.rs @@ -1,9 +1,4 @@ -//! PC/SC reader enumeration; filters to YubiKey 5 / Nitrokey 3 by reader name. - -use pcsc::{Card, Context, Protocols, Scope, ShareMode}; -use tracing::{debug, info, warn}; - -use crate::error::RatkeyError; +//! Device classification (always available) + PC/SC reader enumeration (behind `hardware`). #[derive(Debug, Clone)] pub struct DeviceInfo { @@ -47,6 +42,14 @@ pub fn detect_device_type(reader_name: &str) -> DeviceType { } } +#[cfg(feature = "hardware")] +use pcsc::{Card, Context, Protocols, Scope, ShareMode}; +#[cfg(feature = "hardware")] +use tracing::{debug, info, warn}; +#[cfg(feature = "hardware")] +use crate::error::RatkeyError; + +#[cfg(feature = "hardware")] pub fn list_readers() -> Result, RatkeyError> { let ctx = Context::establish(Scope::User)?; @@ -64,6 +67,7 @@ pub fn list_readers() -> Result, RatkeyError> { Ok(names) } +#[cfg(feature = "hardware")] pub fn detect_devices() -> Result, RatkeyError> { let readers = list_readers()?; let mut devices = Vec::new(); @@ -101,6 +105,7 @@ pub fn detect_devices() -> Result, RatkeyError> { Ok(devices) } +#[cfg(feature = "hardware")] fn try_connect_piv(reader_name: &str) -> Result { use crate::apdu; @@ -150,6 +155,7 @@ fn try_connect_piv(reader_name: &str) -> Result { /// Best-effort serial/firmware read. Yubico proprietary INS — Nitrokey 3 returns (None, None). /// APDU errors are tolerated; never fails a connection. +#[cfg(feature = "hardware")] pub(crate) fn read_identity(card: &Card, device_type: DeviceType) -> (Option, Option) { use crate::apdu; diff --git a/crates/rns-ratkey/src/hardware.rs b/crates/rns-ratkey/src/hardware.rs index 0c6fdfd..5a87f54 100644 --- a/crates/rns-ratkey/src/hardware.rs +++ b/crates/rns-ratkey/src/hardware.rs @@ -1,5 +1,6 @@ -//! `HardwareIdentity`: public-key-only `Identity` + PIV session for private ops. -//! Wire-compatible with software identities. +//! `HardwareIdentity`: a public-key-only `Identity` whose private ops are served +//! by an `IdentityBackend` (real PIV session or mock). Wire-compatible with +//! software identities. use std::path::Path; @@ -7,71 +8,132 @@ use rns_crypto::hkdf::derive_key_64; use rns_crypto::token; use rns_identity::identity::Identity; +use crate::apdu::{SLOT_AUTHENTICATION as SLOT_9A, SLOT_KEY_MANAGEMENT as SLOT_9D}; use crate::error::RatkeyError; use crate::hwid::HwidConfig; -use crate::mock::{MockPivSession, SLOT_9A, SLOT_9D}; +use crate::mock::MockPivSession; +use crate::session::PivSession; +use crate::transport::PivTransport; + +/// The private-key operations `HardwareIdentity` needs from a token. Implemented +/// by `PivSession` (any transport) and `MockPivSession`, so the runtime +/// identity is backend-agnostic. +pub trait IdentityBackend { + fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError>; + fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError>; + fn read_ed25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError>; + fn read_x25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError>; + fn is_connected(&self) -> bool; + /// Re-lock the session (require PIN again on the next op). + fn lock(&mut self) -> Result<(), RatkeyError>; +} + +// Inherent methods take precedence over trait methods, so these delegate without recursing. +impl IdentityBackend for PivSession { + fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> { + self.sign_ed25519(slot, message) + } + fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> { + self.ecdh_x25519(slot, peer_pub) + } + fn read_ed25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> { + self.read_public_key(slot) + } + fn read_x25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> { + self.read_public_key(slot) + } + fn is_connected(&self) -> bool { + self.is_connected() + } + fn lock(&mut self) -> Result<(), RatkeyError> { + self.lock() + } +} + +impl IdentityBackend for MockPivSession { + fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> { + self.sign_ed25519(slot, message) + } + fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> { + self.ecdh_x25519(slot, peer_pub) + } + fn read_ed25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> { + // Shared borrow so only the inherent `&self` method applies (not this trait method). + (&*self).read_ed25519_public(slot) + } + fn read_x25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> { + (&*self).read_x25519_public(slot) + } + fn is_connected(&self) -> bool { + self.is_connected() + } + fn lock(&mut self) -> Result<(), RatkeyError> { + self.lock(); + Ok(()) + } +} pub struct HardwareIdentity { pub identity: Identity, pub config: HwidConfig, ed25519_pub: [u8; 32], x25519_pub: [u8; 32], - // Mock session storage keeps the current API testable until the real PIV - // backend is wired. See crates/rns-ratkey/HARDWARE_STATUS.md. - mock_session: Option, + backend: Box, } impl HardwareIdentity { - pub fn from_hwid_mock( + /// Build from a `.hwid` config + a backend. Fail-closed: the device's slot + /// public keys must match the published identity. + pub fn from_hwid( config: HwidConfig, - session: MockPivSession, + mut backend: Box, ) -> Result { let ed25519_pub = config.ed25519_pub_bytes()?; let x25519_pub = config.x25519_pub_bytes()?; - // Fail closed: published identity hash must map to keys actually on the device. - let session_ed = session.read_ed25519_public(SLOT_9A)?; - let session_x = session.read_x25519_public(SLOT_9D)?; + let session_ed = backend.read_ed25519_public(SLOT_9A)?; + let session_x = backend.read_x25519_public(SLOT_9D)?; if session_ed != ed25519_pub || session_x != x25519_pub { return Err(RatkeyError::KeyMismatch); } - let mut pub_key_bytes = [0u8; 64]; - pub_key_bytes[..32].copy_from_slice(&x25519_pub); - pub_key_bytes[32..].copy_from_slice(&ed25519_pub); - let identity = Identity::from_public_key(&pub_key_bytes) - .map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))?; - + let identity = build_identity(&ed25519_pub, &x25519_pub)?; Ok(Self { identity, config, ed25519_pub, x25519_pub, - mock_session: Some(session), + backend, }) } - pub fn from_file_mock(path: &Path, session: MockPivSession) -> Result { + pub fn from_file( + path: &Path, + backend: Box, + ) -> Result { let config = HwidConfig::from_file(path)?; - Self::from_hwid_mock(config, session) + Self::from_hwid(config, backend) } - /// Test-only: build without `.hwid`; skips key-mismatch guard. - pub fn from_keys_mock( + /// Test / first-bring-up: build without a `.hwid` and skip the key-mismatch + /// guard, so sign/ECDH can be validated independently of metadata pubkey + /// readback. + pub fn from_keys( ed25519_pub: [u8; 32], x25519_pub: [u8; 32], - session: MockPivSession, + backend: Box, ) -> Result { + let identity = build_identity(&ed25519_pub, &x25519_pub)?; let config = HwidConfig { identity: crate::hwid::HwidIdentity { - hash: String::new(), + hash: hex::encode(identity.hash), nickname: "test".to_string(), created_at: 0, }, device: crate::hwid::HwidDevice { - device_type: session.device_type.clone(), - serial: session.serial, - firmware: session.firmware.clone(), + device_type: "unknown".to_string(), + serial: 0, + firmware: "unknown".to_string(), }, keys: crate::hwid::HwidKeys { ed25519_pub: hex::encode(ed25519_pub), @@ -91,22 +153,12 @@ impl HardwareIdentity { backup: Default::default(), }; - let mut pub_key_bytes = [0u8; 64]; - pub_key_bytes[..32].copy_from_slice(&x25519_pub); - pub_key_bytes[32..].copy_from_slice(&ed25519_pub); - let identity = Identity::from_public_key(&pub_key_bytes) - .map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))?; - - let mut config = config; - // Hash is derived from the Identity so the .hwid stays consistent. - config.identity.hash = hex::encode(identity.hash); - Ok(Self { identity, config, ed25519_pub, x25519_pub, - mock_session: Some(session), + backend, }) } @@ -136,13 +188,11 @@ impl HardwareIdentity { } pub fn sign(&mut self, message: &[u8]) -> Result<[u8; 64], RatkeyError> { - let session = self.mock_session.as_mut().ok_or(RatkeyError::NoDevice)?; - session.sign_ed25519(SLOT_9A, message) + self.backend.sign_ed25519(SLOT_9A, message) } pub fn ecdh(&mut self, peer_pub_bytes: &[u8; 32]) -> Result<[u8; 32], RatkeyError> { - let session = self.mock_session.as_mut().ok_or(RatkeyError::NoDevice)?; - session.ecdh_x25519(SLOT_9D, peer_pub_bytes) + self.backend.ecdh_x25519(SLOT_9D, peer_pub_bytes) } /// Ciphertext = ephemeral_pub(32) || AES-256-CBC token. Mirrors `Identity::decrypt` @@ -190,23 +240,38 @@ impl HardwareIdentity { } pub fn is_connected(&self) -> bool { - self.mock_session.as_ref().is_some_and(|s| s.is_connected()) + self.backend.is_connected() } + + /// Re-lock the session; the next sign/ECDH will require the PIN again. + /// The app calls this on its session timeout and on quit. + pub fn lock(&mut self) -> Result<(), RatkeyError> { + self.backend.lock() + } +} + +fn build_identity(ed25519_pub: &[u8; 32], x25519_pub: &[u8; 32]) -> Result { + let mut pub_key_bytes = [0u8; 64]; + pub_key_bytes[..32].copy_from_slice(x25519_pub); + pub_key_bytes[32..].copy_from_slice(ed25519_pub); + Identity::from_public_key(&pub_key_bytes) + .map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}"))) } #[cfg(test)] mod tests { use super::*; + use crate::mock::{SLOT_9A as MOCK_9A, SLOT_9D as MOCK_9D}; use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey}; use rns_identity::identity::Identity; #[test] - fn test_from_keys_mock() { + fn test_from_keys() { let session = MockPivSession::with_keys(); - let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); - let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); + let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap(); + let x_pub = session.read_x25519_public(MOCK_9D).unwrap(); - let hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + let hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap(); assert_eq!(hw.ed25519_public(), &ed_pub); assert_eq!(hw.x25519_public(), &x_pub); assert!(!hw.hash_hex().is_empty()); @@ -215,9 +280,9 @@ mod tests { #[test] fn test_sign_and_verify() { let session = MockPivSession::with_keys(); - let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); - let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); - let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap(); + let x_pub = session.read_x25519_public(MOCK_9D).unwrap(); + let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap(); let message = b"ratkey hardware identity test"; let sig = hw.sign(message).unwrap(); @@ -231,9 +296,9 @@ mod tests { let ed_seed = [0x42u8; 32]; let x_secret = [0x43u8; 32]; let session = MockPivSession::with_key_bytes(&ed_seed, &x_secret); - let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); - let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); - let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap(); + let x_pub = session.read_x25519_public(MOCK_9D).unwrap(); + let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap(); let mut prv_bytes = [0u8; 64]; prv_bytes[..32].copy_from_slice(&x_secret); @@ -245,10 +310,7 @@ mod tests { let hw_sig = hw.sign(message).unwrap(); let sw_sig = sw_identity.sign(message).unwrap(); - assert_eq!( - hw_sig, sw_sig, - "hardware and software signatures must match" - ); + assert_eq!(hw_sig, sw_sig, "hardware and software signatures must match"); assert_eq!(hw.identity.hash, sw_identity.hash); assert_eq!(hw.get_public_key(), sw_identity.get_public_key()); } @@ -256,9 +318,9 @@ mod tests { #[test] fn test_ecdh_with_software_peer() { let session = MockPivSession::with_keys(); - let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); - let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); - let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap(); + let x_pub = session.read_x25519_public(MOCK_9D).unwrap(); + let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap(); let peer_prv = X25519PrivateKey::generate(); let peer_pub = peer_prv.public_key(); @@ -277,9 +339,9 @@ mod tests { let ed_seed = [0x42u8; 32]; let x_secret = [0x43u8; 32]; let session = MockPivSession::with_key_bytes(&ed_seed, &x_secret); - let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); - let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); - let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap(); + let x_pub = session.read_x25519_public(MOCK_9D).unwrap(); + let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap(); let mut prv_bytes = [0u8; 64]; prv_bytes[..32].copy_from_slice(&x_secret); @@ -296,9 +358,9 @@ mod tests { #[test] fn test_encrypt_from_other_identity() { let session = MockPivSession::with_keys(); - let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); - let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); - let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap(); + let x_pub = session.read_x25519_public(MOCK_9D).unwrap(); + let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap(); let _sender = Identity::new(); @@ -310,27 +372,16 @@ mod tests { #[test] fn test_disconnect_fails_operations() { - let session = MockPivSession::with_keys(); - let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap(); - let x_pub = session.read_x25519_public(SLOT_9D).unwrap(); - let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap(); + let mut session = MockPivSession::with_keys(); + let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap(); + let x_pub = session.read_x25519_public(MOCK_9D).unwrap(); + session.disconnect(); - assert!(hw.is_connected()); - hw.mock_session.as_mut().unwrap().disconnect(); + let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap(); assert!(!hw.is_connected()); - assert!(matches!(hw.sign(b"test"), Err(RatkeyError::Disconnected))); } - #[test] - fn test_key_mismatch_rejected() { - // from_keys_mock does not cross-check; the .hwid path does (test_hwid_key_mismatch). - let session = MockPivSession::with_keys(); - let wrong_ed = [0xFFu8; 32]; - let wrong_x = [0xFFu8; 32]; - let _result = HardwareIdentity::from_keys_mock(wrong_ed, wrong_x, session); - } - #[test] fn test_hwid_key_mismatch() { let session = MockPivSession::with_keys(); @@ -363,7 +414,170 @@ mod tests { backup: Default::default(), }; - let result = HardwareIdentity::from_hwid_mock(config, session); + let result = HardwareIdentity::from_hwid(config, Box::new(session)); assert!(matches!(result, Err(RatkeyError::KeyMismatch))); } + + // --- Real backend path over a canned-APDU transport --------------------- + // MockPivSession implements IdentityBackend directly and never touches + // PivSession. These exercise the production path (PivSession ops + its + // IdentityBackend impl + read_public_key→parse + slot routing) without a + // device. Caveat: the fake uses the *assumed* metadata layout, so it + // validates glue, not the real byte layout — that stays hardware-only. + + use crate::detect::DeviceType; + use crate::session::DeviceMeta; + use crate::transport::PivTransport; + + struct FakeTransport { + ed_pub: [u8; 32], + x_pub: [u8; 32], + sig: [u8; 64], + secret: [u8; 32], + } + + impl FakeTransport { + fn metadata(key: &[u8; 32]) -> Vec { + // 01(algo) 04(pubkey = 86 20 <32>) + SW 90 00 + let mut v = vec![0x01, 0x01, 0xE0, 0x04, 0x22, 0x86, 0x20]; + v.extend_from_slice(key); + v.extend_from_slice(&[0x90, 0x00]); + v + } + } + + impl PivTransport for FakeTransport { + fn transmit(&mut self, apdu: &[u8]) -> Result, RatkeyError> { + let (ins, p1, p2) = (apdu[1], apdu[2], apdu[3]); + match ins { + 0xA4 => Ok(vec![0x90, 0x00]), // SELECT (applet / re-lock) + 0x20 => Ok(vec![0x90, 0x00]), // VERIFY PIN + 0x87 if p1 == 0xE0 => { + assert_eq!(p2, 0x9A, "sign must target slot 9A"); + let mut v = vec![0x7C, 0x42, 0x82, 0x40]; + v.extend_from_slice(&self.sig); + v.extend_from_slice(&[0x90, 0x00]); + Ok(v) + } + 0x87 if p1 == 0xE1 => { + assert_eq!(p2, 0x9D, "ECDH must target slot 9D"); + let mut v = vec![0x7C, 0x22, 0x82, 0x20]; + v.extend_from_slice(&self.secret); + v.extend_from_slice(&[0x90, 0x00]); + Ok(v) + } + 0xF7 => { + // GET METADATA: key keyed by requested slot, so a wrong-slot + // read returns the wrong key. + let key = match p2 { + 0x9A => &self.ed_pub, + 0x9D => &self.x_pub, + other => panic!("unexpected metadata slot 0x{other:02X}"), + }; + Ok(Self::metadata(key)) + } + other => panic!("unexpected INS 0x{other:02X}"), + } + } + fn is_connected(&self) -> bool { + true + } + } + + fn fake_meta() -> DeviceMeta { + DeviceMeta { + device_type: DeviceType::YubiKey5, + serial: Some(1), + firmware: Some("5.7.4".to_string()), + } + } + + #[test] + fn test_pivsession_ops_over_fake_transport() { + let ed_pub = [0x11u8; 32]; + let x_pub = [0x22u8; 32]; + let sig = [0x33u8; 64]; + let secret = [0x44u8; 32]; + let fake = FakeTransport { + ed_pub, + x_pub, + sig, + secret, + }; + let mut session = PivSession::new(fake, fake_meta()); + + assert_eq!(session.sign_ed25519(SLOT_9A, b"msg").unwrap(), sig); + assert_eq!(session.ecdh_x25519(SLOT_9D, &[0u8; 32]).unwrap(), secret); + // read_public_key routes the slot and runs the metadata parser. + assert_eq!(session.read_public_key(SLOT_9A).unwrap(), ed_pub); + assert_eq!(session.read_public_key(SLOT_9D).unwrap(), x_pub); + // lock() re-selects the applet (SELECT APDU) without error. + session.lock().unwrap(); + } + + #[test] + fn test_lock_requires_pin_again() { + // End-to-end session lock on the mock path: sign works, lock, then the + // next op needs the PIN again. + let session = MockPivSession::with_keys(); + let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap(); + let x_pub = session.read_x25519_public(MOCK_9D).unwrap(); + let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap(); + + assert!(hw.sign(b"m").is_ok()); + hw.lock().unwrap(); + assert!(matches!(hw.sign(b"m"), Err(RatkeyError::PinRequired))); + } + + #[test] + fn test_hardware_identity_from_hwid_over_real_backend() { + // Closest mock-free representation of the runtime path: HardwareIdentity + // over a real PivSession backend — guard reads pubkeys via metadata, then + // sign dispatches to slot 9A. + let ed_prv = rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&[0x42u8; 32]); + let ed_pub = ed_prv.public_key().to_bytes(); + let x_prv = X25519PrivateKey::from_bytes(&[0x43u8; 32]); + let x_pub = x_prv.public_key().to_bytes(); + let sig = [0x33u8; 64]; + + let fake = FakeTransport { + ed_pub, + x_pub, + sig, + secret: [0x44u8; 32], + }; + let session = PivSession::new(fake, fake_meta()); + + let config = HwidConfig { + identity: crate::hwid::HwidIdentity { + hash: "test".to_string(), + nickname: "fake".to_string(), + created_at: 0, + }, + device: crate::hwid::HwidDevice { + device_type: "yubikey5".to_string(), + serial: 1, + firmware: "5.7.4".to_string(), + }, + keys: crate::hwid::HwidKeys { + ed25519_pub: hex::encode(ed_pub), + x25519_pub: hex::encode(x_pub), + }, + slots: crate::hwid::HwidSlots { + signing: "9A".to_string(), + encryption: "9D".to_string(), + }, + policy: crate::hwid::HwidPolicy { + pin_cache_timeout: 300, + touch_signing: "always".to_string(), + touch_encryption: "cached".to_string(), + }, + attestation: Default::default(), + app: Default::default(), + backup: Default::default(), + }; + + let mut hw = HardwareIdentity::from_hwid(config, Box::new(session)).unwrap(); + assert_eq!(hw.sign(b"announce").unwrap(), sig); + } } diff --git a/crates/rns-ratkey/src/lib.rs b/crates/rns-ratkey/src/lib.rs index 2701258..5d759c4 100644 --- a/crates/rns-ratkey/src/lib.rs +++ b/crates/rns-ratkey/src/lib.rs @@ -1,24 +1,34 @@ //! Hardware-backed identity (YubiKey 5, Nitrokey 3) via PIV. Ed25519 sign + X25519 //! ECDH keys live on-device; only public keys and results leave the token. -//! Wire-compatible with software identities. `hardware` feature enables real PIV via `pcsc`. +//! Wire-compatible with software identities. +//! +//! The PIV protocol logic (`PivSession`, `apdu`) is transport-agnostic; the +//! `PivTransport` seam isolates platform access. The `hardware` feature adds the +//! PC/SC transport (`PcscTransport`) and its `connect()` entry points. Mobile +//! NFC/USB transports implement `PivTransport` from the application layer. pub mod apdu; pub mod attestation; +pub mod detect; pub mod error; pub mod hardware; pub mod hwid; pub mod mock; pub mod pin; pub mod provision; - -#[cfg(feature = "hardware")] -pub mod detect; -#[cfg(feature = "hardware")] pub mod session; +pub mod transport; pub use error::RatkeyError; -pub use hardware::HardwareIdentity; +pub use hardware::{HardwareIdentity, IdentityBackend}; pub use hwid::HwidConfig; pub use mock::MockPivSession; pub use pin::PinCache; pub use provision::{ProvisionConfig, ProvisionResult}; +pub use session::{DeviceMeta, PivSession}; +pub use transport::PivTransport; + +#[cfg(feature = "hardware")] +pub use session::PcscPivSession; +#[cfg(feature = "hardware")] +pub use transport::PcscTransport; diff --git a/crates/rns-ratkey/src/mock.rs b/crates/rns-ratkey/src/mock.rs index 18740ac..25e0c5d 100644 --- a/crates/rns-ratkey/src/mock.rs +++ b/crates/rns-ratkey/src/mock.rs @@ -145,6 +145,12 @@ impl MockPivSession { self.pin_verified = false; } + /// Re-lock: clears PIN verification so the next op needs `verify_pin` again. + /// Mirrors `PivSession::lock` (which re-selects the applet on real hardware). + pub fn lock(&mut self) { + self.pin_verified = false; + } + pub fn simulate_touch(&mut self) { self.touch_required = false; } diff --git a/crates/rns-ratkey/src/provision.rs b/crates/rns-ratkey/src/provision.rs index ddd7861..1b60246 100644 --- a/crates/rns-ratkey/src/provision.rs +++ b/crates/rns-ratkey/src/provision.rs @@ -218,7 +218,7 @@ mod tests { let result = provision_mock(&mut session, &config).unwrap(); let path = result.hwid_path.as_ref().unwrap(); - let mut hw = crate::HardwareIdentity::from_file_mock(path, session).unwrap(); + let mut hw = crate::HardwareIdentity::from_file(path, Box::new(session)).unwrap(); let message = b"provisioned and loaded"; let sig = hw.sign(message).unwrap(); diff --git a/crates/rns-ratkey/src/session.rs b/crates/rns-ratkey/src/session.rs index e9f6d6e..b1c8aef 100644 --- a/crates/rns-ratkey/src/session.rs +++ b/crates/rns-ratkey/src/session.rs @@ -1,70 +1,43 @@ -//! Real PIV session over PC/SC (YubiKey 5, Nitrokey 3). -//! Requires `hardware` feature + PC/SC daemon (macOS CryptoTokenKit / Linux pcscd / Windows WinSCard). - -use pcsc::{Card, Context, Protocols, Scope, ShareMode}; -use tracing::{debug, warn}; -use zeroize::Zeroize; +//! Transport-agnostic PIV session. Every PIV operation is built on `apdu` plus a +//! `PivTransport`; the transport is the only platform-specific part (see `transport`). +//! `hardware` feature adds the PC/SC `connect()` entry points. use crate::apdu; use crate::detect::DeviceType; use crate::error::RatkeyError; use crate::pin::PinCache; +use crate::transport::PivTransport; -const MAX_RESPONSE: usize = 4096; +/// Device identity captured once at connect time; no per-operation cost. +pub struct DeviceMeta { + pub device_type: DeviceType, + pub serial: Option, + pub firmware: Option, +} -pub struct PivSession { - card: Card, +pub struct PivSession { + transport: T, device_type: DeviceType, - reader_name: String, serial: Option, firmware: Option, pin_cache: PinCache, } -impl PivSession { - pub fn connect() -> Result { - let devices = crate::detect::detect_devices()?; - let device = devices.first().ok_or(RatkeyError::NoDevice)?; - Self::connect_reader(&device.reader_name) - } - - pub fn connect_reader(reader_name: &str) -> Result { - let ctx = Context::establish(Scope::User)?; - let reader = std::ffi::CString::new(reader_name) - .map_err(|_| RatkeyError::UnsupportedDevice(reader_name.to_string()))?; - - let card = ctx.connect(&reader, ShareMode::Shared, Protocols::ANY)?; - - let resp = transmit(&card, &apdu::select_piv())?; - apdu::check_response(&resp)?; - - let device_type = crate::detect::detect_device_type(reader_name); - debug!( - "PIV session established with {} ({})", - reader_name, - device_type.as_str() - ); - - let (serial, firmware) = crate::detect::read_identity(&card, device_type); - - Ok(Self { - card, - device_type, - reader_name: reader_name.to_string(), - serial, - firmware, +impl PivSession { + pub fn new(transport: T, meta: DeviceMeta) -> Self { + Self { + transport, + device_type: meta.device_type, + serial: meta.serial, + firmware: meta.firmware, pin_cache: PinCache::default_timeout(), - }) + } } pub fn device_type(&self) -> DeviceType { self.device_type } - pub fn reader_name(&self) -> &str { - &self.reader_name - } - pub fn serial(&self) -> Option { self.serial } @@ -73,102 +46,122 @@ impl PivSession { self.firmware.as_deref() } - /// Probes the attestation slot (F9) — always present on provisioned tokens. pub fn is_connected(&self) -> bool { - let cmd = apdu::get_metadata(apdu::SLOT_ATTESTATION); - let mut buf = vec![0u8; 256]; - self.card.transmit(&cmd, &mut buf).is_ok() + self.transport.is_connected() + } + + /// Re-locks the card: re-selects the PIV applet (resetting the on-card PIN + /// verification) and clears the cached PIN, so the next private-key op needs + /// a fresh `verify_pin`. This is the mechanism behind the app-side session + /// timeout / lock-on-quit. + pub fn lock(&mut self) -> Result<(), RatkeyError> { + let resp = self.transport.transmit(&apdu::select_piv())?; + apdu::check_response(&resp)?; + self.pin_cache.clear(); + Ok(()) } pub fn verify_pin(&mut self, pin: &str) -> Result<(), RatkeyError> { - let cmd = apdu::verify_pin(pin); - let resp = transmit(&self.card, &cmd)?; + let resp = self.transport.transmit(&apdu::verify_pin(pin))?; apdu::check_response(&resp)?; self.pin_cache.cache(pin); - debug!("PIN verified"); Ok(()) } pub fn change_pin(&mut self, old_pin: &str, new_pin: &str) -> Result<(), RatkeyError> { - let cmd = apdu::change_pin(old_pin, new_pin); - let resp = transmit(&self.card, &cmd)?; + let resp = self.transport.transmit(&apdu::change_pin(old_pin, new_pin))?; apdu::check_response(&resp)?; self.pin_cache.cache(new_pin); - debug!("PIN changed"); Ok(()) } pub fn generate_ed25519( - &self, + &mut self, slot: u8, pin_policy: Option, touch_policy: Option, ) -> Result<[u8; 32], RatkeyError> { - let cmd = apdu::generate_key(slot, apdu::ALG_ED25519, pin_policy, touch_policy); - let resp = transmit(&self.card, &cmd)?; + let resp = self.transport.transmit(&apdu::generate_key( + slot, + apdu::ALG_ED25519, + pin_policy, + touch_policy, + ))?; let data = apdu::check_response(&resp)?; apdu::parse_generate_response(data) } pub fn generate_x25519( - &self, + &mut self, slot: u8, pin_policy: Option, touch_policy: Option, ) -> Result<[u8; 32], RatkeyError> { - let cmd = apdu::generate_key(slot, apdu::ALG_X25519, pin_policy, touch_policy); - let resp = transmit(&self.card, &cmd)?; + let resp = self.transport.transmit(&apdu::generate_key( + slot, + apdu::ALG_X25519, + pin_policy, + touch_policy, + ))?; let data = apdu::check_response(&resp)?; apdu::parse_generate_response(data) } - pub fn sign_ed25519(&self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> { - let cmd = apdu::sign_ed25519(slot, message); - let resp = transmit(&self.card, &cmd)?; + pub fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> { + let resp = self.transport.transmit(&apdu::sign_ed25519(slot, message))?; let data = apdu::check_response(&resp)?; apdu::parse_sign_response(data) } - pub fn ecdh_x25519(&self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> { - let cmd = apdu::ecdh_x25519(slot, peer_pub); - let resp = transmit(&self.card, &cmd)?; + pub fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> { + let resp = self.transport.transmit(&apdu::ecdh_x25519(slot, peer_pub))?; let data = apdu::check_response(&resp)?; - let mut secret = apdu::parse_ecdh_response(data)?; - // Wipes local stack copy only. Caller must zeroize the returned bytes. - let result = secret; - secret.zeroize(); - Ok(result) + apdu::parse_ecdh_response(data) } /// Returns DER-encoded X.509 attestation certificate. - pub fn attest_key(&self, slot: u8) -> Result, RatkeyError> { - let cmd = apdu::attest_key(slot); - let resp = transmit(&self.card, &cmd)?; - let data = apdu::check_response(&resp)?; - Ok(data.to_vec()) + pub fn attest_key(&mut self, slot: u8) -> Result, RatkeyError> { + let resp = self.transport.transmit(&apdu::attest_key(slot))?; + Ok(apdu::check_response(&resp)?.to_vec()) } - pub fn read_certificate(&self, slot: u8) -> Result, RatkeyError> { + pub fn read_certificate(&mut self, slot: u8) -> Result, RatkeyError> { let cmd = apdu::get_data(slot).ok_or(RatkeyError::EmptySlot { slot })?; - let resp = transmit(&self.card, &cmd)?; - let data = apdu::check_response(&resp)?; - Ok(data.to_vec()) + let resp = self.transport.transmit(&cmd)?; + Ok(apdu::check_response(&resp)?.to_vec()) } - /// Returns raw metadata TLV bytes. - pub fn read_metadata(&self, slot: u8) -> Result, RatkeyError> { - let cmd = apdu::get_metadata(slot); - let resp = transmit(&self.card, &cmd)?; - let data = apdu::check_response(&resp)?; - Ok(data.to_vec()) + /// Returns raw GET METADATA TLV bytes. + pub fn read_metadata(&mut self, slot: u8) -> Result, RatkeyError> { + let resp = self.transport.transmit(&apdu::get_metadata(slot))?; + Ok(apdu::check_response(&resp)?.to_vec()) + } + + /// Reads the slot's 32-byte public key from GET METADATA. The metadata byte + /// layout is pending confirmation against a real device — see + /// `apdu::parse_metadata_public_key`. Yubico 5.3+ only (Nitrokey 3 has no + /// GET METADATA). + pub fn read_public_key(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> { + let metadata = self.read_metadata(slot)?; + apdu::parse_metadata_public_key(&metadata) } } -fn transmit(card: &Card, command: &[u8]) -> Result, RatkeyError> { - let mut response_buf = vec![0u8; MAX_RESPONSE]; - let response = card.transmit(command, &mut response_buf).map_err(|e| { - warn!("PC/SC transmit failed: {}", e); - RatkeyError::Disconnected - })?; - Ok(response.to_vec()) +/// PC/SC convenience alias; `connect()` lives on this monomorphization. +#[cfg(feature = "hardware")] +pub type PcscPivSession = PivSession; + +#[cfg(feature = "hardware")] +impl PivSession { + /// Connect to the first detected token over PC/SC. + pub fn connect() -> Result { + let (transport, meta) = crate::transport::PcscTransport::connect()?; + Ok(Self::new(transport, meta)) + } + + /// Connect to a specific PC/SC reader by name. + pub fn connect_reader(reader_name: &str) -> Result { + let (transport, meta) = crate::transport::PcscTransport::connect_reader(reader_name)?; + Ok(Self::new(transport, meta)) + } } diff --git a/crates/rns-ratkey/src/transport.rs b/crates/rns-ratkey/src/transport.rs new file mode 100644 index 0000000..dcbc05c --- /dev/null +++ b/crates/rns-ratkey/src/transport.rs @@ -0,0 +1,97 @@ +//! Transport seam for PIV. The PIV protocol logic lives in `PivSession`; this +//! trait is the only platform-specific part: APDU bytes in, response bytes out. +//! Desktop PC/SC ships here behind the `hardware` feature. Mobile NFC/USB +//! transports live in the application layer and implement the same trait. + +use crate::error::RatkeyError; + +pub trait PivTransport { + /// Send one ISO 7816-4 APDU; return the full response including SW1/SW2. + fn transmit(&mut self, apdu: &[u8]) -> Result, RatkeyError>; + + /// Cheap liveness probe — token still present and responding. + fn is_connected(&self) -> bool; +} + +#[cfg(feature = "hardware")] +pub use pcsc_transport::PcscTransport; + +#[cfg(feature = "hardware")] +mod pcsc_transport { + use pcsc::{Context, Protocols, Scope, ShareMode}; + use tracing::{debug, warn}; + + use super::PivTransport; + use crate::apdu; + use crate::detect::{self, detect_device_type}; + use crate::error::RatkeyError; + use crate::session::DeviceMeta; + + const MAX_RESPONSE: usize = 4096; + + /// Real PIV transport over PC/SC (YubiKey 5, Nitrokey 3). Requires a PC/SC + /// daemon: macOS CryptoTokenKit / Linux pcscd / Windows WinSCard. + pub struct PcscTransport { + card: pcsc::Card, + } + + impl PcscTransport { + /// Connect to the first detected RATKEY token. + pub fn connect() -> Result<(Self, DeviceMeta), RatkeyError> { + let devices = detect::detect_devices()?; + let device = devices.first().ok_or(RatkeyError::NoDevice)?; + Self::connect_reader(&device.reader_name) + } + + /// Connect to a specific PC/SC reader by name. + pub fn connect_reader(reader_name: &str) -> Result<(Self, DeviceMeta), RatkeyError> { + let ctx = Context::establish(Scope::User)?; + let reader = std::ffi::CString::new(reader_name) + .map_err(|_| RatkeyError::UnsupportedDevice(reader_name.to_string()))?; + let card = ctx.connect(&reader, ShareMode::Shared, Protocols::ANY)?; + + let resp = transmit_card(&card, &apdu::select_piv())?; + apdu::check_response(&resp)?; + + let device_type = detect_device_type(reader_name); + debug!( + "PIV session established with {} ({})", + reader_name, + device_type.as_str() + ); + + let (serial, firmware) = detect::read_identity(&card, device_type); + + Ok(( + Self { card }, + DeviceMeta { + device_type, + serial, + firmware, + }, + )) + } + } + + impl PivTransport for PcscTransport { + fn transmit(&mut self, apdu: &[u8]) -> Result, RatkeyError> { + transmit_card(&self.card, apdu) + } + + fn is_connected(&self) -> bool { + // Attestation slot (F9) is present on any provisioned token. + let cmd = apdu::get_metadata(apdu::SLOT_ATTESTATION); + let mut buf = vec![0u8; 256]; + self.card.transmit(&cmd, &mut buf).is_ok() + } + } + + fn transmit_card(card: &pcsc::Card, command: &[u8]) -> Result, RatkeyError> { + let mut response_buf = vec![0u8; MAX_RESPONSE]; + let response = card.transmit(command, &mut response_buf).map_err(|e| { + warn!("PC/SC transmit failed: {}", e); + RatkeyError::Disconnected + })?; + Ok(response.to_vec()) + } +} diff --git a/crates/rns-tools/src/commands/rnid/hw_commands.rs b/crates/rns-tools/src/commands/rnid/hw_commands.rs index 2f8e50e..976938a 100644 --- a/crates/rns-tools/src/commands/rnid/hw_commands.rs +++ b/crates/rns-tools/src/commands/rnid/hw_commands.rs @@ -14,7 +14,7 @@ pub fn run(cmd: HwCommands) { HwCommands::List { dir } => cmd_list(dir), HwCommands::Info { hwid } => cmd_info(hwid), HwCommands::Verify { hwid } => cmd_verify(hwid), - HwCommands::Test { hwid } => cmd_test(hwid), + HwCommands::Test { hwid, pin } => cmd_test(hwid, pin), } } @@ -81,7 +81,7 @@ fn cmd_provision(pin: Option, nickname: Option, output: Option

s, Err(e) => { eprintln!("Error connecting to hardware token: {e}"); @@ -95,12 +95,14 @@ fn cmd_provision(pin: Option, nickname: Option, output: Option

pub_key, Err(e) => { @@ -109,12 +111,13 @@ fn cmd_provision(pin: Option, nickname: Option, output: Option

pub_key, Err(e) => { @@ -164,8 +167,8 @@ fn cmd_provision(pin: Option, nickname: Option, output: Option

k, + Err(e) => { + eprintln!("Error: .hwid has invalid Ed25519 key: {e}"); + std::process::exit(1); + } + }; + let expected_x = match config.x25519_pub_bytes() { + Ok(k) => k, + Err(e) => { + eprintln!("Error: .hwid has invalid X25519 key: {e}"); + std::process::exit(1); + } + }; + + let mut session = match rns_ratkey::PcscPivSession::connect() { Ok(s) => s, Err(e) => { eprintln!("Error: cannot connect to hardware token: {e}"); @@ -300,20 +318,42 @@ fn cmd_verify(hwid_path: PathBuf) { } }; - let metadata = match session.read_metadata(rns_ratkey::apdu::SLOT_AUTHENTICATION) { - Ok(m) => m, - Err(e) => { - eprintln!("Error reading slot 9A: {e}"); - std::process::exit(1); + // Reads the slot public keys from GET METADATA and compares against the .hwid. + // This is the on-device confirmation of the metadata parser before it gates + // HardwareIdentity construction. + let mut ok = true; + match session.read_public_key(rns_ratkey::apdu::SLOT_AUTHENTICATION) { + Ok(dev_ed) if dev_ed == expected_ed => println!(" Slot 9A (Ed25519): MATCH"), + Ok(_) => { + println!(" Slot 9A (Ed25519): MISMATCH"); + ok = false; } - }; + Err(e) => { + println!(" Slot 9A (Ed25519): error reading key: {e}"); + ok = false; + } + } + match session.read_public_key(rns_ratkey::apdu::SLOT_KEY_MANAGEMENT) { + Ok(dev_x) if dev_x == expected_x => println!(" Slot 9D (X25519): MATCH"), + Ok(_) => { + println!(" Slot 9D (X25519): MISMATCH"); + ok = false; + } + Err(e) => { + println!(" Slot 9D (X25519): error reading key: {e}"); + ok = false; + } + } - println!(" Slot 9A metadata: {} bytes", metadata.len()); - println!(" Verification requires comparing public keys from device with .hwid file."); - println!(" (Full verification implemented when hardware is available for testing)"); + if ok { + println!("\nVerified: connected token matches this .hwid."); + } else { + println!("\nVerification FAILED: token does not match this .hwid."); + std::process::exit(1); + } } -fn cmd_test(hwid_path: PathBuf) { +fn cmd_test(hwid_path: PathBuf, pin: Option) { let config = match rns_ratkey::hwid::HwidConfig::from_file(&hwid_path) { Ok(c) => c, Err(e) => { @@ -322,9 +362,18 @@ fn cmd_test(hwid_path: PathBuf) { } }; + let pin = match pin { + Some(p) => p, + None => { + eprintln!("Error: --pin is required (PIN-once keys need one verification per session)"); + eprintln!("Usage: rnid-rs hw test --pin "); + std::process::exit(1); + } + }; + println!("Testing hardware identity {}...\n", config.identity.hash); - let session = match rns_ratkey::session::PivSession::connect() { + let mut session = match rns_ratkey::PcscPivSession::connect() { Ok(s) => s, Err(e) => { eprintln!("Error: cannot connect to hardware token: {e}"); @@ -332,6 +381,12 @@ fn cmd_test(hwid_path: PathBuf) { } }; + // PIN_POLICY_ONCE: a fresh session must verify the PIN before any private-key op. + if let Err(e) = session.verify_pin(&pin) { + eprintln!("PIN verification failed: {e}"); + std::process::exit(1); + } + println!("1. Testing Ed25519 signing in slot 9A..."); let test_msg = b"RATKEY hardware identity test message"; match session.sign_ed25519(rns_ratkey::apdu::SLOT_AUTHENTICATION, test_msg) { @@ -373,5 +428,33 @@ fn cmd_test(hwid_path: PathBuf) { } } + println!("3. Testing HardwareIdentity decrypt (on-device ECDH + HKDF + AES) end-to-end..."); + let mut hw = match rns_ratkey::HardwareIdentity::from_hwid(config.clone(), Box::new(session)) { + Ok(h) => h, + Err(e) => { + println!(" FAIL: cannot build HardwareIdentity: {e}"); + std::process::exit(1); + } + }; + let plaintext = b"RATKEY end-to-end decrypt test"; + let ciphertext = match hw.as_identity().encrypt(plaintext, None) { + Ok(c) => c, + Err(e) => { + println!(" FAIL: encrypt to hardware identity failed: {e}"); + std::process::exit(1); + } + }; + match hw.decrypt(&ciphertext, None, false) { + Ok(pt) if pt == plaintext => println!(" PASS: round-trip decrypt via on-device ECDH"), + Ok(_) => { + println!(" FAIL: decrypted plaintext mismatch"); + std::process::exit(1); + } + Err(e) => { + println!(" FAIL: {e}"); + std::process::exit(1); + } + } + println!("\nAll tests passed."); } diff --git a/crates/rns-tools/src/commands/rnid/main.rs b/crates/rns-tools/src/commands/rnid/main.rs index bbf9381..7c705f5 100644 --- a/crates/rns-tools/src/commands/rnid/main.rs +++ b/crates/rns-tools/src/commands/rnid/main.rs @@ -200,6 +200,8 @@ enum HwCommands { }, Test { hwid: PathBuf, + #[arg(long)] + pin: Option, }, }