Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Keep the users keys stable after RESET RETRY COUNTER #135

Merged
merged 1 commit into from
Apr 11, 2023
Merged
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
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ trussed = "0.1.0"
trussed-rsa-alloc = { version = "0.1.0", optional = true }
serde_repr = "0.1"
hex-literal = "0.3.4"
trussed-auth = "0.1.0"
trussed-auth = "0.2.1"

# optional dependencies
apdu-dispatch = { version = "0.1", optional = true }
Expand Down Expand Up @@ -85,8 +85,8 @@ log-error = []
interchange = { git = "https://github.com/trussed-dev/interchange", rev = "fe5633466640e1e9a8c06d9b5dd1d0af08c272af" }
littlefs2 = { git = "https://github.com/Nitrokey/littlefs2", tag = "v0.3.2-nitrokey-2" }
p256-cortex-m4 = { git = "https://github.com/Nitrokey/p256-cortex-m4", tag = "v0.1.0-alpha.6-nitrokey-1" }
trussed = { git = "https://github.com/Nitrokey/trussed" , tag = "v0.1.0-nitrokey.8" }
trussed-auth = { git = "https://github.com/trussed-dev/trussed-auth.git", tag= "v0.1.0"}
trussed = { git = "https://github.com/Nitrokey/trussed" , rev = "56848118cefa74eaa4f33e93d79930d7e66717ee" }
trussed-auth = { git = "https://github.com/trussed-dev/trussed-auth.git", tag= "v0.2.1"}
trussed-rsa-alloc = { git = "https://github.com/Nitrokey/trussed-rsa-backend", rev = "311d2366f99cc300b03d61e7f6a0a07abd3e8700" }

[package.metadata.docs.rs]
Expand Down
28 changes: 9 additions & 19 deletions src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@ fn reset_retry_conter<const R: usize, T: trussed::Client + AuthClient>(
}

