Skip to content

Commit

Permalink
Use try_fill_bytes() to handle RNG errors in RngWorker
Browse files Browse the repository at this point in the history
  • Loading branch information
Norbert Fabritius committed Jul 8, 2024
1 parent 13e4928 commit 01c4c41
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
2 changes: 2 additions & 0 deletions heimlig/src/crypto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ pub mod x25519;
/// Common errors.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Error {
/// Error during random number generation.
Random,
/// Error during encryption.
Encrypt,
/// Error during decryption.
Expand Down
25 changes: 19 additions & 6 deletions heimlig/src/hsm/workers/rng_worker.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::common::jobs::{ClientId, Error, Request, RequestId, Response};
use crate::common::limits::MAX_RANDOM_SIZE;
use crate::crypto;
use crate::hsm::keystore::{self, KeyId};
use embassy_sync::blocking_mutex::raw::RawMutex;
use embassy_sync::mutex::Mutex;
Expand Down Expand Up @@ -82,11 +83,17 @@ impl<
error: Error::RequestTooLarge,
};
}
self.rng.lock().await.fill_bytes(output);
Response::GetRandom {
client_id,
request_id,
data: output,
match self.rng.lock().await.try_fill_bytes(output) {
Ok(()) => Response::GetRandom {
client_id,
request_id,
data: output,
},
Err(_) => Response::Error {
client_id,
request_id,
error: Error::Crypto(crypto::Error::Random),
},
}
}

Expand All @@ -109,7 +116,13 @@ impl<
Ok(key_info) => {
let mut key = [0u8; keystore::KeyType::MAX_SYMMETRIC_KEY_SIZE];
let key = &mut key[0..key_info.ty.key_size()];
self.rng.lock().await.fill_bytes(key);
if self.rng.lock().await.try_fill_bytes(key).is_err() {
return Response::Error {
client_id,
request_id,
error: Error::Crypto(crypto::Error::Random),
};
};
let mut locked_key_store = key_store.lock().await;

// Check overwrite permission
Expand Down
3 changes: 3 additions & 0 deletions heimlig/src/integration/raw_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ pub enum JobErrorRaw {
#[repr(u8)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum CryptoErrorRaw {
/// Error during random number generation
Random,
/// Error during encryption.
Encrypt,
/// Error during decryption.
Expand Down Expand Up @@ -98,6 +100,7 @@ impl From<jobs::Error> for JobErrorRaw {
impl From<crypto::Error> for CryptoErrorRaw {
fn from(value: crypto::Error) -> Self {
match value {
crypto::Error::Random => CryptoErrorRaw::Random,
crypto::Error::Encrypt => CryptoErrorRaw::Encrypt,
crypto::Error::Decrypt => CryptoErrorRaw::Decrypt,
crypto::Error::Sign => CryptoErrorRaw::Sign,
Expand Down

0 comments on commit 01c4c41

Please sign in to comment.