diff mbox series

[1/3] rust: add userspace pointers

Message ID 20240124-alice-mm-v1-1-d1abcec83c44@google.com (mailing list archive)
State New
Headers show
Series Memory management patches needed by Rust Binder | expand

Commit Message

Alice Ryhl Jan. 24, 2024, 11:20 a.m. UTC
From: Wedson Almeida Filho <wedsonaf@gmail.com>

A pointer to an area in userspace memory, which can be either read-only
or read-write.

All methods on this struct are safe: invalid pointers return `EFAULT`.
Concurrent access, *including data races to/from userspace memory*, is
permitted, because fundamentally another userspace thread/process could
always be modifying memory at the same time (in the same way that
userspace Rust's `std::io` permits data races with the contents of
files on disk). In the presence of a race, the exact byte values
read/written are unspecified but the operation is well-defined.
Kernelspace code should validate its copy of data after completing a
read, and not expect that multiple reads of the same address will return
the same value.

These APIs are designed to make it difficult to accidentally write
TOCTOU bugs. Every time you read from a memory location, the pointer is
advanced by the length so that you cannot use that reader to read the
same memory location twice. Preventing double-fetches avoids TOCTOU
bugs. This is accomplished by taking `self` by value to prevent
obtaining multiple readers on a given `UserSlicePtr`, and the readers
only permitting forward reads. If double-fetching a memory location is
necessary for some reason, then that is done by creating multiple
readers to the same memory location.

Constructing a `UserSlicePtr` performs no checks on the provided
address and length, it can safely be constructed inside a kernel thread
with no current userspace process. Reads and writes wrap the kernel APIs
`copy_from_user` and `copy_to_user`, which check the memory map of the
current process and enforce that the address range is within the user
range (no additional calls to `access_ok` are needed).

This code is based on something that was originally written by Wedson on
the old rust branch. It was modified by Alice by removing the
`IoBufferReader` and `IoBufferWriter` traits, introducing the
`MAX_USER_OP_LEN` constant, and various changes to the comments and
documentation.

Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com>
Co-developed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
 rust/helpers.c          |  14 +++
 rust/kernel/lib.rs      |   1 +
 rust/kernel/user_ptr.rs | 222 ++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 237 insertions(+)

Comments

Valentin Obst Jan. 24, 2024, 11:12 p.m. UTC | #1
> +//! User pointers.
> +//!
> +//! C header: [`include/linux/uaccess.h`](../../../../include/linux/uaccess.h)
> +

nit: could this be using srctree-relative links?

> +/// The maximum length of a operation using `copy_[from|to]_user`.

nit: 'a' -> 'an'

> +///
> +/// If a usize is not greater than this constant, then casting it to `c_ulong`
> +/// is guaranteed to be lossless.

nit: could this be `usize` or [`usize`]. Maybe would also be clearer to
say "... a value of type [`usize`] is smaller than ..."

> +///
> +/// These APIs are designed to make it difficult to accidentally write TOCTOU
> +/// bugs. Every time you read from a memory location, the pointer is advanced by

Maybe makes sense to also introduce the abbreviation TOCTOU in the type
documentation when it is first used.

> +    /// Reads the entirety of the user slice.
> +    ///
> +    /// Returns `EFAULT` if the address does not currently point to
> +    /// mapped, readable memory.
> +    pub fn read_all(self) -> Result<Vec<u8>> {
> +        self.reader().read_all()
> +    }

If I understand it correctly, the function will return `EFAULT` if _any_
address in the interval `[self.0, self.0 + self.1)` does not point to
mapped, readable memory. Maybe the docs could be more explicit.

> +        // Since this is not a pointer to a valid object in our program,
> +        // we cannot use `add`, which has C-style rules for defined
> +        // behavior.
> +        self.0 = self.0.wrapping_add(len);

If I understand it correctly, you are using 'valid object' to refer to
an 'allocated object' [1] as this is what the `add` method's docs
refer to [2]. In that case it might be better to use the latter term as
it has a defined meaning. Also see [3] and [4] which are about making it
more precise.

[1]: https://doc.rust-lang.org/core/ptr/index.html#allocated-object
[2]: https://doc.rust-lang.org/core/primitive.pointer.html#method.add
[3]: https://github.com/rust-lang/rust/pull/116675
[4]: https://github.com/rust-lang/unsafe-code-guidelines/issues/465
Trevor Gross Feb. 1, 2024, 4:06 a.m. UTC | #2
On Wed, Jan 24, 2024 at 6:21 AM Alice Ryhl <aliceryhl@google.com> wrote:
> --- /dev/null
> +++ b/rust/kernel/user_ptr.rs
> @@ -0,0 +1,222 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +//! User pointers.
> +//!
> +//! C header: [`include/linux/uaccess.h`](../../../../include/linux/uaccess.h)
> +
> +// Comparison with MAX_USER_OP_LEN triggers this lint on platforms
> +// where `c_ulong == usize`.
> +#![allow(clippy::absurd_extreme_comparisons)]
> +
> +use crate::{bindings, error::code::*, error::Result};
> +use alloc::vec::Vec;
> +use core::ffi::{c_ulong, c_void};
> +
> +/// The maximum length of a operation using `copy_[from|to]_user`.
> +///
> +/// If a usize is not greater than this constant, then casting it to `c_ulong`
> +/// is guaranteed to be lossless.
> +const MAX_USER_OP_LEN: usize = c_ulong::MAX as usize;
> +
> +/// A pointer to an area in userspace memory, which can be either read-only or
> +/// read-write.
> +///
> +/// All methods on this struct are safe: invalid pointers return `EFAULT`.

Maybe

    ... attempting to read or write invalid pointers will return `EFAULT`.

