From a4083bd4fef1fa31fca0eaf907e8a937fba04a1c Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Fri, 29 May 2026 00:07:25 -0600 Subject: [PATCH] ratkey: PIV key import + recoverable provisioning/restore IMPORT ASYMMETRIC KEY APDU (Ed25519 tag 0x07 / X25519 0x08) + PivSession import methods (mgmt-key gated). provision_recoverable derives from a fresh 24-word phrase and imports both keys; restore does the same from an existing phrase. Mirrors ratkey-py's import path. --- crates/rns-ratkey/src/apdu.rs | 74 +++++++++++++++++ crates/rns-ratkey/src/provision.rs | 122 +++++++++++++++++++++++++++++ crates/rns-ratkey/src/session.rs | 37 +++++++++ 3 files changed, 233 insertions(+) diff --git a/crates/rns-ratkey/src/apdu.rs b/crates/rns-ratkey/src/apdu.rs index 5c25f7d..8a99070 100644 --- a/crates/rns-ratkey/src/apdu.rs +++ b/crates/rns-ratkey/src/apdu.rs @@ -158,6 +158,49 @@ pub fn generate_key( build_apdu(INS_GENERATE_ASYMMETRIC, 0x00, slot, &data) } +// Yubico private-key import elements: Ed25519 = 0x07, X25519 = 0x08. +const TAG_IMPORT_ED25519: u8 = 0x07; +const TAG_IMPORT_X25519: u8 = 0x08; + +/// IMPORT ASYMMETRIC KEY (Ed25519, slot). Requires management-key auth. For +/// recoverable provisioning — the key was derived off-device from a seed phrase. +pub fn import_ed25519( + slot: u8, + private_key: &[u8; 32], + pin_policy: Option, + touch_policy: Option, +) -> Vec { + import_key(slot, ALG_ED25519, TAG_IMPORT_ED25519, private_key, pin_policy, touch_policy) +} + +/// IMPORT ASYMMETRIC KEY (X25519, slot). Requires management-key auth. +pub fn import_x25519( + slot: u8, + private_key: &[u8; 32], + pin_policy: Option, + touch_policy: Option, +) -> Vec { + import_key(slot, ALG_X25519, TAG_IMPORT_X25519, private_key, pin_policy, touch_policy) +} + +fn import_key( + slot: u8, + alg: u8, + key_tag: u8, + private_key: &[u8; 32], + pin_policy: Option, + touch_policy: Option, +) -> Vec { + let mut data = tlv(key_tag, private_key); + if let Some(pp) = pin_policy { + data.extend_from_slice(&tlv(TAG_PIN_POLICY, &[pp])); + } + if let Some(tp) = touch_policy { + data.extend_from_slice(&tlv(TAG_TOUCH_POLICY, &[tp])); + } + build_apdu(INS_IMPORT_KEY, alg, slot, &data) +} + /// GENERAL AUTHENTICATE Ed25519 sign. Send raw message — device does SHA-512 internally; no pre-hash. pub fn sign_ed25519(slot: u8, message: &[u8]) -> Vec { let challenge = tlv(TAG_AUTH_CHALLENGE, message); @@ -748,6 +791,37 @@ mod tests { assert_eq!(parse_metadata_algorithm(&meta).unwrap(), MGMT_ALG_AES192); } + #[test] + fn test_import_ed25519() { + let key = [0x11; 32]; + let apdu = import_ed25519( + SLOT_AUTHENTICATION, + &key, + Some(PIN_POLICY_ONCE), + Some(TOUCH_POLICY_NEVER), + ); + assert_eq!(apdu[1], 0xFE); // INS IMPORT KEY + assert_eq!(apdu[2], 0xE0); // P1 = Ed25519 + assert_eq!(apdu[3], 0x9A); // P2 = slot + assert_eq!(apdu[5], 0x07); // Ed25519 private-key element tag + assert_eq!(apdu[6], 0x20); // 32-byte length + assert_eq!(&apdu[7..39], &key); + assert_eq!( + &apdu[39..45], + &[0xAA, 0x01, PIN_POLICY_ONCE, 0xAB, 0x01, TOUCH_POLICY_NEVER] + ); + } + + #[test] + fn test_import_x25519_tag() { + let apdu = import_x25519(SLOT_KEY_MANAGEMENT, &[0x22; 32], None, None); + assert_eq!(apdu[1], 0xFE); + assert_eq!(apdu[2], 0xE1); // X25519 + assert_eq!(apdu[3], 0x9D); + assert_eq!(apdu[5], 0x08); // X25519 private-key element tag + assert_eq!(apdu[6], 0x20); + } + #[test] fn test_parse_metadata_public_key_bare() { // Slot metadata: 01(algo) 02(policy) 03(origin) 04(pubkey = 86 20 <32>). diff --git a/crates/rns-ratkey/src/provision.rs b/crates/rns-ratkey/src/provision.rs index 1b60246..23ddcb0 100644 --- a/crates/rns-ratkey/src/provision.rs +++ b/crates/rns-ratkey/src/provision.rs @@ -5,9 +5,13 @@ use std::time::{SystemTime, UNIX_EPOCH}; use rns_crypto::sha::truncated_hash; +use crate::apdu; use crate::error::RatkeyError; use crate::hwid::*; use crate::mock::{MockPivSession, SLOT_9A, SLOT_9D, TouchPolicy}; +use crate::seed; +use crate::session::PivSession; +use crate::transport::PivTransport; #[derive(Debug, Clone)] pub struct ProvisionResult { @@ -132,6 +136,124 @@ pub fn compute_identity_hash(ed25519_pub: &[u8; 32], x25519_pub: &[u8; 32]) -> [ truncated_hash(&pub_key_bytes) } +fn touch_byte(tp: TouchPolicy) -> u8 { + match tp { + TouchPolicy::Never => apdu::TOUCH_POLICY_NEVER, + TouchPolicy::Always => apdu::TOUCH_POLICY_ALWAYS, + TouchPolicy::Cached => apdu::TOUCH_POLICY_CACHED, + } +} + +fn touch_str(tp: TouchPolicy) -> &'static str { + match tp { + TouchPolicy::Never => "never", + TouchPolicy::Always => "always", + TouchPolicy::Cached => "cached", + } +} + +/// Recoverable provision / restore: derive the identity from `mnemonic`, import +/// both keys into the token (PIN-once + configured touch policy), and write the +/// `.hwid`. Requires the management key. The session must already be connected. +pub fn import_recoverable_identity( + session: &mut PivSession, + mgmt_key: &[u8], + config: &ProvisionConfig, + mnemonic: &str, +) -> Result { + let derived = seed::derive_identity(mnemonic)?; + session.authenticate_management_key(mgmt_key)?; + session.import_ed25519( + SLOT_9A, + &derived.ed25519_seed, + Some(apdu::PIN_POLICY_ONCE), + Some(touch_byte(config.touch_signing)), + )?; + session.import_x25519( + SLOT_9D, + &derived.x25519_secret, + Some(apdu::PIN_POLICY_ONCE), + Some(touch_byte(config.touch_encryption)), + )?; + + let identity_hash = compute_identity_hash(&derived.ed25519_pub, &derived.x25519_pub); + let identity_hash_hex = hex::encode(identity_hash); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + + let hwid = HwidConfig { + identity: HwidIdentity { + hash: identity_hash_hex.clone(), + nickname: config.nickname.clone(), + created_at: now, + }, + device: HwidDevice { + device_type: session.device_type().as_str().to_string(), + serial: session.serial().unwrap_or(0), + firmware: session.firmware().unwrap_or("unknown").to_string(), + }, + keys: HwidKeys { + ed25519_pub: hex::encode(derived.ed25519_pub), + x25519_pub: hex::encode(derived.x25519_pub), + }, + slots: HwidSlots { + signing: "9A".to_string(), + encryption: "9D".to_string(), + }, + policy: HwidPolicy { + pin_cache_timeout: 300, + touch_signing: touch_str(config.touch_signing).to_string(), + touch_encryption: touch_str(config.touch_encryption).to_string(), + }, + attestation: HwidAttestation::default(), + app: HwidApp::default(), + backup: HwidBackup::default(), + }; + + let hwid_path = if let Some(ref dir) = config.identities_dir { + let identity_dir = dir.join(&identity_hash_hex); + std::fs::create_dir_all(&identity_dir)?; + let path = identity_dir.join("identity.hwid"); + hwid.to_file(&path)?; + Some(path) + } else { + None + }; + + Ok(ProvisionResult { + config: hwid, + ed25519_pub: derived.ed25519_pub, + x25519_pub: derived.x25519_pub, + identity_hash, + identity_hash_hex, + hwid_path, + }) +} + +/// Recoverable provisioning: generate a fresh 24-word mnemonic, import the +/// derived identity, and return both the result and the mnemonic to show once. +pub fn provision_recoverable( + session: &mut PivSession, + mgmt_key: &[u8], + config: &ProvisionConfig, +) -> Result<(ProvisionResult, String), RatkeyError> { + let mnemonic = seed::generate_mnemonic()?; + let result = import_recoverable_identity(session, mgmt_key, config, &mnemonic)?; + Ok((result, mnemonic)) +} + +/// Restore a recoverable identity from an existing 24-word mnemonic onto a token. +pub fn restore( + session: &mut PivSession, + mgmt_key: &[u8], + config: &ProvisionConfig, + mnemonic: &str, +) -> Result { + import_recoverable_identity(session, mgmt_key, config, mnemonic) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/rns-ratkey/src/session.rs b/crates/rns-ratkey/src/session.rs index 1c9921b..03ac5ef 100644 --- a/crates/rns-ratkey/src/session.rs +++ b/crates/rns-ratkey/src/session.rs @@ -107,6 +107,43 @@ impl PivSession { apdu::parse_generate_response(data) } + /// Import an off-device Ed25519 key (recoverable provisioning / restore). + /// Requires prior `authenticate_management_key`. + pub fn import_ed25519( + &mut self, + slot: u8, + private_key: &[u8; 32], + pin_policy: Option, + touch_policy: Option, + ) -> Result<(), RatkeyError> { + let resp = self.transport.transmit(&apdu::import_ed25519( + slot, + private_key, + pin_policy, + touch_policy, + ))?; + apdu::check_response(&resp)?; + Ok(()) + } + + /// Import an off-device X25519 key. Requires prior `authenticate_management_key`. + pub fn import_x25519( + &mut self, + slot: u8, + private_key: &[u8; 32], + pin_policy: Option, + touch_policy: Option, + ) -> Result<(), RatkeyError> { + let resp = self.transport.transmit(&apdu::import_x25519( + slot, + private_key, + pin_policy, + touch_policy, + ))?; + apdu::check_response(&resp)?; + Ok(()) + } + 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)?;