uaccess.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. // SPDX-License-Identifier: GPL-2.0
  2. //! Slices to user space memory regions.
  3. //!
  4. //! C header: [`include/linux/uaccess.h`](srctree/include/linux/uaccess.h)
  5. use crate::{
  6. alloc::Flags,
  7. bindings,
  8. error::Result,
  9. ffi::c_void,
  10. prelude::*,
  11. types::{AsBytes, FromBytes},
  12. };
  13. use core::mem::{size_of, MaybeUninit};
  14. /// The type used for userspace addresses.
  15. pub type UserPtr = usize;
  16. /// A pointer to an area in userspace memory, which can be either read-only or read-write.
  17. ///
  18. /// All methods on this struct are safe: attempting to read or write on bad addresses (either out of
  19. /// the bound of the slice or unmapped addresses) will return [`EFAULT`]. Concurrent access,
  20. /// *including data races to/from userspace memory*, is permitted, because fundamentally another
  21. /// userspace thread/process could always be modifying memory at the same time (in the same way that
  22. /// userspace Rust's [`std::io`] permits data races with the contents of files on disk). In the
  23. /// presence of a race, the exact byte values read/written are unspecified but the operation is
  24. /// well-defined. Kernelspace code should validate its copy of data after completing a read, and not
  25. /// expect that multiple reads of the same address will return the same value.
  26. ///
  27. /// These APIs are designed to make it difficult to accidentally write TOCTOU (time-of-check to
  28. /// time-of-use) bugs. Every time a memory location is read, the reader's position is advanced by
  29. /// the read length and the next read will start from there. This helps prevent accidentally reading
  30. /// the same location twice and causing a TOCTOU bug.
  31. ///
  32. /// Creating a [`UserSliceReader`] and/or [`UserSliceWriter`] consumes the `UserSlice`, helping
  33. /// ensure that there aren't multiple readers or writers to the same location.
  34. ///
  35. /// If double-fetching a memory location is necessary for some reason, then that is done by creating
  36. /// multiple readers to the same memory location, e.g. using [`clone_reader`].
  37. ///
  38. /// # Examples
  39. ///
  40. /// Takes a region of userspace memory from the current process, and modify it by adding one to
  41. /// every byte in the region.
  42. ///
  43. /// ```no_run
  44. /// use kernel::ffi::c_void;
  45. /// use kernel::error::Result;
  46. /// use kernel::uaccess::{UserPtr, UserSlice};
  47. ///
  48. /// fn bytes_add_one(uptr: UserPtr, len: usize) -> Result<()> {
  49. /// let (read, mut write) = UserSlice::new(uptr, len).reader_writer();
  50. ///
  51. /// let mut buf = KVec::new();
  52. /// read.read_all(&mut buf, GFP_KERNEL)?;
  53. ///
  54. /// for b in &mut buf {
  55. /// *b = b.wrapping_add(1);
  56. /// }
  57. ///
  58. /// write.write_slice(&buf)?;
  59. /// Ok(())
  60. /// }
  61. /// ```
  62. ///
  63. /// Example illustrating a TOCTOU (time-of-check to time-of-use) bug.
  64. ///
  65. /// ```no_run
  66. /// use kernel::ffi::c_void;
  67. /// use kernel::error::{code::EINVAL, Result};
  68. /// use kernel::uaccess::{UserPtr, UserSlice};
  69. ///
  70. /// /// Returns whether the data in this region is valid.
  71. /// fn is_valid(uptr: UserPtr, len: usize) -> Result<bool> {
  72. /// let read = UserSlice::new(uptr, len).reader();
  73. ///
  74. /// let mut buf = KVec::new();
  75. /// read.read_all(&mut buf, GFP_KERNEL)?;
  76. ///
  77. /// todo!()
  78. /// }
  79. ///
  80. /// /// Returns the bytes behind this user pointer if they are valid.
  81. /// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result<KVec<u8>> {
  82. /// if !is_valid(uptr, len)? {
  83. /// return Err(EINVAL);
  84. /// }
  85. ///
  86. /// let read = UserSlice::new(uptr, len).reader();
  87. ///
  88. /// let mut buf = KVec::new();
  89. /// read.read_all(&mut buf, GFP_KERNEL)?;
  90. ///
  91. /// // THIS IS A BUG! The bytes could have changed since we checked them.
  92. /// //
  93. /// // To avoid this kind of bug, don't call `UserSlice::new` multiple
  94. /// // times with the same address.
  95. /// Ok(buf)
  96. /// }
  97. /// ```
  98. ///
  99. /// [`std::io`]: https://doc.rust-lang.org/std/io/index.html
  100. /// [`clone_reader`]: UserSliceReader::clone_reader
  101. pub struct UserSlice {
  102. ptr: UserPtr,
  103. length: usize,
  104. }
  105. impl UserSlice {
  106. /// Constructs a user slice from a raw pointer and a length in bytes.
  107. ///
  108. /// Constructing a [`UserSlice`] performs no checks on the provided address and length, it can
  109. /// safely be constructed inside a kernel thread with no current userspace process. Reads and
  110. /// writes wrap the kernel APIs `copy_from_user` and `copy_to_user`, which check the memory map
  111. /// of the current process and enforce that the address range is within the user range (no
  112. /// additional calls to `access_ok` are needed). Validity of the pointer is checked when you
  113. /// attempt to read or write, not in the call to `UserSlice::new`.
  114. ///
  115. /// Callers must be careful to avoid time-of-check-time-of-use (TOCTOU) issues. The simplest way
  116. /// is to create a single instance of [`UserSlice`] per user memory block as it reads each byte
  117. /// at most once.
  118. pub fn new(ptr: UserPtr, length: usize) -> Self {
  119. UserSlice { ptr, length }
  120. }
  121. /// Reads the entirety of the user slice, appending it to the end of the provided buffer.
  122. ///
  123. /// Fails with [`EFAULT`] if the read happens on a bad address.
  124. pub fn read_all(self, buf: &mut KVec<u8>, flags: Flags) -> Result {
  125. self.reader().read_all(buf, flags)
  126. }
  127. /// Constructs a [`UserSliceReader`].
  128. pub fn reader(self) -> UserSliceReader {
  129. UserSliceReader {
  130. ptr: self.ptr,
  131. length: self.length,
  132. }
  133. }
  134. /// Constructs a [`UserSliceWriter`].
  135. pub fn writer(self) -> UserSliceWriter {
  136. UserSliceWriter {
  137. ptr: self.ptr,
  138. length: self.length,
  139. }
  140. }
  141. /// Constructs both a [`UserSliceReader`] and a [`UserSliceWriter`].
  142. ///
  143. /// Usually when this is used, you will first read the data, and then overwrite it afterwards.
  144. pub fn reader_writer(self) -> (UserSliceReader, UserSliceWriter) {
  145. (
  146. UserSliceReader {
  147. ptr: self.ptr,
  148. length: self.length,
  149. },
  150. UserSliceWriter {
  151. ptr: self.ptr,
  152. length: self.length,
  153. },
  154. )
  155. }
  156. }
  157. /// A reader for [`UserSlice`].
  158. ///
  159. /// Used to incrementally read from the user slice.
  160. pub struct UserSliceReader {
  161. ptr: UserPtr,
  162. length: usize,
  163. }
  164. impl UserSliceReader {
  165. /// Skip the provided number of bytes.
  166. ///
  167. /// Returns an error if skipping more than the length of the buffer.
  168. pub fn skip(&mut self, num_skip: usize) -> Result {
  169. // Update `self.length` first since that's the fallible part of this operation.
  170. self.length = self.length.checked_sub(num_skip).ok_or(EFAULT)?;
  171. self.ptr = self.ptr.wrapping_add(num_skip);
  172. Ok(())
  173. }
  174. /// Create a reader that can access the same range of data.
  175. ///
  176. /// Reading from the clone does not advance the current reader.
  177. ///
  178. /// The caller should take care to not introduce TOCTOU issues, as described in the
  179. /// documentation for [`UserSlice`].
  180. pub fn clone_reader(&self) -> UserSliceReader {
  181. UserSliceReader {
  182. ptr: self.ptr,
  183. length: self.length,
  184. }
  185. }
  186. /// Returns the number of bytes left to be read from this reader.
  187. ///
  188. /// Note that even reading less than this number of bytes may fail.
  189. pub fn len(&self) -> usize {
  190. self.length
  191. }
  192. /// Returns `true` if no data is available in the io buffer.
  193. pub fn is_empty(&self) -> bool {
  194. self.length == 0
  195. }
  196. /// Reads raw data from the user slice into a kernel buffer.
  197. ///
  198. /// For a version that uses `&mut [u8]`, please see [`UserSliceReader::read_slice`].
  199. ///
  200. /// Fails with [`EFAULT`] if the read happens on a bad address, or if the read goes out of
  201. /// bounds of this [`UserSliceReader`]. This call may modify `out` even if it returns an error.
  202. ///
  203. /// # Guarantees
  204. ///
  205. /// After a successful call to this method, all bytes in `out` are initialized.
  206. pub fn read_raw(&mut self, out: &mut [MaybeUninit<u8>]) -> Result {
  207. let len = out.len();
  208. let out_ptr = out.as_mut_ptr().cast::<c_void>();
  209. if len > self.length {
  210. return Err(EFAULT);
  211. }
  212. // SAFETY: `out_ptr` points into a mutable slice of length `len`, so we may write
  213. // that many bytes to it.
  214. let res = unsafe { bindings::copy_from_user(out_ptr, self.ptr as *const c_void, len) };
  215. if res != 0 {
  216. return Err(EFAULT);
  217. }
  218. self.ptr = self.ptr.wrapping_add(len);
  219. self.length -= len;
  220. Ok(())
  221. }
  222. /// Reads raw data from the user slice into a kernel buffer.
  223. ///
  224. /// Fails with [`EFAULT`] if the read happens on a bad address, or if the read goes out of
  225. /// bounds of this [`UserSliceReader`]. This call may modify `out` even if it returns an error.
  226. pub fn read_slice(&mut self, out: &mut [u8]) -> Result {
  227. // SAFETY: The types are compatible and `read_raw` doesn't write uninitialized bytes to
  228. // `out`.
  229. let out = unsafe { &mut *(out as *mut [u8] as *mut [MaybeUninit<u8>]) };
  230. self.read_raw(out)
  231. }
  232. /// Reads a value of the specified type.
  233. ///
  234. /// Fails with [`EFAULT`] if the read happens on a bad address, or if the read goes out of
  235. /// bounds of this [`UserSliceReader`].
  236. pub fn read<T: FromBytes>(&mut self) -> Result<T> {
  237. let len = size_of::<T>();
  238. if len > self.length {
  239. return Err(EFAULT);
  240. }
  241. let mut out: MaybeUninit<T> = MaybeUninit::uninit();
  242. // SAFETY: The local variable `out` is valid for writing `size_of::<T>()` bytes.
  243. //
  244. // By using the _copy_from_user variant, we skip the check_object_size check that verifies
  245. // the kernel pointer. This mirrors the logic on the C side that skips the check when the
  246. // length is a compile-time constant.
  247. let res = unsafe {
  248. bindings::_copy_from_user(
  249. out.as_mut_ptr().cast::<c_void>(),
  250. self.ptr as *const c_void,
  251. len,
  252. )
  253. };
  254. if res != 0 {
  255. return Err(EFAULT);
  256. }
  257. self.ptr = self.ptr.wrapping_add(len);
  258. self.length -= len;
  259. // SAFETY: The read above has initialized all bytes in `out`, and since `T` implements
  260. // `FromBytes`, any bit-pattern is a valid value for this type.
  261. Ok(unsafe { out.assume_init() })
  262. }
  263. /// Reads the entirety of the user slice, appending it to the end of the provided buffer.
  264. ///
  265. /// Fails with [`EFAULT`] if the read happens on a bad address.
  266. pub fn read_all(mut self, buf: &mut KVec<u8>, flags: Flags) -> Result {
  267. let len = self.length;
  268. buf.reserve(len, flags)?;
  269. // The call to `try_reserve` was successful, so the spare capacity is at least `len` bytes
  270. // long.
  271. self.read_raw(&mut buf.spare_capacity_mut()[..len])?;
  272. // SAFETY: Since the call to `read_raw` was successful, so the next `len` bytes of the
  273. // vector have been initialized.
  274. unsafe { buf.set_len(buf.len() + len) };
  275. Ok(())
  276. }
  277. }
  278. /// A writer for [`UserSlice`].
  279. ///
  280. /// Used to incrementally write into the user slice.
  281. pub struct UserSliceWriter {
  282. ptr: UserPtr,
  283. length: usize,
  284. }
  285. impl UserSliceWriter {
  286. /// Returns the amount of space remaining in this buffer.
  287. ///
  288. /// Note that even writing less than this number of bytes may fail.
  289. pub fn len(&self) -> usize {
  290. self.length
  291. }
  292. /// Returns `true` if no more data can be written to this buffer.
  293. pub fn is_empty(&self) -> bool {
  294. self.length == 0
  295. }
  296. /// Writes raw data to this user pointer from a kernel buffer.
  297. ///
  298. /// Fails with [`EFAULT`] if the write happens on a bad address, or if the write goes out of
  299. /// bounds of this [`UserSliceWriter`]. This call may modify the associated userspace slice even
  300. /// if it returns an error.
  301. pub fn write_slice(&mut self, data: &[u8]) -> Result {
  302. let len = data.len();
  303. let data_ptr = data.as_ptr().cast::<c_void>();
  304. if len > self.length {
  305. return Err(EFAULT);
  306. }
  307. // SAFETY: `data_ptr` points into an immutable slice of length `len`, so we may read
  308. // that many bytes from it.
  309. let res = unsafe { bindings::copy_to_user(self.ptr as *mut c_void, data_ptr, len) };
  310. if res != 0 {
  311. return Err(EFAULT);
  312. }
  313. self.ptr = self.ptr.wrapping_add(len);
  314. self.length -= len;
  315. Ok(())
  316. }
  317. /// Writes the provided Rust value to this userspace pointer.
  318. ///
  319. /// Fails with [`EFAULT`] if the write happens on a bad address, or if the write goes out of
  320. /// bounds of this [`UserSliceWriter`]. This call may modify the associated userspace slice even
  321. /// if it returns an error.
  322. pub fn write<T: AsBytes>(&mut self, value: &T) -> Result {
  323. let len = size_of::<T>();
  324. if len > self.length {
  325. return Err(EFAULT);
  326. }
  327. // SAFETY: The reference points to a value of type `T`, so it is valid for reading
  328. // `size_of::<T>()` bytes.
  329. //
  330. // By using the _copy_to_user variant, we skip the check_object_size check that verifies the
  331. // kernel pointer. This mirrors the logic on the C side that skips the check when the length
  332. // is a compile-time constant.
  333. let res = unsafe {
  334. bindings::_copy_to_user(
  335. self.ptr as *mut c_void,
  336. (value as *const T).cast::<c_void>(),
  337. len,
  338. )
  339. };
  340. if res != 0 {
  341. return Err(EFAULT);
  342. }
  343. self.ptr = self.ptr.wrapping_add(len);
  344. self.length -= len;
  345. Ok(())
  346. }
  347. }