> +/// Concurrent access, *including data races to/from userspace memory*, is
> +/// permitted, because fundamentally another userspace thread/process could
> +/// always be modifying memory at the same time (in the same way that userspace
> +/// Rust's [`std::io`] permits data races with the contents of files on disk).
> +/// In the presence of a race, the exact byte values read/written are
> +/// unspecified but the operation is well-defined. Kernelspace code should
> +/// validate its copy of data after completing a read, and not expect that
> +/// multiple reads of the same address will return the same value.
> +///
> +/// These APIs are designed to make it difficult to accidentally write TOCTOU
> +/// bugs. Every time you read from a memory location, the pointer is advanced by
> +/// the length so that you cannot use that reader to read the same memory
> +/// location twice. Preventing double-fetches avoids TOCTOU bugs. This is
> +/// accomplished by taking `self` by value to prevent obtaining multiple readers
> +/// on a given [`UserSlicePtr`], and the readers only permitting forward reads.
> +/// If double-fetching a memory location is necessary for some reason, then that
> +/// is done by creating multiple readers to the same memory location, e.g. using
> +/// [`clone_reader`].

Maybe something like

    Every time a memory location is read, the reader's position is advanced by
    the read length and the next read will start from there. This helps prevent
    accidentally reading the same location twice and causing a TOCTOU bug.

    Creating a [`UserSlicePtrReader`] and/or [`UserSlicePtrWriter`]
    consumes the `UserSlicePtr`, helping ensure that there aren't multiple
    readers or writers to the same location.

    If double fetching a memory location...

> +///
> +/// Constructing a [`UserSlicePtr`] performs no checks on the provided address
> +/// and length, it can safely be constructed inside a kernel thread with no
> +/// current userspace process. Reads and writes wrap the kernel APIs

Maybe some of this is better documented on `new` rather than the type?

> +/// `copy_from_user` and `copy_to_user`, which check the memory map of the
> +/// current process and enforce that the address range is within the user range
> +/// (no additional calls to `access_ok` are needed).
> +///
> +/// [`std::io`]: https://doc.rust-lang.org/std/io/index.html
> +/// [`clone_reader`]: UserSlicePtrReader::clone_reader
> +pub struct UserSlicePtr(*mut c_void, usize);

I think just `UserSlice` could work for the name here, since
`SlicePtr` is a bit redundant (slices automatically containing a
pointer). Also makes the Reader/Writer types a bit less wordy. Though
I understand wanting to make it discoverable for C users.

Is some sort of `Debug` implementation useful?

> +impl UserSlicePtr {
> +    /// Constructs a user slice from a raw pointer and a length in bytes.
> +    ///
> +    /// Callers must be careful to avoid time-of-check-time-of-use
> +    /// (TOCTOU) issues. The simplest way is to create a single instance of
> +    /// [`UserSlicePtr`] per user memory block as it reads each byte at
> +    /// most once.
> +    pub fn new(ptr: *mut c_void, length: usize) -> Self {
> +        UserSlicePtr(ptr, length)
> +    }
> +
> +    /// Reads the entirety of the user slice.
> +    ///
> +    /// Returns `EFAULT` if the address does not currently point to
> +    /// mapped, readable memory.
> +    pub fn read_all(self) -> Result<Vec<u8>> {
> +        self.reader().read_all()
> +    }

std::io uses the signature

    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> { ... }

Maybe this could be better here too, since it allows reusing the
vector without going through `read_raw`.

https://doc.rust-lang.org/std/io/trait.Read.html#method.read_to_end

> +    /// Constructs a [`UserSlicePtrReader`].
> +    pub fn reader(self) -> UserSlicePtrReader {
> +        UserSlicePtrReader(self.0, self.1)
> +    }

I wonder if this should be called `into_reader` to note that it is a
consuming method. Indifferent here, since there aren't any non-`self`
variants.

> +
> +    /// Constructs a [`UserSlicePtrWriter`].
> +    pub fn writer(self) -> UserSlicePtrWriter {
> +        UserSlicePtrWriter(self.0, self.1)
> +    }
> +
> +    /// Constructs both a [`UserSlicePtrReader`] and a [`UserSlicePtrWriter`].

Could you add a brief about what is or isn't allowed when you have a
reader and a writer to the same location?

> +    pub fn reader_writer(self) -> (UserSlicePtrReader, UserSlicePtrWriter) {
> +        (
> +            UserSlicePtrReader(self.0, self.1),
> +            UserSlicePtrWriter(self.0, self.1),
> +        )
> +    }
> +}
> +
> +/// A reader for [`UserSlicePtr`].
> +///
> +/// Used to incrementally read from the user slice.
> +pub struct UserSlicePtrReader(*mut c_void, usize);
> +
> +impl UserSlicePtrReader {
> +    /// Skip the provided number of bytes.
> +    ///
> +    /// Returns an error if skipping more than the length of the buffer.
> +    pub fn skip(&mut self, num_skip: usize) -> Result {
> +        // Update `self.1` first since that's the fallible one.
> +        self.1 = self.1.checked_sub(num_skip).ok_or(EFAULT)?;
> +        self.0 = self.0.wrapping_add(num_skip);

I think it would be better to change to named structs to make this more clear.

> +        Ok(())
> +    }
> +
> +    /// Create a reader that can access the same range of data.
> +    ///
> +    /// Reading from the clone does not advance the current reader.
> +    ///
> +    /// The caller should take care to not introduce TOCTOU issues.

Could you add an example of what should be avoided?

> +    pub fn clone_reader(&self) -> UserSlicePtrReader {
> +        UserSlicePtrReader(self.0, self.1)
> +    }
> +
> +    /// Returns the number of bytes left to be read from this.

Remove "from this" or change to "from this reader".

> +    ///
> +    /// Note that even reading less than this number of bytes may fail.> +    pub fn len(&self) -> usize {
> +        self.1
> +    }
> +
> +    /// Returns `true` if no data is available in the io buffer.
> +    pub fn is_empty(&self) -> bool {
> +        self.1 == 0
> +    }
> +
> +    /// Reads raw data from the user slice into a raw kernel buffer.
> +    ///
> +    /// Fails with `EFAULT` if the read encounters a page fault.

This is raised if the address is invalid right, not just page faults?
Or, are page faults just the only mode of indication that a pointer
isn't valid.

I know this is the same as copy_from_user, but I don't understand that
too well myself. I'm also a bit curious what happens if you pass a
kernel pointer to these methods.

