Skip to content

Commit

Permalink
kernel/vtpm: fix potential UB when accessing guest buffer
Browse files Browse the repository at this point in the history
Creating a mutable reference to the guest buffer, could have been an UB
because the guest could potentially modify it.

So, let's copy the guest buffer to an internal one and then copy it back
to give the result to the guest.

Signed-off-by: Stefano Garzarella <sgarzare@redhat.com>
  • Loading branch information
stefano-garzarella committed Feb 20, 2025
1 parent 035bb52 commit 7b5bcdd
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions kernel/src/protocols/vtpm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
extern crate alloc;

use core::{mem::size_of, slice::from_raw_parts_mut};
use core::mem::size_of;

use alloc::vec::Vec;

Expand Down Expand Up @@ -239,10 +239,25 @@ fn vtpm_command_request(params: &RequestParams) -> Result<(), SvsmReqError> {
return Err(SvsmReqError::unsupported_call());
}

let buffer = unsafe { from_raw_parts_mut(vaddr.as_mut_ptr::<u8>(), PAGE_SIZE) };

let response_size = match cmd {
TpmPlatformCommand::SendCommand => tpm_send_command_request(buffer)?,
TpmPlatformCommand::SendCommand => {
let buf_ptr = GuestPtr::<[u8; PAGE_SIZE]>::new(vaddr);

// SAFETY: `buf_ptr` is initialized with `vaddr` which points to
// a valid region just mapped, and its size is PAGE_SIZE.
// Since we need a mutable buffer in the next calls, to avoid UB,
// we copy the guest buffer to an internal one and then copy it back
// to give the result to the guest.
let mut buffer = unsafe { buf_ptr.read()? };

let response_size = tpm_send_command_request(&mut buffer)?;

// SAFETY: `buf_ptr` is initialized with `vaddr` which points to
// a valid region just mapped, and its size is PAGE_SIZE.
unsafe { buf_ptr.write(buffer)? };

response_size
}
};

// SAFETY: vaddr points to a new mapped region.
Expand Down

0 comments on commit 7b5bcdd

Please sign in to comment.