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

Add a get_application_key method #21

Merged
merged 3 commits into from
Apr 25, 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
16 changes: 16 additions & 0 deletions src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use trussed::{
};

use crate::{
backend::data::{expand_app_key, get_app_salt},
extension::{reply, AuthExtension, AuthReply, AuthRequest},
BACKEND_DIR,
};
Expand Down Expand Up @@ -331,6 +332,21 @@ impl ExtensionImpl<AuthExtension> for AuthBackend {
let retries = PinData::load(fs, self.location, request.id)?.retries_left();
Ok(reply::PinRetries { retries }.into())
}
AuthRequest::GetApplicationKey(request) => {
let salt = get_app_salt(fs, rng, self.location)?;
let key = expand_app_key(
&salt,
&self.get_app_key(client_id, global_fs, ctx, rng)?,
&request.info,
);
let key_id = keystore.store_key(
Location::Volatile,
Secrecy::Secret,
Kind::Symmetric(KEY_LEN),
&*key,
)?;
Ok(reply::GetApplicationKey { key: key_id }.into())
}
}
}
}
Expand Down
55 changes: 53 additions & 2 deletions src/backend/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ use subtle::ConstantTimeEq as _;
use trussed::{
platform::{CryptoRng, RngCore},
store::filestore::Filestore,
types::Location,
types::{Location, PathBuf},
Bytes,
};

use super::Error;
use crate::{Pin, PinId, MAX_PIN_LENGTH};
use crate::{Pin, PinId, BACKEND_DIR, MAX_PIN_LENGTH};

pub(crate) const SIZE: usize = 256;
pub(crate) const CHACHA_TAG_LEN: usize = 16;
Expand Down Expand Up @@ -493,6 +494,56 @@ fn pin_len(pin: &Pin) -> u8 {
pin.len() as u8
}

fn app_salt_path() -> PathBuf {
const SALT_PATH: &str = "application_salt";

let mut path = PathBuf::new();
path.push(&PathBuf::from(BACKEND_DIR));
path.push(&PathBuf::from(SALT_PATH));
path
}

pub(crate) fn get_app_salt<S: Filestore, R: CryptoRng + RngCore>(
fs: &mut S,
rng: &mut R,
location: Location,
) -> Result<Salt, Error> {
if !fs.exists(&app_salt_path(), location) {
create_app_salt(fs, rng, location)
} else {
load_app_salt(fs, location)
}
}

fn create_app_salt<S: Filestore, R: CryptoRng + RngCore>(
fs: &mut S,
rng: &mut R,
location: Location,
) -> Result<Salt, Error> {
let mut salt = Salt::default();
rng.fill_bytes(&mut *salt);
fs.write(&app_salt_path(), location, &*salt)
.map_err(|_| Error::WriteFailed)?;
Ok(salt)
}

fn load_app_salt<S: Filestore>(fs: &mut S, location: Location) -> Result<Salt, Error> {
fs.read(&app_salt_path(), location)
.map_err(|_| Error::ReadFailed)
.and_then(|b: Bytes<SALT_LEN>| (**b).try_into().map_err(|_| Error::ReadFailed))
}

pub fn expand_app_key(salt: &Salt, application_key: &Key, info: &[u8]) -> Key {
#[allow(clippy::expect_used)]
let mut hmac = Hmac::<Sha256>::new_from_slice(&**application_key)
.expect("Slice will always be of acceptable size");
hmac.update(&**salt);
hmac.update(&(info.len() as u64).to_be_bytes());
hmac.update(info);
let tmp: [_; HASH_LEN] = hmac.finalize().into_bytes().into();
tmp.into()
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
13 changes: 12 additions & 1 deletion src/extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub mod request;
use serde::{Deserialize, Serialize};
use trussed::{
serde_extensions::{Extension, ExtensionClient, ExtensionResult},
types::KeyId,
types::{KeyId, Message},
};

use crate::{Pin, PinId};
Expand All @@ -28,12 +28,14 @@ impl Extension for AuthExtension {
type Reply = AuthReply;
}

#[allow(clippy::large_enum_variant)]
#[derive(Debug, Deserialize, Serialize)]
#[allow(missing_docs)]
pub enum AuthRequest {
HasPin(request::HasPin),
CheckPin(request::CheckPin),
GetPinKey(request::GetPinKey),
GetApplicationKey(request::GetApplicationKey),
SetPin(request::SetPin),
SetPinWithKey(request::SetPinWithKey),
ChangePin(request::ChangePin),
Expand All @@ -48,6 +50,7 @@ pub enum AuthReply {
HasPin(reply::HasPin),
CheckPin(reply::CheckPin),
GetPinKey(reply::GetPinKey),
GetApplicationKey(reply::GetApplicationKey),
SetPin(reply::SetPin),
SetPinWithKey(reply::SetPinWithKey),
ChangePin(reply::ChangePin),
Expand Down Expand Up @@ -169,6 +172,14 @@ pub trait AuthClient: ExtensionClient<AuthExtension> {
fn pin_retries<I: Into<PinId>>(&mut self, id: I) -> AuthResult<'_, reply::PinRetries, Self> {
self.extension(request::PinRetries { id: id.into() })
}

/// Returns a keyid that is persistent given the "info" parameter
fn get_application_key(
&mut self,
info: Message,
) -> AuthResult<'_, reply::GetApplicationKey, Self> {
self.extension(request::GetApplicationKey { info })
}
}

impl<C: ExtensionClient<AuthExtension>> AuthClient for C {}
23 changes: 23 additions & 0 deletions src/extension/reply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,29 @@ impl TryFrom<AuthReply> for GetPinKey {
}
}