> +    /// # Safety
> +    ///
> +    /// The `out` pointer must be valid for writing `len` bytes.
> +    pub unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> Result {

What is the motivation for taking raw pointers rather than a slice
here? In which case it could just be called `read`.

> +        if len > self.1 || len > MAX_USER_OP_LEN {
> +            return Err(EFAULT);
> +        }
> +        // SAFETY: The caller promises that `out` is valid for writing `len` bytes.
> +        let res = unsafe { bindings::copy_from_user(out.cast::<c_void>(), self.0, len as c_ulong) };

To me, it would be more clear to `c_ulong::try_from(len).map_err(|_|
EFAULT)?` rather than using MAX_USER_OP_LEN with an `as` cast, since
it makes it immediately clear that the conversion is ok (and is doing
that same comparison)

> +        if res != 0 {
> +            return Err(EFAULT);
> +        }
> +        // Since this is not a pointer to a valid object in our program,
> +        // we cannot use `add`, which has C-style rules for defined
> +        // behavior.
> +        self.0 = self.0.wrapping_add(len);
> +        self.1 -= len;
> +        Ok(())
> +    }
> +
> +    /// Reads all remaining data in the buffer into a vector.
> +    ///
> +    /// Fails with `EFAULT` if the read encounters a page fault.
> +    pub fn read_all(&mut self) -> Result<Vec<u8>> {

Same as the above note about read_to_end

> +        let len = self.len();
> +        let mut data = Vec::<u8>::try_with_capacity(len)?;
> +
> +        // SAFETY: The output buffer is valid for `len` bytes as we just allocated that much space.
> +        unsafe { self.read_raw(data.as_mut_ptr(), len)? };

If making the change above (possibly even if not), going through
https://doc.rust-lang.org/std/vec/struct.Vec.html#method.spare_capacity_mut
can be more clear about uninitialized data.

> +
> +        // SAFETY: Since the call to `read_raw` was successful, the first `len` bytes of the vector
> +        // have been initialized.
> +        unsafe { data.set_len(len) };
> +        Ok(data)
> +    }
> +}
> +
> +/// A writer for [`UserSlicePtr`].
> +///
> +/// Used to incrementally write into the user slice.
> +pub struct UserSlicePtrWriter(*mut c_void, usize);
> +
> +impl UserSlicePtrWriter {
> +    /// Returns the amount of space remaining in this buffer.
> +    ///
> +    /// Note that even writing less than this number of bytes may fail.
> +    pub fn len(&self) -> usize {
> +        self.1
> +    }
> +
> +    /// Returns `true` if no more data can be written to this buffer.
> +    pub fn is_empty(&self) -> bool {
> +        self.1 == 0
> +    }
> +
> +    /// Writes raw data to this user pointer from a raw kernel buffer.
> +    ///
> +    /// Fails with `EFAULT` if the write encounters a page fault.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The `data` pointer must be valid for reading `len` bytes.
> +    pub unsafe fn write_raw(&mut self, data: *const u8, len: usize) -> Result {

Same as for Reader regarding signature

> +        if len > self.1 || len > MAX_USER_OP_LEN {
> +            return Err(EFAULT);
> +        }
> +        let res = unsafe { bindings::copy_to_user(self.0, data.cast::<c_void>(), len as c_ulong) };

Same as for Reader regarding `as` casts.

> +        if res != 0 {
> +            return Err(EFAULT);
> +        }
> +        // Since this is not a pointer to a valid object in our program,
> +        // we cannot use `add`, which has C-style rules for defined
> +        // behavior.
> +        self.0 = self.0.wrapping_add(len);
> +        self.1 -= len;
> +        Ok(())
> +    }
> +
> +    /// Writes the provided slice to this user pointer.
> +    ///
> +    /// Fails with `EFAULT` if the write encounters a page fault.
> +    pub fn write_slice(&mut self, data: &[u8]) -> Result {

This could probably just be called `write`, which would be consistent
with std::io::Write.

> +        let len = data.len();
> +        let ptr = data.as_ptr();
> +        // SAFETY: The pointer originates from a reference to a slice of length
> +        // `len`, so the pointer is valid for reading `len` bytes.
> +        unsafe { self.write_raw(ptr, len) }
> +    }
> +}
>
> --
> 2.43.0.429.g432eaa2c6b-goog

The docs could use usage examples, but I am sure you are planning on
that already :)

- Trevor
Alice Ryhl Feb. 8, 2024, 12:20 p.m. UTC | #3
On Thu, Jan 25, 2024 at 12:13 AM Valentin Obst <kernel@valentinobst.de> wrote:
>
> > +//! User pointers.
> > +//!
> > +//! C header: [`include/linux/uaccess.h`](../../../../include/linux/uaccess.h)
> > +
>
> nit: could this be using srctree-relative links?
>
> > +/// The maximum length of a operation using `copy_[from|to]_user`.
>
> nit: 'a' -> 'an'
>
> > +///
> > +/// If a usize is not greater than this constant, then casting it to `c_ulong`
> > +/// is guaranteed to be lossless.
>
> nit: could this be `usize` or [`usize`]. Maybe would also be clearer to
> say "... a value of type [`usize`] is smaller than ..."
>
> > +///
> > +/// These APIs are designed to make it difficult to accidentally write TOCTOU
> > +/// bugs. Every time you read from a memory location, the pointer is advanced by
>
> Maybe makes sense to also introduce the abbreviation TOCTOU in the type
> documentation when it is first used.
>
> > +    /// Reads the entirety of the user slice.
> > +    ///
> > +    /// Returns `EFAULT` if the address does not currently point to
> > +    /// mapped, readable memory.
> > +    pub fn read_all(self) -> Result<Vec<u8>> {
> > +        self.reader().read_all()
> > +    }
>
> If I understand it correctly, the function will return `EFAULT` if _any_
> address in the interval `[self.0, self.0 + self.1)` does not point to
> mapped, readable memory. Maybe the docs could be more explicit.
>
> > +        // Since this is not a pointer to a valid object in our program,
> > +        // we cannot use `add`, which has C-style rules for defined
> > +        // behavior.
> > +        self.0 = self.0.wrapping_add(len);
>
> If I understand it correctly, you are using 'valid object' to refer to
> an 'allocated object' [1] as this is what the `add` method's docs
> refer to [2]. In that case it might be better to use the latter term as
> it has a defined meaning. Also see [3] and [4] which are about making it
> more precise.
>
> [1]: https://doc.rust-lang.org/core/ptr/index.html#allocated-object
> [2]: https://doc.rust-lang.org/core/primitive.pointer.html#method.add
> [3]: https://github.com/rust-lang/rust/pull/116675
> [4]: https://github.com/rust-lang/unsafe-code-guidelines/issues/465

