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

kernel/vtpm: fix potential UB when accessing guest buffer #603

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
14 changes: 14 additions & 0 deletions kernel/src/mm/guestmem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,20 @@ impl<T: Copy> GuestPtr<T> {
unsafe { do_movsb(&buf, self.ptr) }
}

/// # Safety
///
/// The caller must verify not to read arbitrary memory, as this function
/// doesn't make any checks in that regard.
///
/// # Returns
///
/// Returns an error if the specified address is not mapped.
#[inline]
pub unsafe fn read_ref(&self, buf: &mut T) -> Result<(), SvsmError> {
// SAFETY: demanded to the caller
unsafe { do_movsb(self.ptr, buf) }
}

/// # Safety
///
/// The caller must verify not to corrupt arbitrary memory, as this function
Expand Down
32 changes: 27 additions & 5 deletions kernel/src/protocols/vtpm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
extern crate alloc;

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

use alloc::vec::Vec;
use alloc::{vec, vec::Vec};

use crate::{
address::{Address, PhysAddr},
Expand Down Expand Up @@ -239,10 +239,32 @@ 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's use Vec to avoid consuming too much stack.
let mut buffer: Vec<u8> = vec![0; PAGE_SIZE];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to avoid having to allocate an entire page for every request. Is there some header in the payload that indicates how big the request is? If so, you could read that header into a stack local (which should be small), allocate your buffer based on how big the header indicates the data to be, then copy the stack local into the buffer and use read_ref to read the remainder of the command block into the buffer.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking in the SVSM specification, it actually does not say anywhere that the buffer must be PAGE_SIZE, so I think you are right. Although the Linux driver for now always passes a large PAGE_SIZE buffer since it's used also for the response, so in practice it should be the same, but I see your point, I'll try it!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should consider using let mut uninit_buffer: Box<MaybeUninit<[u8]>> = Box::new_uninit_slice(PAGE_SIZE) and then you can avoid having to zero-initialize the contents that you are about to write over (and you can also avoid the intermediate Vec representation). This would require GuestPtr::read_ref() to become GuestPtr::read_ptr() (because creating a reference to uninitialized data is UB but creating a pointer to it is not), and after the copy is done, you could use let mut buffer: &[u8] = unsafe { uninit_buffer.assume_init() } to make your buffer safely usable once the copy initialization is complete.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cool, thanks for this, I like it, I'll try!

That said, I just discovered that during the path from this code to the TCG TPM C code, we allocate/copy the buffer several times:

I think the second case maybe we cannot avoid, since the C code seems to expect 2 different buffers for input and output, but maybe, since we have to copy them from/to the guest anyway, we could pass 2 buffers from the beginning and avoid these allocations/copies.

I'll try to see if we can refactor a bit.

let buf_slice: &mut [u8; PAGE_SIZE] = buffer
.as_mut_slice()
.try_into()
.expect("Failed to initialize vTPM buffer");

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.
unsafe { buf_ptr.read_ref(buf_slice)? };

let response_size = tpm_send_command_request(buf_slice)?;

// 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_ref(buf_slice)? };

response_size
}
};

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