Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion dev-vpicc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ 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 }
trussed-wrap-key-to-file = "0.3.0"
trussed-hpke = "0.3.0"
trussed-chunked = "0.3.0"
trussed-auth = "0.5"
regex = "1"
78 changes: 63 additions & 15 deletions dev-vpicc/src/virt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Backend>] = &[
BackendId::Custom(Backend::Staging),
BackendId::Custom(Backend::Auth),
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<PathBuf>) {
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<PathBuf> {
let mut collector = Vec::new();
dump_directory(fs, path!("/"), &mut collector);
collector
}

static VALID_PATHS: LazyLock<RegexSet> = 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
Expand All @@ -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<P, R, F>(internal: P, client_id: &str, f: F) -> R
where
F: FnOnce(VirtClient<'_>) -> R,
P: Into<PathBuf>,
P: Into<std::path::PathBuf>,
{
let store = StoreConfig {
internal: StorageConfig::filesystem(internal.into()),
Expand All @@ -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<R, F>(client_id: &str, f: F) -> R
where
Expand Down
19 changes: 15 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down Expand Up @@ -976,6 +978,7 @@ impl<T: Client> 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)?;
Expand All @@ -986,9 +989,11 @@ impl<T: Client> LoadedAuthenticator<'_, T> {
self.trussed,
self.options.storage,
reply.lend(),
read_valid,
&read_valid,
);

read_valid.clear(self.trussed);

if !res? {
return Err(Status::NotFound);
}
Expand Down Expand Up @@ -1082,13 +1087,15 @@ impl<T: Client> 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;
Expand All @@ -1099,14 +1106,18 @@ impl<T: Client> LoadedAuthenticator<'_, T> {
self.trussed,
self.options.storage,
);
if storage == Location::Volatile {
info!("Volatile id: {id:?}");
syscall!(self.trussed.delete(id));
}
Ok(())
}
_ => Err(Status::FunctionNotSupported),
}
}
}

/// Super trait with all trussed extensions required by opcard
/// Super trait with all trussed extensions required by piv
pub trait Client:
CryptoClient
+ FilesystemClient
Expand Down
36 changes: 31 additions & 5 deletions src/state.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use core::convert::{TryFrom, TryInto};
use core::mem;
use core::mem::{self, ManuallyDrop};

use flexiber::EncodableHeapless;
use heapless::Vec;
Expand Down Expand Up @@ -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
}
}
Expand Down Expand Up @@ -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,
Expand All @@ -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>(
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -1071,12 +1097,12 @@ fn load_if_exists_streaming(
location: Location,
path: &PathBuf,
mut buffer: Reply<'_>,
encryption: Option<KeyId>,
encryption: Option<&KeyId>,
) -> Result<bool, Status> {
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
Expand Down Expand Up @@ -1221,7 +1247,7 @@ impl ContainerStorage {
client: &mut impl crate::Client,
storage: Location,
mut reply: Reply<'_>,
read_valid: ReadValid,
read_valid: &ReadValid,
) -> Result<bool, Status> {
let encryption = match read_valid {
ReadValid::Plain => None,
Expand Down
4 changes: 3 additions & 1 deletion tests/card/mod.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -27,7 +28,7 @@ pub fn with_vsc<F: FnOnce() -> 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(());
Expand All @@ -37,6 +38,7 @@ pub fn with_vsc<F: FnOnce() -> R, R>(options: Options, f: F) -> R {
tx.send(()).expect("failed to send message");
}
}
vpicc_card.power_off();
result
})
});
Expand Down
2 changes: 2 additions & 0 deletions tests/command_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,7 @@ fn command_response() {
for io in &t.cmd_resp {
io.run(card);
}
card.deselect();
});
}
match t.uuid_config {
Expand All @@ -815,6 +816,7 @@ fn command_response() {
for io in &t.cmd_resp {
io.run(card);
}
card.deselect();
});
}
_ => {}
Expand Down
2 changes: 1 addition & 1 deletion tests/setup/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub type Piv<'a> = piv_authenticator::Authenticator<VirtClient<'a>>;
pub const WITHOUT_UUID: Options = Options::new();

pub fn piv<R>(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)
})
Expand Down
Loading