Thanks. I'll include all of your suggestions in my next version.

Alice
Alice Ryhl Feb. 8, 2024, 12:53 p.m. UTC | #4
On Thu, Feb 1, 2024 at 5:06 AM Trevor Gross <tmgross@umich.edu> wrote:
>
> On Wed, Jan 24, 2024 at 6:21 AM Alice Ryhl <aliceryhl@google.com> wrote:
> > +/// A pointer to an area in userspace memory, which can be either read-only or
> > +/// read-write.
> > +///
> > +/// All methods on this struct are safe: invalid pointers return `EFAULT`.
>
> Maybe
>
>     ... attempting to read or write invalid pointers will return `EFAULT`.

Sure, that works.

> > +/// Concurrent access, *including data races to/from userspace memory*, is
> > +/// permitted, because fundamentally another userspace thread/process could
> > +/// always be modifying memory at the same time (in the same way that userspace
> > +/// Rust's [`std::io`] permits data races with the contents of files on disk).
> > +/// In the presence of a race, the exact byte values read/written are
> > +/// unspecified but the operation is well-defined. Kernelspace code should
> > +/// validate its copy of data after completing a read, and not expect that
> > +/// multiple reads of the same address will return the same value.
> > +///
> > +/// These APIs are designed to make it difficult to accidentally write TOCTOU
> > +/// bugs. Every time you read from a memory location, the pointer is advanced by
> > +/// the length so that you cannot use that reader to read the same memory
> > +/// location twice. Preventing double-fetches avoids TOCTOU bugs. This is
> > +/// accomplished by taking `self` by value to prevent obtaining multiple readers
> > +/// on a given [`UserSlicePtr`], and the readers only permitting forward reads.
> > +/// If double-fetching a memory location is necessary for some reason, then that
> > +/// is done by creating multiple readers to the same memory location, e.g. using
> > +/// [`clone_reader`].
>
> Maybe something like
>
>     Every time a memory location is read, the reader's position is advanced by
>     the read length and the next read will start from there. This helps prevent
>     accidentally reading the same location twice and causing a TOCTOU bug.
>
>     Creating a [`UserSlicePtrReader`] and/or [`UserSlicePtrWriter`]
>     consumes the `UserSlicePtr`, helping ensure that there aren't multiple
>     readers or writers to the same location.
>
>     If double fetching a memory location...

That makes sense to me. I'll update that.

> > +///
> > +/// Constructing a [`UserSlicePtr`] performs no checks on the provided address
> > +/// and length, it can safely be constructed inside a kernel thread with no
> > +/// current userspace process. Reads and writes wrap the kernel APIs
>
> Maybe some of this is better documented on `new` rather than the type?

I agree. I will move it.

> > +/// `copy_from_user` and `copy_to_user`, which check the memory map of the
> > +/// current process and enforce that the address range is within the user range
> > +/// (no additional calls to `access_ok` are needed).
> > +///
> > +/// [`std::io`]: https://doc.rust-lang.org/std/io/index.html
> > +/// [`clone_reader`]: UserSlicePtrReader::clone_reader
> > +pub struct UserSlicePtr(*mut c_void, usize);
>
> I think just `UserSlice` could work for the name here, since
> `SlicePtr` is a bit redundant (slices automatically containing a
> pointer). Also makes the Reader/Writer types a bit less wordy. Though
> I understand wanting to make it discoverable for C users.

Sure, renamed.

> Is some sort of `Debug` implementation useful?

Leaking pointer addresses in logs is frowned upon in the kernel, so I
don't think we should include that.

> > +    /// Reads the entirety of the user slice.
> > +    ///
> > +    /// Returns `EFAULT` if the address does not currently point to
> > +    /// mapped, readable memory.
> > +    pub fn read_all(self) -> Result<Vec<u8>> {
> > +        self.reader().read_all()
> > +    }
>
> std::io uses the signature
>
>     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> { ... }
>
> Maybe this could be better here too, since it allows reusing the
> vector without going through `read_raw`.
>
> https://doc.rust-lang.org/std/io/trait.Read.html#method.read_to_end

I updated the signature so that it appends to an existing vector
instead of creating a new one.

> > +    /// Constructs a [`UserSlicePtrReader`].
> > +    pub fn reader(self) -> UserSlicePtrReader {
> > +        UserSlicePtrReader(self.0, self.1)
> > +    }
>
> I wonder if this should be called `into_reader` to note that it is a
> consuming method. Indifferent here, since there aren't any non-`self`
> variants.

Hmm. I think the current name is good enough, since there aren't any
non-self methods, as you mention.

> > +
> > +    /// Constructs a [`UserSlicePtrWriter`].
> > +    pub fn writer(self) -> UserSlicePtrWriter {
> > +        UserSlicePtrWriter(self.0, self.1)
> > +    }
> > +
> > +    /// Constructs both a [`UserSlicePtrReader`] and a [`UserSlicePtrWriter`].
>
> Could you add a brief about what is or isn't allowed when you have a
> reader and a writer to the same location?

Ultimately, you can do whatever you want. But I'll add this:

/// Usually when this is used, you will first read the data, and then
/// overwrite it afterwards.

