Skip to content

Commit

Permalink
Add return error code to rng::fill_bytes (google#120)
Browse files Browse the repository at this point in the history
  • Loading branch information
ia0 authored Apr 20, 2023
1 parent 229e2cf commit cb1c221
Show file tree
Hide file tree
Showing 19 changed files with 126 additions and 37 deletions.
2 changes: 1 addition & 1 deletion book/src/applet/prelude/usb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ fn main() {
//{ ANCHOR: generate
// Generate a question for this level.
let mut question = vec![0; level];
rng::fill_bytes(&mut question);
rng::fill_bytes(&mut question).unwrap();
for byte in &mut question {
const BASE32: [u8; 32] = *b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
*byte = BASE32[(*byte & 0x1f) as usize];
Expand Down
3 changes: 2 additions & 1 deletion crates/api-desc/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

### Minor

- Add scheduling::breakpoint
- Add return code to `rng::fill_bytes()`
- Add `scheduling::breakpoint()`

### Patch

Expand Down
7 changes: 6 additions & 1 deletion crates/api-desc/src/rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,12 @@ pub(crate) fn new() -> Item {

/// The length of the slice.
len: usize,
} -> {}
} -> {
/// Error code: 0 on success, -1 on error
///
/// The buffer may be modified on error and should not be used.
res: isize
}
}];
Item::Mod(Mod { docs, name, items })
}
3 changes: 2 additions & 1 deletion crates/prelude/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

### Minor

- Add scheduling::breakpoint
- Add return code to `rng::fill_bytes()`
- Add `scheduling::breakpoint()`

## 0.1.3

Expand Down
12 changes: 10 additions & 2 deletions crates/prelude/src/rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,16 @@
use wasefire_applet_api::rng as api;

/// Error generating randomness.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Error;

