From 71b0bca0c4ef0d629d8cb68432eea04e4c177011 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Mon, 9 Nov 2026 17:18:37 +0100 Subject: [PATCH] Fix memory leak in import key This PR also makes deselect clear the admin state --- Cargo.toml | 3 ++ Makefile | 1 + dev-vpicc/Cargo.toml | 4 +- dev-vpicc/src/virt.rs | 78 +++++++++++++++++++++++++++++++-------- src/lib.rs | 19 ++++++++-- src/state.rs | 36 +++++++++++++++--- tests/card/mod.rs | 4 +- tests/command_response.rs | 2 + tests/setup/mod.rs | 2 +- 9 files changed, 122 insertions(+), 27 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8ad1af7b..b9522276 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -79,3 +79,6 @@ opt-level = 2 [profile.dev.package.num-bigint-dig] opt-level = 2 + +[patch.crates-io] +trussed = { git = "https://github.com/sosthene-nitrokey/trussed.git", rev = "5a41ab2b4709350df9a2f7fbf385535baf37cb8f" } diff --git a/Makefile b/Makefile index 1c336065..b31e85a4 100644 --- a/Makefile +++ b/Makefile @@ -3,6 +3,7 @@ -include variables.mk export RUST_LOG ?= info,cargo_tarpaulin=off +# export RUST_BACKTRACE ?= 1 TEST_FEATURES ?= rsa export PIV_DANGEROUS_TEST_CARD_READER ?= Virtual PCD 00 00 export PIV_DANGEROUS_TEST_CARD_PIV_SERIAL ?= 99 37 9A 79 9E DC 48 1E A5 3E 11 CF EF 74 47 62 diff --git a/dev-vpicc/Cargo.toml b/dev-vpicc/Cargo.toml index 5f87e872..40d1cb60 100644 --- a/dev-vpicc/Cargo.toml +++ b/dev-vpicc/Cargo.toml @@ -9,8 +9,9 @@ heapless = "0.9" vpicc = "0.1.0" piv-authenticator = { path = ".." } log = "0.4" +littlefs2 = "0.8.1" trussed-rsa-alloc = { version = "0.5", features = ["raw"] } -trussed = { version = "0.2", default-features = false, features = ["aes256-cbc", "chacha8-poly1305", "crypto-client", "ed255", "filesystem-client", "p256", "p384", "shared-secret", "serde-extensions", "tdes", "x255", "virt"] } +trussed = { version = "0.2.1", default-features = false, features = ["aes256-cbc", "chacha8-poly1305", "crypto-client", "ed255", "filesystem-client", "p256", "p384", "shared-secret", "serde-extensions", "tdes", "x255", "virt"] } trussed-auth-backend = "0.2" trussed-core = "0.2" trussed-staging = { version = "0.5", features = ["chunked", "hpke", "wrap-key-to-file"], default-features = false } @@ -18,3 +19,4 @@ trussed-wrap-key-to-file = "0.3.0" trussed-hpke = "0.3.0" trussed-chunked = "0.3.0" trussed-auth = "0.5" +regex = "1" diff --git a/dev-vpicc/src/virt.rs b/dev-vpicc/src/virt.rs index 759c0789..912eb6f0 100644 --- a/dev-vpicc/src/virt.rs +++ b/dev-vpicc/src/virt.rs @@ -22,7 +22,7 @@ pub mod dispatch { use trussed_staging::{StagingBackend, StagingContext}; use trussed_wrap_key_to_file::WrapKeyToFileExtension; - /// Backends used by opcard + /// Backends used by piv pub const BACKENDS: &[BackendId] = &[ BackendId::Custom(Backend::Staging), BackendId::Custom(Backend::Auth), @@ -70,14 +70,14 @@ pub mod dispatch { } } - /// Dispatch implementation with the backends required by opcard + /// Dispatch implementation with the backends required by piv #[derive(Debug)] pub struct Dispatch { auth: AuthBackend, staging: StagingBackend, } - /// Dispatch context for the backends required by opcard + /// Dispatch context for the backends required by piv #[derive(Default)] pub struct DispatchContext { auth: AuthContext, @@ -208,11 +208,57 @@ pub mod dispatch { } } -use std::path::PathBuf; -use trussed::virt::{self, Client, StorageConfig, StoreConfig}; +use littlefs2::path; +use regex::RegexSet; +use std::{sync::LazyLock, vec::Vec}; +use trussed::{ + Platform as _, + store::{DynFilesystem, Store}, + types::{Path, PathBuf}, + virt::{self, Client, Platform, StorageConfig, StoreConfig}, +}; use trussed_core::types::Bytes; -/// Client type using a dispatcher with the backends required by opcard +fn dump_directory(fs: &dyn DynFilesystem, path: &Path, collector: &mut Vec) { + fs.read_dir_and_then(path, &mut |entries| { + for entry in entries { + let entry = entry?; + if entry.file_type().is_file() { + collector.push(entry.path().into()); + } else if entry.file_name() != path!(".") && entry.file_name() != path!("..") { + assert!(entry.file_type().is_dir()); + dump_directory(fs, entry.path(), collector); + } + } + Ok(()) + }) + .unwrap(); +} + +fn dump_fs(fs: &dyn DynFilesystem) -> Vec { + let mut collector = Vec::new(); + dump_directory(fs, path!("/"), &mut collector); + collector +} + +static VALID_PATHS: LazyLock = LazyLock::new(|| { + RegexSet::new([ + r"^/trussed/data/rng-state.bin$", + r"^/backend-auth/data/salt$", + r"^/piv/backend-auth/dat/pin.0\d$", + ]) + .unwrap() +}); + +fn cleanup(platform: &mut Platform<'_>) { + let store = platform.store(); + let mut vfs = dump_fs(store.vfs()); + + vfs.retain(|p| !VALID_PATHS.is_match(p.as_str())); + assert_eq!(vfs, Vec::new()); +} + +/// Client type using a dispatcher with the backends required by piv pub type VirtClient<'a> = Client<'a, dispatch::Dispatch>; /// Run a client using a provided store @@ -222,21 +268,23 @@ where { #[allow(clippy::unwrap_used)] virt::with_platform(store, |platform| { - platform.run_client_with_backends( - client_id, - dispatch::Dispatch::with_hw_key(Bytes::from(b"some bytes")), - dispatch::BACKENDS, - f, - ) + platform + .cleanup(Box::new(cleanup)) + .run_client_with_backends( + client_id, + dispatch::Dispatch::with_hw_key(Bytes::from(b"some bytes")), + dispatch::BACKENDS, + f, + ) }) } -/// Run the backend with the extensions required by opcard +/// Run the backend with the extensions required by piv /// using storage backed by a file pub fn with_fs_client(internal: P, client_id: &str, f: F) -> R where F: FnOnce(VirtClient<'_>) -> R, - P: Into, + P: Into, { let store = StoreConfig { internal: StorageConfig::filesystem(internal.into()), @@ -246,7 +294,7 @@ where with_client(store, client_id, f) } -/// Run the backend with the extensions required by opcard +/// Run the backend with the extensions required by piv /// using a RAM file storage pub fn with_ram_client(client_id: &str, f: F) -> R where diff --git a/src/lib.rs b/src/lib.rs index 7a9aa1c5..f6c18b54 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -130,7 +130,9 @@ where // TODO: we'd like to listen on multiple AIDs. // The way apdu-dispatch currently works, this would deselect, resetting security indicators. - pub fn deselect(&mut self) {} + pub fn deselect(&mut self) { + self.state.volatile.clear(&mut self.trussed); + } pub fn select(&mut self, mut reply: Reply<'_>) -> Result { use piv_types::Algorithms::*; @@ -976,6 +978,7 @@ impl LoadedAuthenticator<'_, T> { reply.expand(tag)?; match container { Container::KeyHistoryObject => { + read_valid.clear(self.trussed); let offset = reply.len(); self.get_key_history_object(reply.lend())?; reply.prepend_len(offset)?; @@ -986,9 +989,11 @@ impl LoadedAuthenticator<'_, T> { self.trussed, self.options.storage, reply.lend(), - read_valid, + &read_valid, ); + read_valid.clear(self.trussed); + if !res? { return Err(Status::NotFound); } @@ -1082,13 +1087,15 @@ impl LoadedAuthenticator<'_, T> { let p = tlv::get_do(&[0x01], data).ok_or(Status::IncorrectDataParameter)?; let q = tlv::get_do(&[0x02], data).ok_or(Status::IncorrectDataParameter)?; let e = tlv::get_do(&[0x03], data).ok_or(Status::IncorrectDataParameter)?; + let storage = + AsymmetricKeyReference::PivAuthentication.storage(self.options.storage); let id = syscall!(self.trussed.unsafe_inject_key( algo.key_mechanism(), &RsaImportFormat { e, p, q }.serialize().map_err(|_err| { error!("Failed rsa import serialization: {_err:?}"); Status::UnspecifiedNonpersistentExecutionError })?, - AsymmetricKeyReference::PivAuthentication.storage(self.options.storage), + storage, KeySerialization::RsaParts )) .key; @@ -1099,6 +1106,10 @@ impl LoadedAuthenticator<'_, T> { self.trussed, self.options.storage, ); + if storage == Location::Volatile { + info!("Volatile id: {id:?}"); + syscall!(self.trussed.delete(id)); + } Ok(()) } _ => Err(Status::FunctionNotSupported), @@ -1106,7 +1117,7 @@ impl LoadedAuthenticator<'_, T> { } } -/// Super trait with all trussed extensions required by opcard +/// Super trait with all trussed extensions required by piv pub trait Client: CryptoClient + FilesystemClient diff --git a/src/state.rs b/src/state.rs index 864ce5f8..cd100695 100644 --- a/src/state.rs +++ b/src/state.rs @@ -1,5 +1,5 @@ use core::convert::{TryFrom, TryInto}; -use core::mem; +use core::mem::{self, ManuallyDrop}; use flexiber::EncodableHeapless; use heapless::Vec; @@ -239,8 +239,13 @@ impl Keys { }; if let Some(key_id) = user_public_key { + info!("User public key: {key_id:?}"); syscall!(client.clear(key_id)); } + error!( + "{:?}", + syscall!(client.exists(new.alg.key_mechanism(), new.id)) + ); old } } @@ -440,7 +445,7 @@ pub struct Volatile { #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct GlobalSecurityStatus {} -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Debug, Eq, PartialEq)] pub enum ReadValid { /// Container can be read in plain text Plain, @@ -452,6 +457,22 @@ pub enum ReadValid { Encrypted(KeyId), } +impl ReadValid { + pub fn clear(self, trussed: &mut impl crate::Client) { + let this = ManuallyDrop::new(self); + if let Self::Encrypted(key_id) = &*this { + syscall!(trussed.delete(*key_id)); + } + } +} + +#[cfg(debug_assertions)] +impl Drop for ReadValid { + fn drop(&mut self) { + panic!("ReadValid must be cleared befor drop"); + } +} + impl Volatile { #[must_use] pub fn verify_pin<'this, T: crate::Client>( @@ -486,6 +507,11 @@ impl Volatile { self.app_security_status.pin_verified.is_verified() } + pub fn clear(&mut self, client: &mut impl crate::Client) { + self.clear_pin_verified(client); + *self = Self::default(); + } + pub fn clear_pin_verified(&mut self, client: &mut impl crate::Client) { self.app_security_status.pin_verified.clear(client); self.app_security_status.pin_just_verified = false; @@ -1071,12 +1097,12 @@ fn load_if_exists_streaming( location: Location, path: &PathBuf, mut buffer: Reply<'_>, - encryption: Option, + encryption: Option<&KeyId>, ) -> Result { let offset = buffer.len(); match encryption { Some(key) => { - try_syscall!(client.start_encrypted_chunked_read(location, path.clone(), key,)) + try_syscall!(client.start_encrypted_chunked_read(location, path.clone(), *key)) .map_err(|_err| { error!("Encrypted {path} couldn't be read: {_err:?}"); Status::UnspecifiedPersistentExecutionError @@ -1221,7 +1247,7 @@ impl ContainerStorage { client: &mut impl crate::Client, storage: Location, mut reply: Reply<'_>, - read_valid: ReadValid, + read_valid: &ReadValid, ) -> Result { let encryption = match read_valid { ReadValid::Plain => None, diff --git a/tests/card/mod.rs b/tests/card/mod.rs index 49cbb3bb..31483828 100644 --- a/tests/card/mod.rs +++ b/tests/card/mod.rs @@ -1,5 +1,6 @@ use dev_vpicc::{virt::with_ram_client, vpicc::VpiccCard}; use piv_authenticator::{Authenticator, Options}; +use vpicc::VSmartCard; use std::{sync::mpsc, thread::sleep, time::Duration}; use stoppable_thread::spawn; @@ -27,7 +28,7 @@ pub fn with_vsc R, R>(options: Options, f: F) -> R { let (tx, rx) = mpsc::channel(); let handle = spawn(move |stopped| { - with_ram_client("opcard", |client| { + with_ram_client("piv", |client| { let card = Authenticator::new(client, options); let mut vpicc_card = VpiccCard::new(card); let mut result = Ok(()); @@ -37,6 +38,7 @@ pub fn with_vsc R, R>(options: Options, f: F) -> R { tx.send(()).expect("failed to send message"); } } + vpicc_card.power_off(); result }) }); diff --git a/tests/command_response.rs b/tests/command_response.rs index a9bb951b..730df6b2 100644 --- a/tests/command_response.rs +++ b/tests/command_response.rs @@ -804,6 +804,7 @@ fn command_response() { for io in &t.cmd_resp { io.run(card); } + card.deselect(); }); } match t.uuid_config { @@ -815,6 +816,7 @@ fn command_response() { for io in &t.cmd_resp { io.run(card); } + card.deselect(); }); } _ => {} diff --git a/tests/setup/mod.rs b/tests/setup/mod.rs index 19ca8544..e8aed2d5 100644 --- a/tests/setup/mod.rs +++ b/tests/setup/mod.rs @@ -15,7 +15,7 @@ pub type Piv<'a> = piv_authenticator::Authenticator>; pub const WITHOUT_UUID: Options = Options::new(); pub fn piv(options: Options, test: impl FnOnce(&mut Piv<'_>) -> R) -> R { - with_ram_client("test", |client| { + with_ram_client("piv", |client| { let mut piv_app = Authenticator::new(client, options); test(&mut piv_app) })