> > +    pub fn reader_writer(self) -> (UserSlicePtrReader, UserSlicePtrWriter) {
> > +        (
> > +            UserSlicePtrReader(self.0, self.1),
> > +            UserSlicePtrWriter(self.0, self.1),
> > +        )
> > +    }
> > +}
> > +
> > +/// A reader for [`UserSlicePtr`].
> > +///
> > +/// Used to incrementally read from the user slice.
> > +pub struct UserSlicePtrReader(*mut c_void, usize);
> > +
> > +impl UserSlicePtrReader {
> > +    /// Skip the provided number of bytes.
> > +    ///
> > +    /// Returns an error if skipping more than the length of the buffer.
> > +    pub fn skip(&mut self, num_skip: usize) -> Result {
> > +        // Update `self.1` first since that's the fallible one.
> > +        self.1 = self.1.checked_sub(num_skip).ok_or(EFAULT)?;
> > +        self.0 = self.0.wrapping_add(num_skip);
>
> I think it would be better to change to named structs to make this more clear.

Good idea. Changed to named fields.

> > +        Ok(())
> > +    }
> > +
> > +    /// Create a reader that can access the same range of data.
> > +    ///
> > +    /// Reading from the clone does not advance the current reader.
> > +    ///
> > +    /// The caller should take care to not introduce TOCTOU issues.
>
> Could you add an example of what should be avoided?
>
> > +    pub fn clone_reader(&self) -> UserSlicePtrReader {
> > +        UserSlicePtrReader(self.0, self.1)
> > +    }
> > +
> > +    /// Returns the number of bytes left to be read from this.
>
> Remove "from this" or change to "from this reader".

Done.

> > +    ///
> > +    /// Note that even reading less than this number of bytes may fail.> +    pub fn len(&self) -> usize {
> > +        self.1
> > +    }
> > +
> > +    /// Returns `true` if no data is available in the io buffer.
> > +    pub fn is_empty(&self) -> bool {
> > +        self.1 == 0
> > +    }
> > +
> > +    /// Reads raw data from the user slice into a raw kernel buffer.
> > +    ///
> > +    /// Fails with `EFAULT` if the read encounters a page fault.
>
> This is raised if the address is invalid right, not just page faults?
> Or, are page faults just the only mode of indication that a pointer
> isn't valid.
>
> I know this is the same as copy_from_user, but I don't understand that
> too well myself. I'm also a bit curious what happens if you pass a
> kernel pointer to these methods.

Basically, if the userspace process wouldn't be able to dereference
the pointer, then you get this error.

> > +    /// # Safety
> > +    ///
> > +    /// The `out` pointer must be valid for writing `len` bytes.
> > +    pub unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> Result {
>
> What is the motivation for taking raw pointers rather than a slice
> here? In which case it could just be called `read`.

The second patch will introduce a method called `read`, so we can't
use that name.

I don't think a slice gains that much compared to a raw pointer. It
would have to be an `&mut [MaybeUninit<u8>]` due to uninit memory, but
that doesn't actually allow the caller to use this method without
unsafe, since the caller would have to unsafely assert that the slice
has been initialized by this call themselves. Making this method
usable safely would require that we start using something along the
lines of the standard library's BorrowedBuf [1], which seems way
overkill to me.

[1]: https://doc.rust-lang.org/stable/std/io/struct.BorrowedBuf.html

> > +        if len > self.1 || len > MAX_USER_OP_LEN {
> > +            return Err(EFAULT);
> > +        }
> > +        // SAFETY: The caller promises that `out` is valid for writing `len` bytes.
> > +        let res = unsafe { bindings::copy_from_user(out.cast::<c_void>(), self.0, len as c_ulong) };
>
> To me, it would be more clear to `c_ulong::try_from(len).map_err(|_|
> EFAULT)?` rather than using MAX_USER_OP_LEN with an `as` cast, since
> it makes it immediately clear that the conversion is ok (and is doing
> that same comparison)

Thanks for the suggestion. I changed this.

> > +        let len = self.len();
> > +        let mut data = Vec::<u8>::try_with_capacity(len)?;
> > +
> > +        // SAFETY: The output buffer is valid for `len` bytes as we just allocated that much space.
> > +        unsafe { self.read_raw(data.as_mut_ptr(), len)? };
>
> If making the change above (possibly even if not), going through
> https://doc.rust-lang.org/std/vec/struct.Vec.html#method.spare_capacity_mut
> can be more clear about uninitialized data.
>
> > +
> > +        // SAFETY: Since the call to `read_raw` was successful, the first `len` bytes of the vector
> > +        // have been initialized.
> > +        unsafe { data.set_len(len) };
> > +        Ok(data)
> > +    }
> > +}
> > +
> > +/// A writer for [`UserSlicePtr`].
> > +///
> > +/// Used to incrementally write into the user slice.
> > +pub struct UserSlicePtrWriter(*mut c_void, usize);
> > +
> > +impl UserSlicePtrWriter {
> > +    /// Returns the amount of space remaining in this buffer.
> > +    ///
> > +    /// Note that even writing less than this number of bytes may fail.
> > +    pub fn len(&self) -> usize {
> > +        self.1
> > +    }
> > +
> > +    /// Returns `true` if no more data can be written to this buffer.
> > +    pub fn is_empty(&self) -> bool {
> > +        self.1 == 0
> > +    }
> > +
> > +    /// Writes raw data to this user pointer from a raw kernel buffer.
> > +    ///
> > +    /// Fails with `EFAULT` if the write encounters a page fault.
> > +    ///
> > +    /// # Safety
> > +    ///
> > +    /// The `data` pointer must be valid for reading `len` bytes.
> > +    pub unsafe fn write_raw(&mut self, data: *const u8, len: usize) -> Result {
>
> Same as for Reader regarding signature

I suppose we could have only `write_slice`. But if we're going to have
a read_raw, then having write_raw too makes sense to me.

Besides, a memcpy of uninit memory isn't UB by itself, so the raw
method would let you write uninit memory if you needed to.

> > +        if res != 0 {
> > +            return Err(EFAULT);
> > +        }
> > +        // Since this is not a pointer to a valid object in our program,
> > +        // we cannot use `add`, which has C-style rules for defined
> > +        // behavior.
> > +        self.0 = self.0.wrapping_add(len);
> > +        self.1 -= len;
> > +        Ok(())
> > +    }
> > +
> > +    /// Writes the provided slice to this user pointer.
> > +    ///
> > +    /// Fails with `EFAULT` if the write encounters a page fault.
> > +    pub fn write_slice(&mut self, data: &[u8]) -> Result {
>
> This could probably just be called `write`, which would be consistent
> with std::io::Write.

This would also name conflict with the second patch.

> The docs could use usage examples, but I am sure you are planning on
> that already :)

I'll add some.


Alice
Greg KH Feb. 8, 2024, 3:35 p.m. UTC | #5
On Thu, Feb 08, 2024 at 01:53:20PM +0100, Alice Ryhl wrote:
> > Is some sort of `Debug` implementation useful?
> 
> Leaking pointer addresses in logs is frowned upon in the kernel, so I
> don't think we should include that.

s/frowned upon/forbidden/ :)

