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

Implement hpke extension #36

Merged
merged 2 commits into from
Oct 17, 2024
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
60 changes: 60 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,66 @@

[Unreleased]: https://github.com/trussed-dev/trussed-staging/compare/v0.3.0...HEAD

## [v0.3.6][] (2024-10-17)

[v0.3.6]: https://github.com/Nitrokey/trussed-se050-backend/compare/v0.3.5...v0.3.6

- Add implementation of the `trussed-hpke` extension ([#36][])

[#36]: https://github.com/Nitrokey/trussed-se050-backend/pull/36

## [v0.3.5][] (2024-08-13)

[v0.3.5]: https://github.com/Nitrokey/trussed-se050-backend/compare/v0.3.4...v0.3.5

### Added

- Add support for more curves ([#33](https://github.com/Nitrokey/trussed-se050-backend/pull/33)):
- NIST P-384
- Brainpool P-256
- Brainpool P-384
- Brainpool P-512

### Changed

- Delete metadata for transient keys ([#34](https://github.com/Nitrokey/trussed-se050-backend/pull/34))

## [v0.3.4][] (2024-07-31)

[v0.3.4]: https://github.com/Nitrokey/trussed-se050-backend/compare/v0.3.3...v0.3.4

No changes.

## [v0.3.3][] (2024-06-21)

[v0.3.3]: https://github.com/Nitrokey/trussed-se050-backend/compare/v0.3.2...v0.3.3

### Changed

- Update `trussed-rsa-alloc` to v0.2.1 ([#32](https://github.com/Nitrokey/trussed-se050-backend/pull/32))

## [v0.3.2][] (2024-06-07)

[v0.3.2]: https://github.com/Nitrokey/trussed-se050-backend/compare/v0.3.1...v0.3.2

### Changed

- Improve inlining of se050 constants ([#20](https://github.com/Nitrokey/trussed-se050-backend/pull/20))
- Make configure method public ([#31](https://github.com/Nitrokey/trussed-se050-backend/pull/31))

### Fixed

- Fully delete application PINs on application factory-reset ([#30](https://github.com/Nitrokey/trussed-se050-backend/pull/30))

## [v0.3.1][] (2024-04-10)

[v0.3.1]: https://github.com/Nitrokey/trussed-se050-backend/compare/v0.3.0...v0.3.1

### Changed

- Remove top-level `dat` folder to reduce filesystem usage ([#16](https://github.com/Nitrokey/trussed-se050-backend/pull/16))
- Update `trussed-auth` to v0.3.0

## [v0.3.0][] (2024-03-15)

[v0.3.0]: https://github.com/Nitrokey/trussed-se050-backend/compare/v0.2.0...v0.3.0
Expand Down
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ license = "Apache-2.0 OR MIT"

[package]
name = "trussed-se050-backend"
version = "0.3.0"
version = "0.3.6"
authors.workspace = true
edition.workspace = true
repository.workspace = true
Expand All @@ -28,6 +28,7 @@ trussed-auth = "0.3.0"
trussed-manage = "0.1.0"
trussed-se050-manage = "0.1.0"
trussed-wrap-key-to-file = "0.1.0"
trussed-hpke = "0.1.0"
delog = "0.1.6"
embedded-hal = "0.2.7"
hkdf = { version = "0.12.3", default-features = false }
Expand All @@ -49,6 +50,7 @@ p256-cortex-m4 = { version = "0.1.0-alpha.6", features = ["prehash", "sec1-signa
admin-app = "0.1.0"
bitflags = "2.5.0"
der = "0.7.9"
chacha20poly1305 = { version = "0.10.1", default-features = false }

[dev-dependencies]
admin-app = { version = "0.1.0", features = ["migration-tests"] }
Expand All @@ -64,6 +66,7 @@ trussed-manage = { git = "https://github.com/trussed-dev/trussed-staging.git", t
trussed-rsa-alloc = { git = "https://github.com/trussed-dev/trussed-rsa-backend.git", tag = "v0.2.1" }
trussed-wrap-key-to-file = { git = "https://github.com/trussed-dev/trussed-staging.git", tag = "wrap-key-to-file-v0.1.0" }
admin-app = { git = "https://github.com/Nitrokey/admin-app.git", tag = "v0.1.0-nitrokey.12" }
trussed-hpke = { git = "https://github.com/trussed-dev/trussed-staging.git", rev = "f0babe53813e7882cfe5ce749ebe3a65fc143fd7" }

trussed-se050-manage = { path = "extensions/se050-manage" }

Expand Down
155 changes: 88 additions & 67 deletions src/core_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ struct VolatileRsaKey {
intermediary_key: [u8; 16],
}

#[derive(Serialize, Deserialize, Debug, Clone)]
enum WrappedKeyType {
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub(crate) enum WrappedKeyType {
Volatile,
VolatileRsa,
}
Expand Down Expand Up @@ -445,7 +445,7 @@ impl<Twi: I2CForT1, D: DelayUs<u32>> Se050Backend<Twi, D> {
/// Put a volatile key stored on the filesystem back into the SE050
///
/// This is used to perform one operation, the key must then be cleared again with [`clear_volatile_key`](Se050Backend::clear_volatile_key)
fn reimport_volatile_key(
pub(crate) fn reimport_volatile_key(
&mut self,
key: KeyId,
kind: Kind,
Expand Down Expand Up @@ -775,7 +775,7 @@ impl<Twi: I2CForT1, D: DelayUs<u32>> Se050Backend<Twi, D> {
Ok(reply::DeriveKey { key })
}

fn clear_volatile_key(&mut self, object_id: ObjectId) -> Result<(), Error> {
pub(crate) fn clear_volatile_key(&mut self, object_id: ObjectId) -> Result<(), Error> {
self.se
.run_command(&DeleteSecureObject { object_id }, &mut [0; 128])
.map_err(|_err| {
Expand Down Expand Up @@ -2568,21 +2568,15 @@ impl<Twi: I2CForT1, D: DelayUs<u32>> Se050Backend<Twi, D> {
Ok(reply::Clear { success })
}

pub(crate) fn wrap_key(
pub(crate) fn wrap_key_data(
&mut self,
req: &request::WrapKey,
core_keystore: &mut impl Keystore,
key: KeyId,
se050_keystore: &mut impl Keystore,
ns: NamespaceValue,
) -> Result<reply::WrapKey, Error> {
if !matches!(req.mechanism, Mechanism::Chacha8Poly1305) {
return Err(Error::RequestNotAvailable);
}
let (parsed_key, _parsed_ty) = parse_key_id(req.key, ns).ok_or_else(|| {
debug!("Failed to parse key id to wrap: {:?}", req.key);
// Let non-se050 keys be wrapped by the core backend
Error::RequestNotAvailable
})?;
) -> Result<Option<(key::Key, WrappedKeyType)>, Error> {
let Some((parsed_key, _parsed_ty)) = parse_key_id(key, ns) else {
return Ok(None);
};

let ty = match parsed_key {
ParsedObjectId::VolatileKey(_) => WrappedKeyType::Volatile,
Expand All @@ -2592,7 +2586,7 @@ impl<Twi: I2CForT1, D: DelayUs<u32>> Se050Backend<Twi, D> {
return Err(Error::ObjectHandleInvalid);
}
};
debug!("trussed: Chacha8Poly1305::WrapKey {:?}", req.key);
debug!("trussed: Chacha8Poly1305::WrapKey {:?}", key);
match parsed_key {
ParsedObjectId::VolatileKey(_id) => {
debug!("Id: {:?}", _id.0);
Expand All @@ -2603,14 +2597,31 @@ impl<Twi: I2CForT1, D: DelayUs<u32>> Se050Backend<Twi, D> {
_ => unreachable!(),
}

let serialized_key = se050_keystore.load_key(key::Secrecy::Secret, None, &req.key)?;
let serialized_key = se050_keystore.load_key(key::Secrecy::Secret, None, &key)?;

Ok(Some((serialized_key, ty)))
}

let message = Message::from_slice(&serialized_key.serialize()).unwrap();
pub(crate) fn wrap_key(
&mut self,
req: &request::WrapKey,
core_keystore: &mut impl Keystore,
se050_keystore: &mut impl Keystore,
ns: NamespaceValue,
) -> Result<reply::WrapKey, Error> {
if !matches!(req.mechanism, Mechanism::Chacha8Poly1305) {
return Err(Error::RequestNotAvailable);
}
let Some((key, ty)) = self.wrap_key_data(req.key, se050_keystore, ns)? else {
debug!("Failed to parse key id");
// Let non-se050 keys be wrapped by the core backend
return Err(Error::RequestNotAvailable);
};

let encryption_request = request::Encrypt {
mechanism: Mechanism::Chacha8Poly1305,
key: req.wrapping_key,
message,
message: Bytes::from_slice(&key.serialize()).unwrap(),
associated_data: req.associated_data.clone(),
nonce: req.nonce.clone(),
};
Expand Down Expand Up @@ -2647,61 +2658,19 @@ impl<Twi: I2CForT1, D: DelayUs<u32>> Se050Backend<Twi, D> {
Ok(())
}

pub(crate) fn unwrap_key(
pub(crate) fn store_unwrapped_key_data(
&mut self,
req: &request::UnwrapKey,
core_keystore: &mut impl Keystore,
ty: WrappedKeyType,
serialized_key: &[u8],
se050_keystore: &mut impl Keystore,
ns: NamespaceValue,
) -> Result<reply::UnwrapKey, Error> {
debug!("Unwrapping_key");
// SE050 wrapped keys start with a `0`, see `wrap_key` for details
if !matches!(req.mechanism, Mechanism::Chacha8Poly1305)
|| req.wrapped_key.first() != Some(&0)
{
return Err(Error::RequestNotAvailable);
}
if !matches!(req.attributes.persistence, Location::Volatile) {
return Err(Error::FunctionNotSupported);
}

let WrappedKeyData {
encrypted_data:
reply::Encrypt {
ciphertext,
nonce,
tag,
},
ty,
} = postcard::from_bytes(&req.wrapped_key[1..]).map_err(|_| Error::CborError)?;

let decryption_request = request::Decrypt {
mechanism: Mechanism::Chacha8Poly1305,
key: req.wrapping_key,
message: ciphertext,
associated_data: req.associated_data.clone(),
nonce,
tag,
};

let serialized_key = if let Some(serialized_key) =
<trussed::mechanisms::Chacha8Poly1305 as trussed::service::Decrypt>::decrypt(
core_keystore,
&decryption_request,
)?
.plaintext
{
serialized_key
} else {
return Ok(reply::UnwrapKey { key: None });
};

) -> Result<KeyId, Error> {
// TODO: probably change this to returning Option<key> too
let key::Key {
flags: _,
kind,
material,
} = key::Key::try_deserialize(&serialized_key)?;
} = key::Key::try_deserialize(serialized_key)?;

let key_ty = match kind {
Kind::Rsa2048 => KeyType::Rsa2048,
Expand Down Expand Up @@ -2759,6 +2728,58 @@ impl<Twi: I2CForT1, D: DelayUs<u32>> Se050Backend<Twi, D> {
&key_id,
&material,
)?;
Ok(key_id)
}

pub(crate) fn unwrap_key(
&mut self,
req: &request::UnwrapKey,
core_keystore: &mut impl Keystore,
se050_keystore: &mut impl Keystore,
ns: NamespaceValue,
) -> Result<reply::UnwrapKey, Error> {
debug!("Unwrapping_key");
// SE050 wrapped keys start with a `0`, see `wrap_key` for details
if !matches!(req.mechanism, Mechanism::Chacha8Poly1305)
|| req.wrapped_key.first() != Some(&0)
{
return Err(Error::RequestNotAvailable);
}
if !matches!(req.attributes.persistence, Location::Volatile) {
return Err(Error::FunctionNotSupported);
}

let WrappedKeyData {
encrypted_data:
reply::Encrypt {
ciphertext,
nonce,
tag,
},
ty,
} = postcard::from_bytes(&req.wrapped_key[1..]).map_err(|_| Error::CborError)?;

let decryption_request = request::Decrypt {
mechanism: Mechanism::Chacha8Poly1305,
key: req.wrapping_key,
message: ciphertext,
associated_data: req.associated_data.clone(),
nonce,
tag,
};

let decryption_result =
<trussed::mechanisms::Chacha8Poly1305 as trussed::service::Decrypt>::decrypt(
core_keystore,
&decryption_request,
)?
.plaintext;

let Some(serialized_key) = decryption_result else {
return Ok(reply::UnwrapKey { key: None });
};

let key_id = self.store_unwrapped_key_data(ty, &serialized_key, se050_keystore, ns)?;

Ok(reply::UnwrapKey { key: Some(key_id) })
}
Expand Down
Loading