From a475caf4075989b85f599f7c5cf1997da786dc27 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Thu, 28 May 2026 23:10:52 -0600 Subject: [PATCH] ratkey: Identity LocalKeyBackend seam + hardware-backed identity Identity gains an optional LocalKeyBackend (Ed25519 sign + X25519 ECDH delegation, used only when the in-memory key is absent; None for software identities, so wire output is unchanged). rns-ratkey HardwareBackend runs the PIV session on a card-service thread (Send+Sync) and load_hardware_identity builds an Identity::from_backend. Backend-aware Identity::clone keeps both clone_identity sites working for hardware (Arc-shared) without extracting a private key. --- crates/rns-identity/src/identity.rs | 126 +++++++++++++++++++++++- crates/rns-ratkey/src/backend.rs | 128 +++++++++++++++++++++++++ crates/rns-ratkey/src/lib.rs | 4 + crates/rns-runtime/src/link_manager.rs | 9 +- crates/rns-runtime/src/reticulum.rs | 8 +- 5 files changed, 267 insertions(+), 8 deletions(-) create mode 100644 crates/rns-ratkey/src/backend.rs diff --git a/crates/rns-identity/src/identity.rs b/crates/rns-identity/src/identity.rs index d187929..8a778e5 100644 --- a/crates/rns-identity/src/identity.rs +++ b/crates/rns-identity/src/identity.rs @@ -9,6 +9,7 @@ use zeroize::{Zeroize, Zeroizing}; use crate::persistence; use std::path::Path; +use std::sync::Arc; /// HKDF-derived key length: 32 bytes AES key || 32 bytes HMAC key. pub const DERIVED_KEY_LENGTH: usize = 64; @@ -33,6 +34,17 @@ pub enum IdentityError { Io(#[from] std::io::Error), } +/// Delegate for an `Identity` whose private key is not in memory (e.g. a PIV +/// hardware token). Implemented outside this crate (see `rns-ratkey`). Both +/// operations must produce standard output — RFC 8032 Ed25519 / RFC 7748 X25519 +/// — so the resulting identity is wire-identical to a software one. +pub trait LocalKeyBackend: Send + Sync { + /// Ed25519 signature over `message`, or `None` if currently unavailable. + fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]>; + /// X25519 ECDH shared secret with `peer_pub`, or `None` if unavailable. + fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]>; +} + /// A Reticulum identity: X25519 keypair for encryption + Ed25519 keypair for signing. /// /// Wire representation: @@ -45,6 +57,29 @@ pub struct Identity { pub_key: X25519PublicKey, sig_pub: Ed25519PublicKey, pub hash: [u8; 16], + /// Set only for hardware-backed identities; `None` for all software ones. + backend: Option>, +} + +impl Clone for Identity { + /// Software identities clone their key material; hardware-backed identities + /// share the same `LocalKeyBackend` (Arc) — there is no extractable key to copy. + fn clone(&self) -> Self { + Self { + prv: self + .prv + .as_ref() + .map(|k| X25519PrivateKey::from_bytes(&k.to_bytes())), + sig_prv: self + .sig_prv + .as_ref() + .map(|k| Ed25519PrivateKey::from_bytes(&k.to_bytes())), + pub_key: self.pub_key.clone(), + sig_pub: self.sig_pub.clone(), + hash: self.hash, + backend: self.backend.clone(), + } + } } impl Default for Identity { @@ -67,6 +102,7 @@ impl Identity { pub_key, sig_pub, hash, + backend: None, } } @@ -91,6 +127,7 @@ impl Identity { pub_key, sig_pub, hash, + backend: None, }) } @@ -114,9 +151,22 @@ impl Identity { pub_key, sig_pub, hash, + backend: None, }) } + /// Construct an identity whose private operations are served by `backend` + /// (e.g. a hardware token). Public-key-only in memory; `sign` and `decrypt` + /// delegate to the backend. Wire-identical to a software identity. + pub fn from_backend( + public_key: &[u8], + backend: Arc, + ) -> Result { + let mut id = Self::from_public_key(public_key)?; + id.backend = Some(backend); + Ok(id) + } + /// Load an identity from file, accepting either the current msgpack envelope /// or a legacy raw 64-byte private key. pub fn from_file(path: &Path) -> Result { @@ -167,15 +217,24 @@ impl Identity { self.prv.is_some() && self.sig_prv.is_some() } + /// True if private operations are served by a hardware backend. + pub fn has_backend(&self) -> bool { + self.backend.is_some() + } + pub fn get_signing_key(&self) -> Option { self.sig_prv .as_ref() .map(|k| Ed25519PrivateKey::from_bytes(&k.to_bytes())) } - /// Sign `message` with the Ed25519 key; `None` if this is a public-only identity. + /// Sign `message` with the Ed25519 key, delegating to the hardware backend + /// when the in-memory key is absent; `None` if neither is available. pub fn sign(&self, message: &[u8]) -> Option<[u8; 64]> { - self.sig_prv.as_ref().map(|key| key.sign(message)) + match self.sig_prv.as_ref() { + Some(key) => Some(key.sign(message)), + None => self.backend.as_ref().and_then(|b| b.sign_ed25519(message)), + } } pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool { @@ -251,8 +310,16 @@ impl Identity { return Err(IdentityError::DecryptionFailed); } - let prv = self.prv.as_ref().ok_or(IdentityError::DecryptionFailed)?; - let mut shared = prv.exchange(&peer_pub); + // Identity-key ECDH: in-memory key if present, else the hardware backend. + let mut shared: [u8; 32] = if let Some(prv) = self.prv.as_ref() { + prv.exchange(&peer_pub) + } else if let Some(backend) = self.backend.as_ref() { + backend + .ecdh(&peer_pub_bytes) + .ok_or(IdentityError::DecryptionFailed)? + } else { + return Err(IdentityError::DecryptionFailed); + }; let derived_result = derive_key_64(&shared, &self.hash).map_err(|_| IdentityError::DecryptionFailed); shared.zeroize(); @@ -483,4 +550,55 @@ mod tests { let pub_id = Identity::from_public_key(&id.get_public_key()).unwrap(); assert!(pub_id.prove(b"test", true).is_err()); } + + // A software-keyed backend, standing in for a hardware token in tests. + struct SoftwareBackend { + sig: rns_crypto::ed25519::Ed25519PrivateKey, + x: rns_crypto::x25519::X25519PrivateKey, + } + impl LocalKeyBackend for SoftwareBackend { + fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]> { + Some(self.sig.sign(message)) + } + fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]> { + let peer = rns_crypto::x25519::X25519PublicKey::from_bytes(peer_pub); + Some(self.x.exchange(&peer)) + } + } + + #[test] + fn test_backend_identity_is_wire_identical() { + use std::sync::Arc; + + // Build a backend from a software identity's keys, then a separate + // backend-driven identity over the same public key. + let sw = Identity::new(); + let prv = sw.get_private_key().unwrap(); + let mut x_bytes = [0u8; 32]; + x_bytes.copy_from_slice(&prv[..32]); + let mut ed_bytes = [0u8; 32]; + ed_bytes.copy_from_slice(&prv[32..]); + let backend = Arc::new(SoftwareBackend { + sig: rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&ed_bytes), + x: rns_crypto::x25519::X25519PrivateKey::from_bytes(&x_bytes), + }); + + let hw = Identity::from_backend(&sw.get_public_key(), backend).unwrap(); + + // Same identity, but no extractable in-memory key. + assert_eq!(hw.hash, sw.hash); + assert!(!hw.has_private_key()); + assert!(hw.get_private_key().is_none()); + + // sign() delegates and is byte-identical (Ed25519 is deterministic). + let msg = b"hardware parity"; + assert_eq!(hw.sign(msg), sw.sign(msg)); + assert!(hw.verify(msg, &hw.sign(msg).unwrap())); + + // decrypt() delegates the ECDH to the backend; round-trips, and the + // software identity decrypts the same ciphertext (identical key material). + let ct = hw.encrypt(b"secret payload", None).unwrap(); + assert_eq!(hw.decrypt(&ct, None, false).unwrap(), b"secret payload"); + assert_eq!(sw.decrypt(&ct, None, false).unwrap(), b"secret payload"); + } } diff --git a/crates/rns-ratkey/src/backend.rs b/crates/rns-ratkey/src/backend.rs new file mode 100644 index 0000000..44ced82 --- /dev/null +++ b/crates/rns-ratkey/src/backend.rs @@ -0,0 +1,128 @@ +//! Bridges a PIV token to an `rns_identity::Identity` via the `LocalKeyBackend` +//! seam. The PIV session runs on a dedicated thread — pcsc handles want serial +//! APDU access and are not `Sync` — so the backend handle holds only channel +//! senders and is therefore `Send + Sync`, usable directly from the async runtime. + +use std::sync::mpsc::{self, Sender}; +use std::sync::{Arc, Mutex}; +use std::thread; + +use rns_identity::identity::{Identity, LocalKeyBackend}; + +use crate::apdu::{SLOT_AUTHENTICATION, SLOT_KEY_MANAGEMENT}; +use crate::error::RatkeyError; +use crate::hwid::HwidConfig; +use crate::session::PivSession; +use crate::transport::PcscTransport; + +enum Cmd { + Sign { + message: Vec, + reply: Sender>, + }, + Ecdh { + peer_pub: [u8; 32], + reply: Sender>, + }, +} + +/// `LocalKeyBackend` over a PIV token. Each call round-trips a request to the +/// card-service thread and blocks for the device's reply (PIV ops are ~10-50ms). +pub struct HardwareBackend { + cmd_tx: Mutex>, +} + +impl LocalKeyBackend for HardwareBackend { + fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]> { + let (reply, rx) = mpsc::channel(); + self.cmd_tx + .lock() + .ok()? + .send(Cmd::Sign { + message: message.to_vec(), + reply, + }) + .ok()?; + rx.recv().ok().flatten() + } + + fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]> { + let (reply, rx) = mpsc::channel(); + self.cmd_tx + .lock() + .ok()? + .send(Cmd::Ecdh { + peer_pub: *peer_pub, + reply, + }) + .ok()?; + rx.recv().ok().flatten() + } +} + +/// Connect to the token described by `hwid`, verify the on-device keys match it +/// (fail-closed), unlock with `pin`, and return an `Identity` whose private +/// operations run on the device. The PIV session lives on a worker thread that +/// exits when the returned identity (and its backend) is dropped. +pub fn load_hardware_identity(hwid: &HwidConfig, pin: &str) -> Result { + let ed_pub = hwid.ed25519_pub_bytes()?; + let x_pub = hwid.x25519_pub_bytes()?; + let pin = pin.to_string(); + + let (cmd_tx, cmd_rx) = mpsc::channel::(); + let (ready_tx, ready_rx) = mpsc::channel::>(); + + thread::Builder::new() + .name("ratkey-piv".to_string()) + .spawn(move || { + let mut session = match PivSession::::connect() { + Ok(s) => s, + Err(e) => { + let _ = ready_tx.send(Err(e)); + return; + } + }; + // Fail closed: the device's slot keys must match the .hwid. + match ( + session.read_public_key(SLOT_AUTHENTICATION), + session.read_public_key(SLOT_KEY_MANAGEMENT), + ) { + (Ok(de), Ok(dx)) if de == ed_pub && dx == x_pub => {} + (Ok(_), Ok(_)) => { + let _ = ready_tx.send(Err(RatkeyError::KeyMismatch)); + return; + } + (Err(e), _) | (_, Err(e)) => { + let _ = ready_tx.send(Err(e)); + return; + } + } + if let Err(e) = session.verify_pin(&pin) { + let _ = ready_tx.send(Err(e)); + return; + } + let _ = ready_tx.send(Ok(())); + + // Serve sign/ECDH until the backend is dropped (sender closed). + while let Ok(cmd) = cmd_rx.recv() { + match cmd { + Cmd::Sign { message, reply } => { + let _ = reply.send(session.sign_ed25519(SLOT_AUTHENTICATION, &message).ok()); + } + Cmd::Ecdh { peer_pub, reply } => { + let _ = reply.send(session.ecdh_x25519(SLOT_KEY_MANAGEMENT, &peer_pub).ok()); + } + } + } + }) + .map_err(|e| RatkeyError::Io(std::io::Error::other(e.to_string())))?; + + // Wait for the worker to connect, match, and unlock before handing back. + ready_rx.recv().map_err(|_| RatkeyError::NoDevice)??; + + let mut pub64 = [0u8; 64]; + pub64[..32].copy_from_slice(&x_pub); + pub64[32..].copy_from_slice(&ed_pub); + Identity::from_backend(&pub64, Arc::new(HardwareBackend { cmd_tx: Mutex::new(cmd_tx) })) + .map_err(|e| RatkeyError::InvalidHwid(format!("cannot build identity: {e}"))) +} diff --git a/crates/rns-ratkey/src/lib.rs b/crates/rns-ratkey/src/lib.rs index fbe19d2..1809a16 100644 --- a/crates/rns-ratkey/src/lib.rs +++ b/crates/rns-ratkey/src/lib.rs @@ -9,6 +9,8 @@ pub mod apdu; pub mod attestation; +#[cfg(feature = "hardware")] +pub mod backend; pub mod detect; pub mod error; pub mod hardware; @@ -29,6 +31,8 @@ pub use provision::{ProvisionConfig, ProvisionResult}; pub use session::{DeviceMeta, PivSession}; pub use transport::PivTransport; +#[cfg(feature = "hardware")] +pub use backend::{HardwareBackend, load_hardware_identity}; #[cfg(feature = "hardware")] pub use session::PcscPivSession; #[cfg(feature = "hardware")] diff --git a/crates/rns-runtime/src/link_manager.rs b/crates/rns-runtime/src/link_manager.rs index a264afc..4685297 100644 --- a/crates/rns-runtime/src/link_manager.rs +++ b/crates/rns-runtime/src/link_manager.rs @@ -2537,8 +2537,13 @@ impl LinkManager { } fn clone_identity(identity: &Identity) -> Option { - let private_key = identity.get_private_key()?; - Identity::from_private_key(&*private_key).ok() + // Clone preserves a hardware backend (shared Arc) — there is no extractable + // private key to copy; software identities clone their key material. + if identity.has_private_key() || identity.has_backend() { + Some(identity.clone()) + } else { + None + } } fn unix_now() -> f64 { diff --git a/crates/rns-runtime/src/reticulum.rs b/crates/rns-runtime/src/reticulum.rs index ffbf040..90ed19b 100644 --- a/crates/rns-runtime/src/reticulum.rs +++ b/crates/rns-runtime/src/reticulum.rs @@ -2553,8 +2553,12 @@ async fn start_blackhole_subscriber(handle: ReticulumHandle) { } fn clone_identity(identity: &Identity) -> Option { - let private_key = identity.get_private_key()?; - Identity::from_private_key(&*private_key).ok() + // Preserve a hardware backend (shared Arc); software identities copy key material. + if identity.has_private_key() || identity.has_backend() { + Some(identity.clone()) + } else { + None + } } fn send_announce_try(