Along those lines, you all are tieing in the "I want to print a pointer,
so hash it properly before I do so" logic from rust like we have in c,
right?  Ideally you'd use the same logic if at all possible.

If not, that probably needs to be done so that you don't accidentally
start leaking things.

thanks,

greg k-h
Alice Ryhl Feb. 8, 2024, 3:41 p.m. UTC | #6
On Thu, Feb 8, 2024 at 4:35 PM Greg Kroah-Hartman
<gregkh@linuxfoundation.org> wrote:
>
> On Thu, Feb 08, 2024 at 01:53:20PM +0100, Alice Ryhl wrote:
> > > Is some sort of `Debug` implementation useful?
> >
> > Leaking pointer addresses in logs is frowned upon in the kernel, so I
> > don't think we should include that.
>
> s/frowned upon/forbidden/ :)

:)

> Along those lines, you all are tieing in the "I want to print a pointer,
> so hash it properly before I do so" logic from rust like we have in c,
> right?  Ideally you'd use the same logic if at all possible.
>
> If not, that probably needs to be done so that you don't accidentally
> start leaking things.

I don't know what the status of this is. For anything I've added, I've
just made it entirely impossible to print addresses, hashed or not.

Alice
Greg KH Feb. 8, 2024, 3:59 p.m. UTC | #7
On Thu, Feb 08, 2024 at 04:41:52PM +0100, Alice Ryhl wrote:
> On Thu, Feb 8, 2024 at 4:35 PM Greg Kroah-Hartman
> > Along those lines, you all are tieing in the "I want to print a pointer,
> > so hash it properly before I do so" logic from rust like we have in c,
> > right?  Ideally you'd use the same logic if at all possible.
> >
> > If not, that probably needs to be done so that you don't accidentally
> > start leaking things.
> 
> I don't know what the status of this is. For anything I've added, I've
> just made it entirely impossible to print addresses, hashed or not.

Even better, thanks!
Kees Cook Feb. 10, 2024, 6:20 a.m. UTC | #8
On February 8, 2024 7:41:52 AM PST, Alice Ryhl <aliceryhl@google.com> wrote:
>On Thu, Feb 8, 2024 at 4:35 PM Greg Kroah-Hartman
><gregkh@linuxfoundation.org> wrote:
>>
>> On Thu, Feb 08, 2024 at 01:53:20PM +0100, Alice Ryhl wrote:
>> > > Is some sort of `Debug` implementation useful?
>> >
>> > Leaking pointer addresses in logs is frowned upon in the kernel, so I
>> > don't think we should include that.
>>
>> s/frowned upon/forbidden/ :)
>
>:)
>
>> Along those lines, you all are tieing in the "I want to print a pointer,
>> so hash it properly before I do so" logic from rust like we have in c,
>> right?  Ideally you'd use the same logic if at all possible.
>>
>> If not, that probably needs to be done so that you don't accidentally
>> start leaking things.
>
>I don't know what the status of this is. For anything I've added, I've
>just made it entirely impossible to print addresses, hashed or not.

Thank you! That is certainly the preferred[1] approach. :)

-Kees

[1] https://www.kernel.org/doc/html/next/process/deprecated.html#p-format-specifier
Trevor Gross Feb. 10, 2024, 7:06 a.m. UTC | #9
On Thu, Feb 8, 2024 at 6:53 AM Alice Ryhl <aliceryhl@google.com> wrote:
> Leaking pointer addresses in logs is frowned upon in the kernel, so I
> don't think we should include that.

Sounds like the very correct decision from what Greg and Kees said. If
we add an impl in the future (to be able to `#[derive(Debug)]` on
anything containing this type) it could just print
`0x****************`.
David Laight Feb. 10, 2024, 2:14 p.m. UTC | #10
...
> > Maybe something like
> >
> >     Every time a memory location is read, the reader's position is advanced by
> >     the read length and the next read will start from there. This helps prevent
> >     accidentally reading the same location twice and causing a TOCTOU bug.

WTF TOCTOU? I'm guessing it is reading things twice and getting
different answers.

That really doesn't match how copying from userspace is used is many places.
Sometimes you really do want to be using offsets and lengths.
For instance the user buffer might contain offsets of items further
down the buffer.
There is also the code (eg ioctl) that does a read-modify-write
on a buffer.


There is also this bit:

> > +    /// Reads the entirety of the user slice.
> > +    ///
> > +    /// Returns `EFAULT` if the address does not currently point to
> > +    /// mapped, readable memory.
> > +    pub fn read_all(self) -> Result<Vec<u8>> {
> > +        self.reader().read_all()
> > +    }
>
> If I understand it correctly, the function will return `EFAULT` if _any_
> address in the interval `[self.0, self.0 + self.1)` does not point to
> mapped, readable memory. Maybe the docs could be more explicit.

That isn't (and can't be) how it works.
access_ok() checks that the buffer isn't in kernel space.
The copy is then done until it actually faults on an invalid address.
In that case the destination buffer has been updated to the point
of failure.

You can't do a check before the copy because another thread can
change the mapping (it would also be horribly expensive).

	David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK
Registration No: 1397386 (Wales)
Alice Ryhl Feb. 12, 2024, 9:30 a.m. UTC | #11
On Sat, Feb 10, 2024 at 3:15 PM David Laight <David.Laight@aculab.com> wrote:
>
> ...
> > > Maybe something like
> > >
> > >     Every time a memory location is read, the reader's position is advanced by
> > >     the read length and the next read will start from there. This helps prevent
> > >     accidentally reading the same location twice and causing a TOCTOU bug.
>
> WTF TOCTOU? I'm guessing it is reading things twice and getting
> different answers.

Yes. In v2 of this patchset [1], I expanded TOCTOU to "time-of-check
to time-of-use" at the first use to reduce this confusion.