#[derive(Debug, Deserialize, Serialize)]
#[must_use]
pub struct GetApplicationKey {
pub key: KeyId,
}

impl From<GetApplicationKey> for AuthReply {
fn from(reply: GetApplicationKey) -> Self {
Self::GetApplicationKey(reply)
}
}

impl TryFrom<AuthReply> for GetApplicationKey {
type Error = Error;

fn try_from(reply: AuthReply) -> Result<Self> {
match reply {
AuthReply::GetApplicationKey(reply) => Ok(reply),
_ => Err(Error::InternalError),
}
}
}

#[derive(Debug, Deserialize, Serialize)]
pub struct SetPin;

Expand Down
13 changes: 12 additions & 1 deletion src/extension/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 or MIT

use serde::{Deserialize, Serialize};
use trussed::types::KeyId;
use trussed::types::{KeyId, Message};

use super::AuthRequest;
use crate::{Pin, PinId};
Expand Down Expand Up @@ -42,6 +42,17 @@ impl From<GetPinKey> for AuthRequest {
}
}

#[derive(Debug, Deserialize, Serialize)]
pub struct GetApplicationKey {
pub info: Message,
}

impl From<GetApplicationKey> for AuthRequest {
fn from(request: GetApplicationKey) -> Self {
Self::GetApplicationKey(request)
}
}

#[derive(Debug, Deserialize, Serialize)]
pub struct SetPin {
pub id: PinId,
Expand Down
29 changes: 28 additions & 1 deletion tests/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ use trussed::{
client::{ClientImplementation, FilesystemClient, HmacSha256},
service::Service,
syscall, try_syscall,
types::{Bytes, Location, PathBuf},
types::{Bytes, Location, Message, PathBuf},
virt::{self, Ram},
};
use trussed_auth::{AuthClient as _, PinId, MAX_HW_KEY_LEN};
Expand Down Expand Up @@ -662,3 +662,30 @@ fn delete_all_pins() {
assert!(result.is_err());
})
}

#[test]
fn application_key() {
run(BACKENDS, |client| {
let info1 = Message::from_slice(b"test1").unwrap();
let info2 = Message::from_slice(b"test2").unwrap();
let app_key1 = syscall!(client.get_application_key(info1.clone())).key;
let app_key2 = syscall!(client.get_application_key(info2)).key;
let mac1 = syscall!(client.sign_hmacsha256(app_key1, b"Some data")).signature;
let mac2 = syscall!(client.sign_hmacsha256(app_key2, b"Some data")).signature;
// Different info leads to different keys
assert_ne!(mac1, mac2);

let app_key1_again = syscall!(client.get_application_key(info1.clone())).key;
let mac1_again = syscall!(client.sign_hmacsha256(app_key1_again, b"Some data")).signature;
// Same info leads to same key
assert_eq!(mac1, mac1_again);

syscall!(client.delete_all_pins());

// After deletion same info leads to different keys
let app_key1_after_delete = syscall!(client.get_application_key(info1)).key;
let mac1_after_delete =
syscall!(client.sign_hmacsha256(app_key1_after_delete, b"Some data")).signature;
assert_ne!(mac1, mac1_after_delete);
})
}