/// Fills a slice with random bytes.
pub fn fill_bytes(buf: &mut [u8]) {
pub fn fill_bytes(buf: &mut [u8]) -> Result<(), Error> {
let params = api::fill_bytes::Params { ptr: buf.as_mut_ptr(), len: buf.len() };
unsafe { api::fill_bytes(params) }
let api::fill_bytes::Results { res } = unsafe { api::fill_bytes(params) };
match res {
0 => Ok(()),
_ => Err(Error),
}
}
3 changes: 2 additions & 1 deletion crates/scheduler/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@

### Minor

- Support `rng::fill_bytes()` return code
- Add `Events::is_empty()`
- Support scheduling::breakpoint
- Support `scheduling::breakpoint()`

### Patch

Expand Down
9 changes: 6 additions & 3 deletions crates/scheduler/src/call/rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use wasefire_applet_api::rng::{self as api, Api};
use wasefire_board_api::rng::Api as _;
use wasefire_board_api::Api as Board;

use crate::{DispatchSchedulerCall, SchedulerCall, Trap};
use crate::{DispatchSchedulerCall, SchedulerCall};

pub fn process<B: Board>(call: Api<DispatchSchedulerCall<B>>) {
match call {
Expand All @@ -30,8 +30,11 @@ fn fill_bytes<B: Board>(mut call: SchedulerCall<B, api::fill_bytes::Sig>) {
let memory = scheduler.applet.memory();
let results = try {
let output = memory.get_mut(*ptr, *len)?;
scheduler.board.rng().fill_bytes(output).map_err(|_| Trap)?;
api::fill_bytes::Results {}
let res = match scheduler.board.rng().fill_bytes(output) {
Ok(_) => 0,
Err(_) => u32::MAX,
};
api::fill_bytes::Results { res: res.into() }
};
call.reply(results);
}
5 changes: 4 additions & 1 deletion examples/assemblyscript/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,10 @@

// The length of the slice.
len: usize,
): void
// Error code: 0 on success, -1 on error
//
// The buffer may be modified on error and should not be used.
): isize
// END OF MODULE rng

// START OF MODULE scheduling
Expand Down
6 changes: 3 additions & 3 deletions examples/rust/ccm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ use wasefire::usb::serial::{read_byte, write_all};
fn main() {
loop {
let mut key = [0; 16];
fill_bytes(&mut key);
fill_bytes(&mut key).unwrap();
write_hex("key", &key);
let mut iv = [0; 8];
fill_bytes(&mut iv);
fill_bytes(&mut iv).unwrap();
write_hex("iv", &iv);

let len = match read_byte().unwrap() {
Expand All @@ -44,7 +44,7 @@ fn main() {
_ => continue,
} as usize;
let mut clear = vec![0; len];
fill_bytes(&mut clear);
fill_bytes(&mut clear).unwrap();
write_hex("clear", &clear);

let cipher = ccm::encrypt(&key, &iv, &clear).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion examples/rust/hsm/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

60 changes: 59 additions & 1 deletion examples/rust/hsm/common/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions examples/rust/hsm/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ edition = "2021"

[dependencies]
thiserror = { version = "1.0.40", optional = true }
wasefire-applet-api = { path = "../../../../crates/api", optional = true }
wasefire = { path = "../../../../crates/prelude", optional = true }

[features]
api = ["dep:wasefire-applet-api"]
api = ["dep:wasefire"]
std = ["dep:thiserror"]
34 changes: 21 additions & 13 deletions examples/rust/hsm/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@ extern crate alloc;
use alloc::vec;
use alloc::vec::Vec;

#[cfg(feature = "api")]
use wasefire_applet_api as api;

pub type KeyHandle = usize;

#[derive(Debug)]
Expand Down Expand Up @@ -55,23 +52,32 @@ pub enum Error {
BadFormat,
#[cfg_attr(feature = "std", error("crypto error"))]
CryptoError,
#[cfg_attr(feature = "std", error("rng error"))]
RngError,
#[cfg_attr(feature = "std", error("store error"))]
StoreError,
#[cfg_attr(feature = "std", error("usb error"))]
UsbError,
}

#[cfg(feature = "api")]
impl From<api::store::Error> for Error {
fn from(_: api::store::Error) -> Self {
Error::StoreError
impl From<wasefire::crypto::Error> for Error {
fn from(_: wasefire::crypto::Error) -> Self {
Error::CryptoError
}
}

#[cfg(feature = "api")]
impl From<api::crypto::Error> for Error {
fn from(_: api::crypto::Error) -> Self {
Error::CryptoError
impl From<wasefire::rng::Error> for Error {
fn from(_: wasefire::rng::Error) -> Self {
Error::RngError
}
}

#[cfg(feature = "api")]
impl From<wasefire::store::Error> for Error {
fn from(_: wasefire::store::Error) -> Self {
Error::StoreError
}
}

Expand Down Expand Up @@ -280,8 +286,9 @@ impl Serialize for Error {
Error::BadHandle => 1,
Error::BadFormat => 2,
Error::CryptoError => 3,
Error::StoreError => 4,
Error::UsbError => 5,
Error::RngError => 4,
Error::StoreError => 5,
Error::UsbError => 6,
};
tag.serialize(serializer)
}
Expand All @@ -295,8 +302,9 @@ impl Deserialize for Error {
1 => Error::BadHandle,
2 => Error::BadFormat,
3 => Error::CryptoError,
4 => Error::StoreError,
5 => Error::UsbError,
4 => Error::RngError,
5 => Error::StoreError,
6 => Error::UsbError,
_ => return Err(Error::BadFormat),
})
}
Expand Down
3 changes: 2 additions & 1 deletion examples/rust/hsm/common/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

set -ex

cargo check
cargo check --features=std
cargo check --target=wasm32-unknown-unknown --features=api
cargo fmt -- --check
cargo clippy -- --deny=warnings
2 changes: 1 addition & 1 deletion examples/rust/hsm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ fn process(request: Request) -> Result<Response, Error> {
match request {
Request::GenerateKey { key } => {
let mut secret = [0; 16];
rng::fill_bytes(&mut secret);
rng::fill_bytes(&mut secret)?;
store::insert(key, &secret)?;
Ok(Response::GenerateKey)
}
Expand Down
2 changes: 1 addition & 1 deletion examples/rust/memory_game/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ fn main() {

// Generate a question for this level.
let mut question = vec![0; level];
rng::fill_bytes(&mut question);
rng::fill_bytes(&mut question).unwrap();
for byte in &mut question {
const BASE32: [u8; 32] = *b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
*byte = BASE32[(*byte & 0x1f) as usize];
Expand Down
2 changes: 1 addition & 1 deletion examples/rust/panic/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use wasefire::rng::fill_bytes;

fn flip() -> bool {
let mut x = 0u8;
fill_bytes(slice::from_mut(&mut x));
fill_bytes(slice::from_mut(&mut x)).unwrap();
x & 1 == 1
}

Expand Down
2 changes: 1 addition & 1 deletion examples/rust/rand/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ fn main() {
_ => continue,
};
let mut buf = vec![0; len as usize];
rng::fill_bytes(&mut buf);
rng::fill_bytes(&mut buf).unwrap();
usb::serial::write_all(format!("{buf:02x?}\r\n").as_bytes()).unwrap();
}
}
2 changes: 1 addition & 1 deletion examples/rust/rng_test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn test_non_constant() {
debug!("test_non_constant(): This should generate 5 different buffers.");
let mut buffers = [[0; 8]; 5];
for buffer in buffers.iter_mut() {
rng::fill_bytes(buffer);
rng::fill_bytes(buffer).unwrap();
debug!("- {buffer:02x?}");
}
for i in 1 .. buffers.len() {
Expand Down

0 comments on commit cb1c221

Please sign in to comment.