> That really doesn't match how copying from userspace is used is many places.
> Sometimes you really do want to be using offsets and lengths.
> For instance the user buffer might contain offsets of items further
> down the buffer.

For this use-case, you can call UserSlice::new multiple times, or use
clone_reader. This use-case does appear sometimes in Rust Binder and
is supported, but I didn't find it to be the most common use-case.

> There is also the code (eg ioctl) that does a read-modify-write
> on a buffer.

The read-modify-write use-case is quite common in Rust Binder and is
supported by the API provided by this patchset. When you call
reader_writer, you get a separate reader and writer. Then, you first
use the reader to read the data. Then you modify it. Then you use the
writer to write it back.

> > > +    /// Reads the entirety of the user slice.
> > > +    ///
> > > +    /// Returns `EFAULT` if the address does not currently point to
> > > +    /// mapped, readable memory.
> > > +    pub fn read_all(self) -> Result<Vec<u8>> {
> > > +        self.reader().read_all()
> > > +    }
> >
> > If I understand it correctly, the function will return `EFAULT` if _any_
> > address in the interval `[self.0, self.0 + self.1)` does not point to
> > mapped, readable memory. Maybe the docs could be more explicit.
>
> That isn't (and can't be) how it works.
> access_ok() checks that the buffer isn't in kernel space.
> The copy is then done until it actually faults on an invalid address.
> In that case the destination buffer has been updated to the point
> of failure.
>
> You can't do a check before the copy because another thread can
> change the mapping (it would also be horribly expensive).

This was reworded in v2 [1]:

/// Fails with `EFAULT` if the read encounters a page fault.

But ultimately, the real condition here is just that it returns EFAULT
if copy_from_user fails. I'm happy to reword further.

Alice

[1]: https://lore.kernel.org/all/20240208-alice-mm-v2-1-d821250204a6@google.com/
diff mbox series

Patch

diff --git a/rust/helpers.c b/rust/helpers.c
index 70e59efd92bc..312b6fcb49d5 100644
--- a/rust/helpers.c
+++ b/rust/helpers.c
@@ -38,6 +38,20 @@  __noreturn void rust_helper_BUG(void)
 }
 EXPORT_SYMBOL_GPL(rust_helper_BUG);
 
