Skip to content

Commit

Permalink
Using NSM_REQUEST_MAX_SIZE to initialize buf capacity, added test to …
Browse files Browse the repository at this point in the history
…ensure there's no panic
  • Loading branch information
Tanner Gill committed Oct 14, 2024
1 parent 1904c84 commit 91426c9
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions src/driver/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,9 @@ struct NsmMessage<'a> {

/// Encode an NSM `Request` value into a vector.
/// *Argument 1 (input)*: The NSM request.
/// *Returns*: The vector containing the CBOR encoding.
fn nsm_encode_request_to_cbor(request: Request) -> Vec<u8> {
let mut buf = Vec::with_capacity(512);
ciborium::into_writer(&request, &mut buf).unwrap();
buf
/// *Argument 2 (input)*: The buffer that will have the CBOR written into it.
fn nsm_encode_request_to_cbor(request: Request, buf: &mut Vec<u8>) {
ciborium::into_writer(&request, buf).expect("buf's Writer returned an unexpected error");
}

/// Decode an NSM `Response` value from a raw memory buffer.
Expand Down Expand Up @@ -87,7 +85,8 @@ fn nsm_ioctl(fd: i32, message: &mut NsmMessage) -> Option<Errno> {
/// *Argument 2 (input)*: The NSM request.
/// *Returns*: The corresponding NSM response from the driver.
pub fn nsm_process_request(fd: i32, request: Request) -> Response {
let cbor_request = nsm_encode_request_to_cbor(request);
let mut cbor_request = Vec::with_capacity(NSM_REQUEST_MAX_SIZE);
nsm_encode_request_to_cbor(request, &mut cbor_request);

// Check if the request is too large
if cbor_request.len() > NSM_REQUEST_MAX_SIZE {
Expand Down Expand Up @@ -138,3 +137,21 @@ pub fn nsm_exit(fd: i32) {
Err(e) => error!("File of descriptor {} failed to close: {}", fd, e),
}
}

#[cfg(test)]
mod test {
use super::{Request, NSM_REQUEST_MAX_SIZE};
#[test]
fn test_nsm_encode_request_to_cbor_exceed_max_size_without_panic() {
let request = Request::ExtendPCR {
index: 0,
data: vec![0u8; NSM_REQUEST_MAX_SIZE],
};

let mut buf = Vec::with_capacity(NSM_REQUEST_MAX_SIZE);
super::nsm_encode_request_to_cbor(request, &mut buf);

// Ensure the buffer increased its capacity without panicking
assert!(buf.len() > NSM_REQUEST_MAX_SIZE);
}
}

0 comments on commit 91426c9

Please sign in to comment.