uaccess: rust: use newtype for user pointers
Subsystems (2)
Alice Ryhl
reviewerPATCH v2 1/1 uaccess: rust: use newtype for user pointers
In C code we use sparse with the __user annotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.
The UserPtr type is not marked with #[derive(Debug)], which means that it's not possible to print values of this type. This avoids ASLR leakage.
The type is added to the prelude as it is a fairly fundamental type similar to c_int. The wrapping_add() method is renamed to wrapping_byte_add() for consistency with the method name found on raw pointers.
---
This is based on top of the strncpy_from_user for Rust patch.
---
Changes in v2:
- Change usize to raw pointer.
- Make field private.
- Rename wrapping_add to wrapping_byte_add.
- Add to prelude.
- Rebase on v4 of strncpy_from_user
- Link to v1: https://lore.kernel.org/r/[email protected]
--- rust/kernel/prelude.rs | 2 ++ rust/kernel/uaccess.rs | 68 +++++++++++++++++++++++++++++++++------- samples/rust/rust_misc_device.rs | 2 ++ 3 files changed, 60 insertions(+), 12 deletions(-)
rust/kernel/prelude.rs +2 -0
@@ -41,3 +41,5 @@pub use super ::init::InPlaceInit ;pub use super ::current; + +pub use super ::uaccess::UserPtr ;
rust/kernel/uaccess.rs +56 -12
128 lines not on this page · raw message
samples/rust/rust_misc_device.rs +2 -0
@@ -176,6 +176,8 @@ fn open(_file: &File, misc: &MiscDeviceRegistration<Self>) -> Result<Pin<KBox<Sefn ioctl (me:Pin <&RustMiscDevice >, _file: &File , cmd:u32 , arg:usize ) ->Result <isize > {dev_info! (me.dev,"IOCTLing Rust Misc Device Sample\n" ); +// Treat the ioctl argument as a user pointer. +let arg =UserPtr ::from_addr (arg);let size =_IOC_SIZE (cmd);match cmd {
---
base-commit: f34da179a4517854b2ffbe4bce8c3405bd9be04e
change-id: 20250506-userptr-newtype-2f060985c33b
prerequisite-change-id: 20250424-strncpy-from-user-1f2d06b0cdde:v4
prerequisite-patch-id: d35c479ddb84bacc541dbb226c7911e5a22cad7e
prerequisite-patch-id: e0c345945dabfa18e9ca11f7fe11f8178d071285
Best regards,
Signature · 1 line
Alice Ryhl <[email protected]>
Quoted 9 lines · Alice Ryhl
In C code we use sparse with the
__userannotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.The UserPtr type is not marked with #[derive(Debug)], which means that it's not possible to print values of this type. This avoids ASLR leakage.
Quoted 6 lines
The type is added to the prelude as it is a fairly fundamental type similar to
c_int. Thewrapping_add()method is renamed towrapping_byte_add()for consistency with the method name found on raw pointers.Signed-off-by Alice Ryhl <[email protected]>
Nice!
Quoted 9 lines · Alice Ryhl
In C code we use sparse with the
__userannotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.The UserPtr type is not marked with #[derive(Debug)], which means that it's not possible to print values of this type. This avoids ASLR leakage.
Quoted 6 lines
The type is added to the prelude as it is a fairly fundamental type similar to
c_int. Thewrapping_add()method is renamed towrapping_byte_add()for consistency with the method name found on raw pointers.Signed-off-by Alice Ryhl <[email protected]>
A question below:
Quoted 60 lines
---
This is based on top of thestrncpy_from_userfor Rust patch.
---
Changes in v2:
- Change usize to raw pointer.
- Make field private.
- Renamewrapping_addtowrapping_byte_add.
- Add to prelude.
- Rebase on v4 ofstrncpy_from_user
- Link to v1: https://lore.kernel.org/r/[email protected]--- rust/kernel/prelude.rs | 2 ++ rust/kernel/uaccess.rs | 68 +++++++++++++++++++++++++++++++++------- samples/rust/rust_misc_device.rs | 2 ++ 3 files changed, 60 insertions(+), 12 deletions(-)rust/kernel/prelude.rs +2
-0@@ -41,3 +41,5 @@pub use super ::init::InPlaceInit ;pub use super ::current; + +pub use super ::uaccess::UserPtr ;rust/kernel/uaccess.rs +24
-2@@ -14,8 +14,48 @@ };use core::mem::{size_of,MaybeUninit }; -/// The type used for userspace addresses. -pub type UserPtr =usize ; +/// A pointer into userspace. +/// +/// This is the Rust equivalent to C pointers tagged with `__user`. +#[repr(transparent)] +#[derive( Copy , Clone )] +pub struct UserPtr (*mut c_void ); + +impl UserPtr { +/// Create a `UserPtr` from an integer representing the userspace address. +pub fn from_addr (addr:usize ) ->Self { +Self (addras *mut c_void ) + } + +/// Create a `UserPtr` from a pointer representing the userspace address. +pub fn from_ptr (addr: *mut c_void ) ->Self { +Self (addr) + } + +/// Cast this userspace pointer to a raw const void pointer. +/// +/// It is up to the caller to use the returned pointer correctly. +#[inline] +pub fn as_const_ptr (self) -> *const c_void { + self.0
rust/kernel/uaccess.rs line 50
Quoted 10 lines
rust/kernel/uaccess.rs +10
-0+ } + +/// Cast this userspace pointer to a raw mutable void pointer. +/// +/// It is up to the caller to use the returned pointer correctly. +#[inline] +pub fn as_mut_ptr (self) -> *mut c_void { + self.0 + } +
why are these two inline but the rest not?
Regards,
Boqun
Quoted 9 lines
rust/kernel/uaccess.rs +8
-0+/// Increment this user pointer by `add` bytes. +/// +/// This addition is wrapping, so wrapping around the address space does not result in a panic +/// even if `CONFIG_RUST_OVERFLOW_CHECKS` is enabled. +pub fn wrapping_byte_add (self, add:usize ) ->UserPtr { +UserPtr (self.0 .wrapping_add (add)) + } +}
[...]
Alice Ryhl
reviewerQuoted 86 lines · Boqun Feng
Quoted 9 lines · Alice Ryhl
In C code we use sparse with the
__userannotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.The UserPtr type is not marked with #[derive(Debug)], which means that it's not possible to print values of this type. This avoids ASLR leakage.
Quoted 6 lines
The type is added to the prelude as it is a fairly fundamental type similar to
c_int. Thewrapping_add()method is renamed towrapping_byte_add()for consistency with the method name found on raw pointers.Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Boqun Feng <[email protected]>A question below:
Quoted 64 lines
---
This is based on top of thestrncpy_from_userfor Rust patch.
---
Changes in v2:
- Change usize to raw pointer.
- Make field private.
- Renamewrapping_addtowrapping_byte_add.
- Add to prelude.
- Rebase on v4 ofstrncpy_from_user
- Link to v1: https://lore.kernel.org/r/[email protected]--- rust/kernel/prelude.rs | 2 ++ rust/kernel/uaccess.rs | 68 +++++++++++++++++++++++++++++++++------- samples/rust/rust_misc_device.rs | 2 ++ 3 files changed, 60 insertions(+), 12 deletions(-)rust/kernel/prelude.rs +2
-0@@ -41,3 +41,5 @@pub use super ::init::InPlaceInit ;pub use super ::current; + +pub use super ::uaccess::UserPtr ;rust/kernel/uaccess.rs +28
-2@@ -14,8 +14,48 @@ };use core::mem::{size_of,MaybeUninit }; -/// The type used for userspace addresses. -pub type UserPtr =usize ; +/// A pointer into userspace. +/// +/// This is the Rust equivalent to C pointers tagged with `__user`. +#[repr(transparent)] +#[derive( Copy , Clone )] +pub struct UserPtr (*mut c_void ); + +impl UserPtr { +/// Create a `UserPtr` from an integer representing the userspace address. +pub fn from_addr (addr:usize ) ->Self { +Self (addras *mut c_void ) + } + +/// Create a `UserPtr` from a pointer representing the userspace address. +pub fn from_ptr (addr: *mut c_void ) ->Self { +Self (addr) + } + +/// Cast this userspace pointer to a raw const void pointer. +/// +/// It is up to the caller to use the returned pointer correctly. +#[inline] +pub fn as_const_ptr (self) -> *const c_void { + self.0 + } + +/// Cast this userspace pointer to a raw mutable void pointer. +///
Quoted 8 lines
rust/kernel/uaccess.rs line 50
Quoted 6 lines
rust/kernel/uaccess.rs +6
-0+/// It is up to the caller to use the returned pointer correctly. +#[inline] +pub fn as_mut_ptr (self) -> *mut c_void { + self.0 + } +why are these two inline but the rest not?
Oh, I just forgot to add it.
Alice
Hi Alice,
Quoted 81 lines · Alice Ryhl
In C code we use sparse with the
__userannotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.The UserPtr type is not marked with #[derive(Debug)], which means that it's not possible to print values of this type. This avoids ASLR leakage.
The type is added to the prelude as it is a fairly fundamental type similar to
c_int. Thewrapping_add()method is renamed towrapping_byte_add()for consistency with the method name found on raw pointers.Signed-off-by Alice Ryhl <[email protected]>---
This is based on top of thestrncpy_from_userfor Rust patch.
---
Changes in v2:
- Change usize to raw pointer.
- Make field private.
- Renamewrapping_addtowrapping_byte_add.
- Add to prelude.
- Rebase on v4 ofstrncpy_from_user
- Link to v1: https://lore.kernel.org/r/[email protected]--- rust/kernel/prelude.rs | 2 ++ rust/kernel/uaccess.rs | 68 +++++++++++++++++++++++++++++++++------- samples/rust/rust_misc_device.rs | 2 ++ 3 files changed, 60 insertions(+), 12 deletions(-)rust/kernel/prelude.rs +2
-0@@ -41,3 +41,5 @@pub use super ::init::InPlaceInit ;pub use super ::current; + +pub use super ::uaccess::UserPtr ;rust/kernel/uaccess.rs +30
-2@@ -14,8 +14,48 @@ };use core::mem::{size_of,MaybeUninit }; -/// The type used for userspace addresses. -pub type UserPtr =usize ; +/// A pointer into userspace. +/// +/// This is the Rust equivalent to C pointers tagged with `__user`. +#[repr(transparent)] +#[derive( Copy , Clone )] +pub struct UserPtr (*mut c_void ); + +impl UserPtr { +/// Create a `UserPtr` from an integer representing the userspace address. +pub fn from_addr (addr:usize ) ->Self { +Self (addras *mut c_void ) + } + +/// Create a `UserPtr` from a pointer representing the userspace address. +pub fn from_ptr (addr: *mut c_void ) ->Self { +Self (addr) + } + +/// Cast this userspace pointer to a raw const void pointer. +/// +/// It is up to the caller to use the returned pointer correctly. +#[inline] +pub fn as_const_ptr (self) -> *const c_void { + self.0 + } + +/// Cast this userspace pointer to a raw mutable void pointer. +/// +/// It is up to the caller to use the returned pointer correctly. +#[inline]
rust/kernel/uaccess.rs line 56
Quoted 10 lines
rust/kernel/uaccess.rs +10
-0+pub fn as_mut_ptr (self) -> *mut c_void { + self.0 + } + +/// Increment this user pointer by `add` bytes. +/// +/// This addition is wrapping, so wrapping around the address space does not result in a panic +/// even if `CONFIG_RUST_OVERFLOW_CHECKS` is enabled. +pub fn wrapping_byte_add (self, add:usize ) ->UserPtr { +UserPtr (self.0 .wrapping_add (add))
Why use ptr::wrapping_add instead of ptr::wrapping_byte_add?
Should not really matter in this case, because c_void is repr(u8), but I find it a bit weird to use wrapping_add here.
With that fixed:
Quoted 112 lines
rust/kernel/uaccess.rs +16
-10+ } +}/// A pointer to an area in userspace memory, which can be either read-only or read-write. /// @@ -179,7 +219,7 @@ impl UserSliceReader {pub fn skip (&mut self, num_skip:usize ) ->Result {// Update `self.length` first since that's the fallible part of this operation. self.length = self.length.checked_sub (num_skip).ok_or (EFAULT )?; - self.ptr = self.ptr.wrapping_add (num_skip); + self.ptr = self.ptr.wrapping_byte_add (num_skip);Ok (()) }@@ -226,11 +266,11 @@ pub fn read_raw(&mut self, out: &mut [MaybeUninit<u8>]) -> Result { }// SAFETY: `out_ptr` points into a mutable slice of length `len`, so we may write // that many bytes to it. -let res =unsafe { bindings::copy_from_user (out_ptr, self.ptras *const c_void , len) }; +let res =unsafe { bindings::copy_from_user (out_ptr, self.ptr.as_const_ptr (), len) };if res !=0 {return Err (EFAULT ); } - self.ptr = self.ptr.wrapping_add (len); + self.ptr = self.ptr.wrapping_byte_add (len); self.length -= len;Ok (()) }@@ -264,14 +304,14 @@ pub fn read<T: FromBytes>(&mut self) -> Result<T> {let res =unsafe { bindings::_copy_from_user ( out.as_mut_ptr ().cast ::<c_void >(), - self.ptras *const c_void , + self.ptr.as_const_ptr (), len, ) };if res !=0 {return Err (EFAULT ); } - self.ptr = self.ptr.wrapping_add (len); + self.ptr = self.ptr.wrapping_byte_add (len); self.length -= len;// SAFETY: The read above has initialized all bytes in `out`, and since `T` implements // `FromBytes`, any bit-pattern is a valid value for this type. @@ -384,11 +424,11 @@ pub fn write_slice(&mut self, data: &[u8]) -> Result { }// SAFETY: `data_ptr` points into an immutable slice of length `len`, so we may read // that many bytes from it. -let res =unsafe { bindings::copy_to_user (self.ptras *mut c_void , data_ptr, len) }; +let res =unsafe { bindings::copy_to_user (self.ptr.as_mut_ptr (), data_ptr, len) };if res !=0 {return Err (EFAULT ); } - self.ptr = self.ptr.wrapping_add (len); + self.ptr = self.ptr.wrapping_byte_add (len); self.length -= len;Ok (()) }@@ -411,7 +451,7 @@ pub fn write<T: AsBytes>(&mut self, value: &T) -> Result {// is a compile-time constant. let res =unsafe { bindings::_copy_to_user ( - self.ptras *mut c_void , + self.ptr.as_mut_ptr (), (valueas *const T ).cast ::<c_void >(), len, )@@ -419,7 +459,7 @@ pub fn write<T: AsBytes>(&mut self, value: &T) -> Result {if res !=0 {return Err (EFAULT ); } - self.ptr = self.ptr.wrapping_add (len); + self.ptr = self.ptr.wrapping_byte_add (len); self.length -= len;Ok (()) }@@ -444,7 +484,11 @@ fn raw_strncpy_from_user(dst: &mut [MaybeUninit<u8>], src: UserPtr) -> Result<us// SAFETY: `dst` is valid for writing `dst.len()` bytes. let res =unsafe { - bindings::strncpy_from_user (dst.as_mut_ptr ().cast ::<c_char >(), srcas *const c_char , len) + bindings::strncpy_from_user ( + dst.as_mut_ptr ().cast ::<c_char >(), + src.as_const_ptr ().cast ::<c_char >(), + len, + ) };if res <0 {samples/rust/rust_misc_device.rs +2
-1@@ -176,6 +176,8 @@ fn open(_file: &File, misc: &MiscDeviceRegistration<Self>) -> Result<Pin<KBox<Sefn ioctl (me:Pin <&RustMiscDevice >, _file: &File , cmd:u32 , arg:usize ) ->Result <isize > {dev_info! (me.dev,"IOCTLing Rust Misc Device Sample\n" ); +// Treat the ioctl argument as a user pointer. +let arg =UserPtr ::from_addr (arg);let size =_IOC_SIZE (cmd);match cmd { ---base-commit:
f34da179a4517854b2ffbe4bce8c3405bd9be04e
change-id: 20250506-userptr-newtype-2f060985c33b
prerequisite-change-id: 20250424-strncpy-from-user-1f2d06b0cdde:v4
prerequisite-patch-id:d35c479ddb84bacc541dbb226c7911e5a22cad7e
prerequisite-patch-id:e0c345945dabfa18e9ca11f7fe11f8178d071285Best regards,
Alice Ryhl
reviewerQuoted 98 lines · Christian Schrefl
Hi Alice,
Quoted 81 lines · Alice Ryhl
In C code we use sparse with the
__userannotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.The UserPtr type is not marked with #[derive(Debug)], which means that it's not possible to print values of this type. This avoids ASLR leakage.
The type is added to the prelude as it is a fairly fundamental type similar to
c_int. Thewrapping_add()method is renamed towrapping_byte_add()for consistency with the method name found on raw pointers.Signed-off-by Alice Ryhl <[email protected]>---
This is based on top of thestrncpy_from_userfor Rust patch.
---
Changes in v2:
- Change usize to raw pointer.
- Make field private.
- Renamewrapping_addtowrapping_byte_add.
- Add to prelude.
- Rebase on v4 ofstrncpy_from_user
- Link to v1: https://lore.kernel.org/r/[email protected]--- rust/kernel/prelude.rs | 2 ++ rust/kernel/uaccess.rs | 68 +++++++++++++++++++++++++++++++++------- samples/rust/rust_misc_device.rs | 2 ++ 3 files changed, 60 insertions(+), 12 deletions(-)rust/kernel/prelude.rs +2
-0@@ -41,3 +41,5 @@pub use super ::init::InPlaceInit ;pub use super ::current; + +pub use super ::uaccess::UserPtr ;rust/kernel/uaccess.rs +30
-2@@ -14,8 +14,48 @@ };use core::mem::{size_of,MaybeUninit }; -/// The type used for userspace addresses. -pub type UserPtr =usize ; +/// A pointer into userspace. +/// +/// This is the Rust equivalent to C pointers tagged with `__user`. +#[repr(transparent)] +#[derive( Copy , Clone )] +pub struct UserPtr (*mut c_void ); + +impl UserPtr { +/// Create a `UserPtr` from an integer representing the userspace address. +pub fn from_addr (addr:usize ) ->Self { +Self (addras *mut c_void ) + } + +/// Create a `UserPtr` from a pointer representing the userspace address. +pub fn from_ptr (addr: *mut c_void ) ->Self { +Self (addr) + } + +/// Cast this userspace pointer to a raw const void pointer. +/// +/// It is up to the caller to use the returned pointer correctly. +#[inline] +pub fn as_const_ptr (self) -> *const c_void { + self.0 + } + +/// Cast this userspace pointer to a raw mutable void pointer. +/// +/// It is up to the caller to use the returned pointer correctly. +#[inline] rust/kernel/uaccess.rs line 56
Quoted 10 lines
rust/kernel/uaccess.rs +10
-0+pub fn as_mut_ptr (self) -> *mut c_void { + self.0 + } + +/// Increment this user pointer by `add` bytes. +/// +/// This addition is wrapping, so wrapping around the address space does not result in a panic +/// even if `CONFIG_RUST_OVERFLOW_CHECKS` is enabled. +pub fn wrapping_byte_add (self, add:usize ) ->UserPtr { +UserPtr (self.0 .wrapping_add (add))Why use
ptr::wrapping_addinstead ofptr::wrapping_byte_add?
Quoted 6 lines
Should not really matter in this case, because
c_voidisrepr(u8), but I find it a bit weird to usewrapping_addhere.With that fixed:
Reviewed-by Christian Schrefl <[email protected]>
Ah yeah, this should probably just be wrapping_byte_add() too. Alice
Quoted 5 lines · Alice Ryhl
In C code we use sparse with the
__userannotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.
Quoted 8 lines
The UserPtr type is not marked with #[derive(Debug)], which means that it's not possible to print values of this type. This avoids ASLR leakage.
The type is added to the prelude as it is a fairly fundamental type similar to
c_int. Thewrapping_add()method is renamed towrapping_byte_add()for consistency with the method name found on raw pointers.
That's considerably weaker than __user, though - with
struct foo {struct bar x; struct baz y[2]; };
struct foo __user *p;
void f(struct bar __user *);sparse does figure out that f(&p->y[1]) is a type error - &p->y[1] is struct baz __user * and f() expects struct bar __user *.
It's not just mixing userland pointers with other things - it's not mixing userland pointers to different types, etc.
In practice I've seen quite a few brainos caught by that...
Quoted 10 lines · Al Viro
Quoted 9 lines · Alice Ryhl
In C code we use sparse with the
__userannotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.The UserPtr type is not marked with #[derive(Debug)], which means that it's not possible to print values of this type. This avoids ASLR leakage.
Quoted 7 lines
Quoted 4 lines
The type is added to the prelude as it is a fairly fundamental type similar to
c_int. Thewrapping_add()method is renamed towrapping_byte_add()for consistency with the method name found on raw pointers.That's considerably weaker than
__user, though - withstruct foo {struct bar x; struct baz y[2]; };
Translate to Rust this is:
struct Foo {
x: Bar,
y: Baz[2],
}Quoted 1 line
struct foo __user *p;
UserPtr should probably be generic over pointee, so:
pub struct UserPtr<T>(*mut c_void, PhantomData<*mut T>);
and
let p: UserPtr<Foo> = ...;
Quoted 1 line
void f(struct bar __user *);
and this is:
pub fn f(bar: UserPtr<Bar>)
and the checking should work, a (maybe unrelated) tricky part though..
Quoted 1 line
sparse does figure out that
f(&p->y[1])is a type error - &p->y[1] is
In Rust, you will need to play a little unsafe game to get &p->y[1]:
let foo_ptr: *mut Foo = p.as_mut_ptr();
let y_ptr: *mut Baz = unsafe { addr_of_mut!((*foo_ptr).y[1]) };
let y: UserPtr<Baz> = unsafe { UserPtr::from_ptr(y_ptr) };passing y to f() will get a type mismatch, so the detection/checking works. To avoid the unsafe game we need field projection [1].
Quoted 5 lines
struct baz
__user* andf()expects struct bar__user*.It's not just mixing userland pointers with other things - it's not mixing userland pointers to different types, etc.
In short, with UserPtr generic over pointee, we can have the similar detection as sparse.
[1]: https://github.com/rust-lang/rfcs/pull/3735
Regards,
Boqun
Quoted 1 line
In practice I've seen quite a few brainos caught by that...
Alice Ryhl
reviewerQuoted 46 lines · Boqun Feng
Quoted 10 lines · Al Viro
Quoted 9 lines · Alice Ryhl
In C code we use sparse with the
__userannotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.The UserPtr type is not marked with #[derive(Debug)], which means that it's not possible to print values of this type. This avoids ASLR leakage.
Quoted 7 lines
Quoted 4 lines
The type is added to the prelude as it is a fairly fundamental type similar to
c_int. Thewrapping_add()method is renamed towrapping_byte_add()for consistency with the method name found on raw pointers.That's considerably weaker than
__user, though - withstruct foo {struct bar x; struct baz y[2]; };Translate to Rust this is:
struct Foo { x: Bar, y: Baz[2], }Quoted 1 line
struct foo __user *p;UserPtr should probably be generic over pointee, so:
pub struct UserPtr<T>(*mut c_void, PhantomData<*mut T>);and
let p: UserPtr<Foo> = ...;Quoted 1 line
void f(struct bar __user *);and this is:
pub fn f(bar: UserPtr<Bar>)
and the checking should work, a (maybe unrelated) tricky part though..
Quoted 1 line
sparse does figure out that
f(&p->y[1])is a type error - &p->y[1] is
Quoted 8 lines
In Rust, you will need to play a little unsafe game to get &p->y[1]:
let foo_ptr: *mut Foo = p.as_mut_ptr(); let y_ptr: *mut Baz = unsafe { addr_of_mut!((*foo_ptr).y[1]) }; let y: UserPtr<Baz> = unsafe { UserPtr::from_ptr(y_ptr) };passing y to
f()will get a type mismatch, so the detection/checking works. To avoid the unsafe game we need field projection [1].
That looks pretty unergonomic. We can do better than that.
Alice
Quoted 15 lines
Quoted 5 lines
struct baz
__user* andf()expects struct bar__user*.It's not just mixing userland pointers with other things - it's not mixing userland pointers to different types, etc.
In short, with UserPtr generic over pointee, we can have the similar detection as sparse.
[1]: https://github.com/rust-lang/rfcs/pull/3735
Regards,
BoqunQuoted 1 line
In practice I've seen quite a few brainos caught by that...
Benno Lossin
reviewerQuoted 44 lines · Boqun Feng
Quoted 10 lines · Al Viro
Quoted 9 lines · Alice Ryhl
In C code we use sparse with the
__userannotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.The UserPtr type is not marked with #[derive(Debug)], which means that it's not possible to print values of this type. This avoids ASLR leakage.
Quoted 7 lines
Quoted 4 lines
The type is added to the prelude as it is a fairly fundamental type similar to
c_int. Thewrapping_add()method is renamed towrapping_byte_add()for consistency with the method name found on raw pointers.That's considerably weaker than
__user, though - withstruct foo {struct bar x; struct baz y[2]; };Translate to Rust this is:
struct Foo { x: Bar, y: Baz[2], }Quoted 1 line
struct foo __user *p;UserPtr should probably be generic over pointee, so:
pub struct UserPtr<T>(*mut c_void, PhantomData<*mut T>);and
let p: UserPtr<Foo> = ...;Quoted 1 line
void f(struct bar __user *);and this is:
pub fn f(bar: UserPtr<Bar>)
and the checking should work, a (maybe unrelated) tricky part though..
Quoted 7 lines
Quoted 1 line
sparse does figure out that
f(&p->y[1])is a type error - &p->y[1] isIn Rust, you will need to play a little unsafe game to get &p->y[1]:
let foo_ptr: *mut Foo = p.as_mut_ptr(); let y_ptr: *mut Baz = unsafe { addr_of_mut!((*foo_ptr).y[1]) }; let y: UserPtr<Baz> = unsafe { UserPtr::from_ptr(y_ptr) };
Shouldn't this use wrapping_add since the pointer shouldn't be dereferenced?
If we don't use wrapping_add, then the field projection operation for this type must be unsafe.
---
Cheers,
Benno
Quoted 47 lines · Benno Lossin
Quoted 46 lines · Boqun Feng
Quoted 10 lines · Al Viro
Quoted 9 lines · Alice Ryhl
In C code we use sparse with the
__userannotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.The UserPtr type is not marked with #[derive(Debug)], which means that it's not possible to print values of this type. This avoids ASLR leakage.
Quoted 7 lines
Quoted 4 lines
The type is added to the prelude as it is a fairly fundamental type similar to
c_int. Thewrapping_add()method is renamed towrapping_byte_add()for consistency with the method name found on raw pointers.That's considerably weaker than
__user, though - withstruct foo {struct bar x; struct baz y[2]; };Translate to Rust this is:
struct Foo { x: Bar, y: Baz[2], }Quoted 1 line
struct foo __user *p;UserPtr should probably be generic over pointee, so:
pub struct UserPtr<T>(*mut c_void, PhantomData<*mut T>);and
let p: UserPtr<Foo> = ...;Quoted 1 line
void f(struct bar __user *);and this is:
pub fn f(bar: UserPtr<Bar>)
and the checking should work, a (maybe unrelated) tricky part though..
Quoted 1 line
sparse does figure out that
f(&p->y[1])is a type error - &p->y[1] is
Quoted 9 lines
Quoted 5 lines
In Rust, you will need to play a little unsafe game to get &p->y[1]:
let foo_ptr: *mut Foo = p.as_mut_ptr(); let y_ptr: *mut Baz = unsafe { addr_of_mut!((*foo_ptr).y[1]) }; let y: UserPtr<Baz> = unsafe { UserPtr::from_ptr(y_ptr) };Shouldn't this use
wrapping_addsince the pointer shouldn't be dereferenced?
Good point, so:
let foo_ptr: *mut Foo = p.as_mut_ptr();
let y_ptr: *mut Baz = foo_ptr.wrapping_byte_add(offset_of!(Foo, y[1]));
let y: UserPtr<Baz> = unsafe { UserPtr::from_ptr(y_ptr) };(using wrapping_byte_add() + offset_of!())
Regards,
Boqun
Quoted 6 lines
If we don't use
wrapping_add, then the field projection operation for this type must beunsafe.---
Cheers,
Benno
Alice Ryhl
reviewerQuoted 19 lines · Al Viro
Quoted 5 lines · Alice Ryhl
In C code we use sparse with the
__userannotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.Quoted 8 lines
The UserPtr type is not marked with #[derive(Debug)], which means that it's not possible to print values of this type. This avoids ASLR leakage.
The type is added to the prelude as it is a fairly fundamental type similar to
c_int. Thewrapping_add()method is renamed towrapping_byte_add()for consistency with the method name found on raw pointers.That's considerably weaker than
__user, though - withstruct foo {struct bar x; struct baz y[2]; }; struct foo __user *p; void f(struct bar __user *);
Quoted 7 lines
sparse does figure out that
f(&p->y[1])is a type error - &p->y[1] is struct baz__user* andf()expects struct bar__user*.It's not just mixing userland pointers with other things - it's not mixing userland pointers to different types, etc.
In practice I've seen quite a few brainos caught by that...
We don't currently have any way to perform that kind of pointer-math on user pointers, nor do we have any users of it. I imagine that this type checking is only useful if you can actually perform pointer math in the first place?
Right now, actual reading/writing to userspace is done via the UserSliceReader and UserSliceWriter types rather than directly on UserPtr, and UserPtr is just the constructor for those other types. There is already some means of type checking on UserSliceReader and UserSliceWriter, so I'm inclined to say that this is good enough.
Of course, if we ever add a way to do pointer math on user pointers, then they should have a pointee type and hence also this check.
Alice
Quoted 4 lines · Alice Ryhl
We don't currently have any way to perform that kind of pointer-math on user pointers, nor do we have any users of it. I imagine that this type checking is only useful if you can actually perform pointer math in the first place?
What you want is something like
x->field::UserPtr(beta) iff x::UserPtr(alpha) and _.field::beta where _::alpha
Generated code would be "add offset and cast to pointer to type of...", but doing that manually would really invite headache.
Quoted 7 lines · Al Viro
Quoted 4 lines · Alice Ryhl
We don't currently have any way to perform that kind of pointer-math on user pointers, nor do we have any users of it. I imagine that this type checking is only useful if you can actually perform pointer math in the first place?
Quoted 7 lines
What you want is something like
x->field::UserPtr(beta) iff x::UserPtr(alpha) and _.field::beta where _::alphaGenerated code would be "add offset and cast to pointer to type of...", but doing that manually would really invite headache.
... except that -> comes with wrong connotations, of course. Hell knows what a decent syntax would look like.
Benno Lossin
reviewerQuoted 11 lines · Al Viro
Quoted 4 lines · Alice Ryhl
We don't currently have any way to perform that kind of pointer-math on user pointers, nor do we have any users of it. I imagine that this type checking is only useful if you can actually perform pointer math in the first place?
What you want is something like
x->field::UserPtr(beta) iff x::UserPtr(alpha) and _.field::beta where _::alpha
Not 100% sure I understand your code correctly, do you mean that:x->field is of type UserPtr(beta) given that x is of type UserPtr(alpha) and field is a field of alpha of type beta?
If that is correct, then I have a proposal called field projection [1] for the rust language itself to support this kind of operation for any custom type.
I also have an macro-based implementation [2] and I could cook up some examples with UserPtr [^3].
[1]: https://github.com/rust-lang/rfcs/pull/3735
[2]: https://github.com/Rust-for-Linux/field-projection/tree/new
[^3]: Here is a quick sketch of how the above would look like in Rust
using [2]:
#[derive(HasFields)]
struct Alpha {
field: Beta,
}
impl Alpha {
fn write_beta<'a>(mut self: UserPtr<'a, Self>, value: Beta) {
start_proj!(mut self);
let mut field: UserPtr<'a, Beta> = p!(@mut self->field);
field.write(value);
}
}
A couple notes for anyone not too familiar with Rust:
* `'a` is called a lifetime, it says for how long a value is valid
* the `< ... >` are generic types
* the `ident: Type` is a type annotation used in parameters (not
optional) and in local variable bindings (optional)
* the `self` parameter is special, it allows one to use the
`val.fun` syntax (it's similar to `this` in java and `self` in
python, but without the object orientation stuff associated with
it)---
Cheers,
Benno
Quoted 2 lines
Generated code would be "add offset and cast to pointer to type of...", but doing that manually would really invite headache.
Quoted 9 lines · Alice Ryhl
In C code we use sparse with the
__userannotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.The UserPtr type is not marked with #[derive(Debug)], which means that it's not possible to print values of this type. This avoids ASLR leakage.
Quoted 6 lines
The type is added to the prelude as it is a fairly fundamental type similar to
c_int. Thewrapping_add()method is renamed towrapping_byte_add()for consistency with the method name found on raw pointers.Signed-off-by Alice Ryhl <[email protected]>
Quoted 6 lines · Alice Ryhl
In C code we use sparse with the
__userannotation to detect cases where a user pointer is mixed up with other things. To replicate that, we introduce a new struct UserPtr that serves the same purpose using the newtype pattern.The UserPtr type is not marked with #[derive(Debug)], which means that
Should we still implement it, not printing the address of course? So something like UserPtr(/* .. */) or whatever people print instead of showing the address?
Quoted 9 lines
it's not possible to print values of this type. This avoids ASLR leakage.
The type is added to the prelude as it is a fairly fundamental type similar to
c_int. Thewrapping_add()method is renamed towrapping_byte_add()for consistency with the method name found on raw pointers.Signed-off-by Alice Ryhl <[email protected]>
I left one question below, but it already looks good, so:
rust/kernel/uaccess.rs fn raw_strncpy_from_user(dst: &mut [MaybeUninit<u8>], src: UserPtr) -> Result<us · line 489
Quoted 8 lines
rust/kernel/uaccess.rs +3
-1@@ -444,7 +484,11 @@ fn raw_strncpy_from_user(dst: &mut [MaybeUninit<u8>], src: UserPtr) -> Result<us// SAFETY: `dst` is valid for writing `dst.len()` bytes. let res =unsafe { - bindings::strncpy_from_user (dst.as_mut_ptr ().cast ::<c_char >(), srcas *const c_char , len) + bindings::strncpy_from_user ( + dst.as_mut_ptr ().cast ::<c_char >(), + src.as_const_ptr().cast::<c_char>(),
Should we also have as_{const,mut}_char_ptr functions? After a quick search, I found that char __user * is a common type for user pointers.
---
Cheers,
Benno
Quoted 3 lines
rust/kernel/uaccess.rs +2
-0+ len, + ) };