+unsigned long rust_helper_copy_from_user(void *to, const void __user *from,
+					 unsigned long n)
+{
+	return copy_from_user(to, from, n);
+}
+EXPORT_SYMBOL_GPL(rust_helper_copy_from_user);
+
+unsigned long rust_helper_copy_to_user(void __user *to, const void *from,
+				       unsigned long n)
+{
+	return copy_to_user(to, from, n);
+}
+EXPORT_SYMBOL_GPL(rust_helper_copy_to_user);
+
 void rust_helper_mutex_lock(struct mutex *lock)
 {
 	mutex_lock(lock);
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 7ac39874aeac..041233305fda 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -50,6 +50,7 @@ 
 pub mod sync;
 pub mod task;
 pub mod types;
+pub mod user_ptr;
 pub mod workqueue;
 
 #[doc(hidden)]
diff --git a/rust/kernel/user_ptr.rs b/rust/kernel/user_ptr.rs
new file mode 100644
index 000000000000..00aa26aa6a83
--- /dev/null
+++ b/rust/kernel/user_ptr.rs
@@ -0,0 +1,222 @@ 
+// SPDX-License-Identifier: GPL-2.0
+
+//! User pointers.
+//!
+//! C header: [`include/linux/uaccess.h`](../../../../include/linux/uaccess.h)
+
+// Comparison with MAX_USER_OP_LEN triggers this lint on platforms
+// where `c_ulong == usize`.
+#![allow(clippy::absurd_extreme_comparisons)]
+
+use crate::{bindings, error::code::*, error::Result};
+use alloc::vec::Vec;
+use core::ffi::{c_ulong, c_void};
+
+/// The maximum length of a operation using `copy_[from|to]_user`.
+///
+/// If a usize is not greater than this constant, then casting it to `c_ulong`
+/// is guaranteed to be lossless.
+const MAX_USER_OP_LEN: usize = c_ulong::MAX as usize;
+
+/// A pointer to an area in userspace memory, which can be either read-only or
+/// read-write.
+///
+/// All methods on this struct are safe: invalid pointers return `EFAULT`.
+/// Concurrent access, *including data races to/from userspace memory*, is
+/// permitted, because fundamentally another userspace thread/process could
+/// always be modifying memory at the same time (in the same way that userspace
+/// Rust's [`std::io`] permits data races with the contents of files on disk).
+/// In the presence of a race, the exact byte values read/written are
+/// unspecified but the operation is well-defined. Kernelspace code should
+/// validate its copy of data after completing a read, and not expect that
+/// multiple reads of the same address will return the same value.
+///
+/// These APIs are designed to make it difficult to accidentally write TOCTOU
+/// bugs. Every time you read from a memory location, the pointer is advanced by
+/// the length so that you cannot use that reader to read the same memory
+/// location twice. Preventing double-fetches avoids TOCTOU bugs. This is
+/// accomplished by taking `self` by value to prevent obtaining multiple readers
+/// on a given [`UserSlicePtr`], and the readers only permitting forward reads.
+/// If double-fetching a memory location is necessary for some reason, then that
+/// is done by creating multiple readers to the same memory location, e.g. using
+/// [`clone_reader`].
+///
+/// Constructing a [`UserSlicePtr`] performs no checks on the provided address
+/// and length, it can safely be constructed inside a kernel thread with no
+/// current userspace process. Reads and writes wrap the kernel APIs
+/// `copy_from_user` and `copy_to_user`, which check the memory map of the
+/// current process and enforce that the address range is within the user range
+/// (no additional calls to `access_ok` are needed).
+///
+/// [`std::io`]: https://doc.rust-lang.org/std/io/index.html
+/// [`clone_reader`]: UserSlicePtrReader::clone_reader
+pub struct UserSlicePtr(*mut c_void, usize);
+
+impl UserSlicePtr {
+    /// Constructs a user slice from a raw pointer and a length in bytes.
+    ///
+    /// Callers must be careful to avoid time-of-check-time-of-use
+    /// (TOCTOU) issues. The simplest way is to create a single instance of
+    /// [`UserSlicePtr`] per user memory block as it reads each byte at
+    /// most once.
+    pub fn new(ptr: *mut c_void, length: usize) -> Self {
+        UserSlicePtr(ptr, length)
+    }
+
+    /// Reads the entirety of the user slice.
+    ///
+    /// Returns `EFAULT` if the address does not currently point to
+    /// mapped, readable memory.
+    pub fn read_all(self) -> Result<Vec<u8>> {
+        self.reader().read_all()
+    }
+
+    /// Constructs a [`UserSlicePtrReader`].
+    pub fn reader(self) -> UserSlicePtrReader {
+        UserSlicePtrReader(self.0, self.1)
+    }
+
+    /// Constructs a [`UserSlicePtrWriter`].
+    pub fn writer(self) -> UserSlicePtrWriter {
+        UserSlicePtrWriter(self.0, self.1)
+    }
+
+    /// Constructs both a [`UserSlicePtrReader`] and a [`UserSlicePtrWriter`].
+    pub fn reader_writer(self) -> (UserSlicePtrReader, UserSlicePtrWriter) {
+        (
+            UserSlicePtrReader(self.0, self.1),
+            UserSlicePtrWriter(self.0, self.1),
+        )
+    }
+}
+
+/// A reader for [`UserSlicePtr`].
+///
+/// Used to incrementally read from the user slice.
+pub struct UserSlicePtrReader(*mut c_void, usize);
+
+impl UserSlicePtrReader {
+    /// Skip the provided number of bytes.
+    ///
+    /// Returns an error if skipping more than the length of the buffer.
+    pub fn skip(&mut self, num_skip: usize) -> Result {
+        // Update `self.1` first since that's the fallible one.
+        self.1 = self.1.checked_sub(num_skip).ok_or(EFAULT)?;
+        self.0 = self.0.wrapping_add(num_skip);
+        Ok(())
+    }
+
+    /// Create a reader that can access the same range of data.
+    ///
+    /// Reading from the clone does not advance the current reader.
+    ///
+    /// The caller should take care to not introduce TOCTOU issues.
+    pub fn clone_reader(&self) -> UserSlicePtrReader {
+        UserSlicePtrReader(self.0, self.1)
+    }
+
+    /// Returns the number of bytes left to be read from this.
+    ///
+    /// Note that even reading less than this number of bytes may fail.
+    pub fn len(&self) -> usize {
+        self.1
+    }
+
+    /// Returns `true` if no data is available in the io buffer.
+    pub fn is_empty(&self) -> bool {
+        self.1 == 0
+    }
+
+    /// Reads raw data from the user slice into a raw kernel buffer.
+    ///
+    /// Fails with `EFAULT` if the read encounters a page fault.
+    ///
+    /// # Safety
+    ///
+    /// The `out` pointer must be valid for writing `len` bytes.
+    pub unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> Result {
+        if len > self.1 || len > MAX_USER_OP_LEN {
+            return Err(EFAULT);
+        }
+        // SAFETY: The caller promises that `out` is valid for writing `len` bytes.
+        let res = unsafe { bindings::copy_from_user(out.cast::<c_void>(), self.0, len as c_ulong) };
+        if res != 0 {
+            return Err(EFAULT);
+        }
+        // Since this is not a pointer to a valid object in our program,
+        // we cannot use `add`, which has C-style rules for defined
+        // behavior.
+        self.0 = self.0.wrapping_add(len);
+        self.1 -= len;
+        Ok(())
+    }
+
+    /// Reads all remaining data in the buffer into a vector.
+    ///
+    /// Fails with `EFAULT` if the read encounters a page fault.
+    pub fn read_all(&mut self) -> Result<Vec<u8>> {
+        let len = self.len();
+        let mut data = Vec::<u8>::try_with_capacity(len)?;
+
+        // SAFETY: The output buffer is valid for `len` bytes as we just allocated that much space.
+        unsafe { self.read_raw(data.as_mut_ptr(), len)? };
+
+        // SAFETY: Since the call to `read_raw` was successful, the first `len` bytes of the vector
+        // have been initialized.
+        unsafe { data.set_len(len) };
+        Ok(data)
+    }
+}
+
+/// A writer for [`UserSlicePtr`].
+///
+/// Used to incrementally write into the user slice.
+pub struct UserSlicePtrWriter(*mut c_void, usize);
+
+impl UserSlicePtrWriter {
+    /// Returns the amount of space remaining in this buffer.
+    ///
+    /// Note that even writing less than this number of bytes may fail.
+    pub fn len(&self) -> usize {
+        self.1
+    }
+
+    /// Returns `true` if no more data can be written to this buffer.
+    pub fn is_empty(&self) -> bool {
+        self.1 == 0
+    }
+
+    /// Writes raw data to this user pointer from a raw kernel buffer.
+    ///
+    /// Fails with `EFAULT` if the write encounters a page fault.
+    ///
+    /// # Safety
+    ///
+    /// The `data` pointer must be valid for reading `len` bytes.
+    pub unsafe fn write_raw(&mut self, data: *const u8, len: usize) -> Result {
+        if len > self.1 || len > MAX_USER_OP_LEN {
+            return Err(EFAULT);
+        }
+        let res = unsafe { bindings::copy_to_user(self.0, data.cast::<c_void>(), len as c_ulong) };
+        if res != 0 {
+            return Err(EFAULT);
+        }
+        // Since this is not a pointer to a valid object in our program,
+        // we cannot use `add`, which has C-style rules for defined
+        // behavior.
+        self.0 = self.0.wrapping_add(len);
+        self.1 -= len;
+        Ok(())
+    }
+
+    /// Writes the provided slice to this user pointer.
+    ///
+    /// Fails with `EFAULT` if the write encounters a page fault.
+    pub fn write_slice(&mut self, data: &[u8]) -> Result {
+        let len = data.len();
+        let ptr = data.as_ptr();
+        // SAFETY: The pointer originates from a reference to a slice of length
+        // `len`, so the pointer is valid for reading `len` bytes.
+        unsafe { self.write_raw(ptr, len) }
+    }
+}