fn reset_retry_conter_with_p3<const R: usize, T: trussed::Client + AuthClient>(
ctx: LoadedContext<'_, R, T>,
mut ctx: LoadedContext<'_, R, T>,
) -> Result<(), Status> {
if ctx.data.len() < MIN_LENGTH_USER_PIN || ctx.data.len() > MAX_PIN_LENGTH {
warn!(
Expand All @@ -568,13 +568,7 @@ fn reset_retry_conter_with_p3<const R: usize, T: trussed::Client + AuthClient>(
}

ctx.state
.persistent
.set_pin(
ctx.backend.client_mut(),
ctx.options.storage,
ctx.data,
Password::Pw1,
)
.reset_user_code_with_pw3(ctx.backend.client_mut(), ctx.options.storage, ctx.data)
.map_err(|_err| {
error!("Failed to change PIN: {_err}");
Status::UnspecifiedNonpersistentExecutionError
Expand All @@ -601,7 +595,7 @@ fn reset_retry_conter_with_code<const R: usize, T: trussed::Client + AuthClient>
let res = ctx
.state
.check_pin(ctx.backend.client_mut(), old, Password::ResetCode);
match res {
let rc_key = match res {
Err(Error::InvalidPin) => {
return Err(Status::RemainingRetries(
ctx.state
Expand All @@ -613,26 +607,22 @@ fn reset_retry_conter_with_code<const R: usize, T: trussed::Client + AuthClient>
error!("Failed to check reset code: {_err:?}");
return Err(Status::UnspecifiedNonpersistentExecutionError);
}
Ok(_reset_kek) => {}
}
Ok(rc_key) => rc_key,
};

if new.len() > MAX_PIN_LENGTH || new.len() < MIN_LENGTH_USER_PIN {
warn!("Attempt to set resetting code with invalid length");
return Err(Status::IncorrectDataParameter);
}

ctx.state
.persistent
.set_pin(
ctx.backend.client_mut(),
ctx.options.storage,
new,
Password::Pw1,
)
.reset_user_code_with_rc(ctx.backend.client_mut(), ctx.options.storage, new, rc_key)
.map_err(|_err| {
error!("Failed to change PIN: {_err:?}");
Status::UnspecifiedNonpersistentExecutionError
})
})?;
syscall!(ctx.backend.client_mut().delete(rc_key));
Ok(())
}

// § 7.2.5
Expand Down
10 changes: 2 additions & 8 deletions src/command/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -992,7 +992,7 @@ fn put_enc_dec_key<const R: usize, T: trussed::Client + AuthClient>(
}

fn put_resetting_code<const R: usize, T: trussed::Client + AuthClient>(
ctx: LoadedContext<'_, R, T>,
mut ctx: LoadedContext<'_, R, T>,
) -> Result<(), Status> {
if ctx.data.is_empty() {
info!("Removing resetting code");
Expand All @@ -1014,13 +1014,7 @@ fn put_resetting_code<const R: usize, T: trussed::Client + AuthClient>(
}

ctx.state
.persistent
.set_pin(
ctx.backend.client_mut(),
ctx.options.storage,
ctx.data,
Password::ResetCode,
)
.set_reset_code(ctx.backend.client_mut(), ctx.options.storage, ctx.data)
.map_err(|_err| {
error!("Failed to change resetting code: {_err}");
Status::UnspecifiedNonpersistentExecutionError
Expand Down
157 changes: 140 additions & 17 deletions src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use serde_repr::{Deserialize_repr, Serialize_repr};

use trussed::api::reply::Metadata;
use trussed::config::MAX_MESSAGE_LENGTH;
use trussed::types::{KeyId, Location, PathBuf};
use trussed::types::{KeyId, Location, Mechanism, PathBuf, StorageAttributes};
use trussed::{syscall, try_syscall};
use trussed_auth::AuthClient;

Expand Down Expand Up @@ -299,6 +299,7 @@ impl<'a> LoadedState<'a> {
.set_pin_len(client, storage, pin.len(), pin_id)?;
Ok(())
}

pub fn check_pin<T: trussed::Client + AuthClient>(
&mut self,
client: &mut T,
Expand All @@ -314,6 +315,110 @@ impl<'a> LoadedState<'a> {
.result
.ok_or(Error::InvalidPin)
}

fn get_user_key<T: trussed::Client + AuthClient>(
&mut self,
client: &mut T,
storage: Location,
) -> Result<KeyId, Error> {
let admin_key = self.volatile.admin_kek().ok_or(Error::InvalidPin)?;
let user_wrapped =
syscall!(client.read_file(storage, PathBuf::from(ADMIN_USER_KEY_BACKUP))).data;
#[allow(clippy::expect_used)]
let user_key = syscall!(client.unwrap_key(
Mechanism::Chacha8Poly1305,
admin_key,
user_wrapped,
ADMIN_USER_KEY_BACKUP.as_bytes(),
StorageAttributes::new().set_persistence(Location::Volatile)
))
.key
.expect("Key backup should not fail to unwrap");
Ok(user_key)
}

fn get_user_key_from_rc<T: trussed::Client + AuthClient>(
&mut self,
client: &mut T,
storage: Location,
rc_key: KeyId,
) -> Result<KeyId, Error> {
let user_wrapped =
syscall!(client.read_file(storage, PathBuf::from(RC_USER_KEY_BACKUP))).data;
#[allow(clippy::expect_used)]
let user_key = syscall!(client.unwrap_key(
Mechanism::Chacha8Poly1305,
rc_key,
user_wrapped,
RC_USER_KEY_BACKUP.as_bytes(),
StorageAttributes::new().set_persistence(Location::Volatile)
))
.key
.expect("Key backup should not fail to unwrap");
Ok(user_key)
}

pub fn reset_user_code_with_pw3<T: trussed::Client + AuthClient>(
&mut self,
client: &mut T,
storage: Location,
new_value: &[u8],
) -> Result<(), Error> {
let user_key = self.get_user_key(client, storage)?;
let new_pin = Bytes::from_slice(new_value).map_err(|_| Error::InvalidPin)?;
syscall!(client.set_pin_with_key(Password::Pw1, new_pin, Some(3), user_key));
syscall!(client.delete(user_key));
Ok(())
}

pub fn reset_user_code_with_rc<T: trussed::Client + AuthClient>(
&mut self,
client: &mut T,
storage: Location,
new_value: &[u8],
rc_key: KeyId,
) -> Result<(), Error> {
let user_key = self.get_user_key_from_rc(client, storage, rc_key)?;
let new_pin = Bytes::from_slice(new_value).map_err(|_| Error::InvalidPin)?;
syscall!(client.set_pin_with_key(Password::Pw1, new_pin, Some(3), user_key));
syscall!(client.delete(user_key));
Ok(())
}

pub fn set_reset_code<T: trussed::Client + AuthClient>(
&mut self,
client: &mut T,
storage: Location,
new_value: &[u8],
) -> Result<(), Error> {
let new_pin = Bytes::from_slice(new_value).map_err(|_| Error::InvalidPin)?;
syscall!(client.set_pin(Password::ResetCode, new_pin.clone(), Some(3), true));
self.persistent
.set_pin_len(client, storage, new_pin.len(), Password::ResetCode)?;
#[allow(clippy::expect_used)]
let rc_key = syscall!(client.get_pin_key(Password::ResetCode, new_pin))
.result
.expect("New pin should not fail");

let user_key = self.get_user_key(client, storage)?;
let wrapped_user_key = syscall!(client.wrap_key(
Mechanism::Chacha8Poly1305,
rc_key,
user_key,
RC_USER_KEY_BACKUP.as_bytes()
))
.wrapped_key;
syscall!(client.write_file(
storage,
PathBuf::from(RC_USER_KEY_BACKUP),
wrapped_user_key,
None
));
syscall!(client.delete(user_key));
syscall!(client.delete(rc_key));

Ok(())
}
}

enum_u8! {
Expand Down Expand Up @@ -360,8 +465,14 @@ pub struct Persistent {
uif_aut: Uif,
}

/// User pin key wrapped by the resetting code key
const RC_USER_KEY_BACKUP: &str = "rc-user-pin-key.bin";
/// User pin key wrapped by the admin key
const ADMIN_USER_KEY_BACKUP: &str = "admin-user-pin-key.bin";

impl Persistent {
const FILENAME: &'static str = "persistent-state.cbor";

// § 4.3
const MAX_RETRIES: u8 = 3;

Expand Down Expand Up @@ -396,23 +507,47 @@ impl Persistent {
PathBuf::from(Self::FILENAME)
}

fn init_pins<T: trussed::Client + AuthClient>(client: &mut T) -> Result<(), Error> {
fn init_pins<T: trussed::Client + AuthClient>(
client: &mut T,
location: Location,
) -> Result<(), Error> {
#[allow(clippy::unwrap_used)]
let default_user_pin = Bytes::from_slice(DEFAULT_USER_PIN).unwrap();
#[allow(clippy::unwrap_used)]
let default_admin_pin = Bytes::from_slice(DEFAULT_ADMIN_PIN).unwrap();
syscall!(client.set_pin(
Password::Pw1,
default_user_pin,
default_user_pin.clone(),
Some(Self::MAX_RETRIES),
true,
));
syscall!(client.set_pin(
Password::Pw3,
default_admin_pin,
default_admin_pin.clone(),
Some(Self::MAX_RETRIES),
true,
));
#[allow(clippy::expect_used)]
let user_key = syscall!(client.get_pin_key(Password::Pw1, default_user_pin))
.result
.expect("Default pin should work after initialization");
#[allow(clippy::expect_used)]
let admin_key = syscall!(client.get_pin_key(Password::Pw3, default_admin_pin))
.result
.expect("Default pin should work after initialization");

let backup = syscall!(client.wrap_key(
Mechanism::Chacha8Poly1305,
admin_key,
user_key,
ADMIN_USER_KEY_BACKUP.as_bytes()
))
.wrapped_key;
syscall!(client.write_file(location, PathBuf::from(ADMIN_USER_KEY_BACKUP), backup, None));

// Clean up memory
syscall!(client.delete(user_key));
syscall!(client.delete(admin_key));
Ok(())
}
pub fn load<T: trussed::Client + AuthClient>(
Expand All @@ -425,7 +560,7 @@ impl Persistent {
Error::Loading
})
} else {
Self::init_pins(client)?;
Self::init_pins(client, storage)?;
Ok(Self::default())
}
}
Expand Down Expand Up @@ -474,18 +609,6 @@ impl Persistent {
self.reset_code_pin_len.map(Into::into)
}

pub fn set_pin<T: trussed::Client + AuthClient>(
&mut self,
client: &mut T,
storage: Location,
new_value: &[u8],
password: Password,
) -> Result<(), Error> {
let new_pin = Bytes::from_slice(new_value).map_err(|_| Error::InvalidPin)?;
syscall!(client.set_pin(password, new_pin.clone(), Some(Self::MAX_RETRIES), true));
self.set_pin_len(client, storage, new_pin.len(), password)
}

pub fn change_pin<T: trussed::Client + AuthClient>(
&mut self,
client: &mut T,
Expand Down