From patchwork Tue May 28 14:58:04 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13676939 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id E2F80C25B78 for ; Tue, 28 May 2024 14:58:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 10EE76B00A0; Tue, 28 May 2024 10:58:27 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 0BE696B00A1; Tue, 28 May 2024 10:58:27 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E79D26B00A2; Tue, 28 May 2024 10:58:26 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0015.hostedemail.com [216.40.44.15]) by kanga.kvack.org (Postfix) with ESMTP id C50F66B00A0 for ; Tue, 28 May 2024 10:58:26 -0400 (EDT) Received: from smtpin12.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 6E6C7A17F8 for ; Tue, 28 May 2024 14:58:26 +0000 (UTC) X-FDA: 82168110612.12.663FB19 Received: from mail-lj1-f202.google.com (mail-lj1-f202.google.com [209.85.208.202]) by imf10.hostedemail.com (Postfix) with ESMTP id 54B8AC0020 for ; Tue, 28 May 2024 14:58:24 +0000 (UTC) Authentication-Results: imf10.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=aW8R2TCr; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf10.hostedemail.com: domain of 3DvFVZgkKCIEfqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com designates 209.85.208.202 as permitted sender) smtp.mailfrom=3DvFVZgkKCIEfqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1716908304; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=b9/4bIUoqG75SiXX4ggGIII0PXg7f1u44UaqTYS94zc=; b=jlcbXvBmlH6TG9NxT+bZRgBtmQ3afdLptAGA4Jnz3XOgmGuUMyw3Fs2m3Ed5WUel07Qe7x P9OP2ur05VcROPt7ztr9vqnbYqBzphTD19+IUOkvPEEuY36bBin8QEOccMuM5ES0HAhKQZ /9z9RyMV7029rS1+VN0pMB2GiJmYW+E= ARC-Authentication-Results: i=1; imf10.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=aW8R2TCr; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf10.hostedemail.com: domain of 3DvFVZgkKCIEfqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com designates 209.85.208.202 as permitted sender) smtp.mailfrom=3DvFVZgkKCIEfqnhjw3mqlttlqj.htrqnsz2-rrp0fhp.twl@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1716908304; a=rsa-sha256; cv=none; b=nO3s7sP5073kcQHqWZAnib4czeHKRFXOxl08AnWQVFGx7ypL93d0iLZrWLBi9Z3N+y3p++ rzN/2DyDAA5oLEQnBxhkRD5dn7uY8tSE2a81uZ89fA8cv0nCxe/1o/TLrcUNDCk2K6b7om ED4eqFzgqj2ltS1Rj5YtM/+0c00zL/0= Received: by mail-lj1-f202.google.com with SMTP id 38308e7fff4ca-2e95a1eba87so7032931fa.0 for ; Tue, 28 May 2024 07:58:23 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1716908302; x=1717513102; darn=kvack.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=b9/4bIUoqG75SiXX4ggGIII0PXg7f1u44UaqTYS94zc=; b=aW8R2TCryXNRZLmpe8GRH2CpWl345WSNC+xWlOBy6rneJQlWKS15ALzdo67vqrgay5 5HNdHIeLAYAy6inSyPBt7ZhVUH8QP3sN0jkqrpv7pY4QrVtAjBrOz2MTZNFAn0G1eiAz rwNzpLMDIcXdWSKj0BBX+VUU7Qsd3WUT+l76z6KwUTEj7UzHc1Q3aoPhxY8scaWGsPRt DNNDYhdAjizrAxFcj8Q9W2JnGA3ieFvWg473GyceKUfKONJO6Gi6RNSCtio1CGXIh4Dj /HY4nQOMD+bnRwXtmuXNgkjBth6p7oKpeJjnvcaU/nrdiGtgT1d64jUzBcnkgDRqb+28 o2cg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1716908302; x=1717513102; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=b9/4bIUoqG75SiXX4ggGIII0PXg7f1u44UaqTYS94zc=; b=bWf4vybEkRUzFVvSaweb6vAej4QpPZ6K+CXRvjBHSDYr5PWxS+BjNODnph0tX/u30Z /C5RtHb8U5dy1LEjB2lO0ifrfWOKjQ4rgCoW4cWBlw3ZZxA0DKgF/isIlY0OPcsyQ++8 X74QgK0UqUJD3k5fOQjce/pzrF5nxwvXA7cvYnBhTWvWE3f2FYnGI55KWM69vI/jy8eG A0byn829V+z8zY9GIjN9lAwTQfm3T37gj5ALcUhKTXn7+dZb7nTt+ZaFWogt6t8CWvcr 0LaOOBKfeUXPdtzlTG3nbainxRK+ZTRMSm6BOKtWwYqiESUOHXomoifFPG37K7ZMRjuV cJkA== X-Forwarded-Encrypted: i=1; AJvYcCXFt89r3L0K/fN5RsjNCPSitF2GikwJdloMpK+mRpprHCFiKKIRDCz0ng9OHAK1BnzNv2k3lXN2ZVn4eP86/rJ8sBk= X-Gm-Message-State: AOJu0YzlY/RF24WA8eousFMwLctvP8rvGZbMqc8IqA3xlXxSvTV7gE+g YR7/kguIOE3U2WWM42PliML7cUrlAjtFELBTJBnNhseujnabRNJwdQdyzkARh5yLIvHUxFdybAG ZULUw8o6qpLs39Q== X-Google-Smtp-Source: AGHT+IGI0oSXsScGynqqZZ2qwR5qKbUrUE71Co+pWa+5ECFU6Ac40a2IMZtYKbVJYyka3eZNWCz/z+D1TV0BmGo= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a2e:360a:0:b0:2e0:d8c9:990b with SMTP id 38308e7fff4ca-2e95b27444fmr106591fa.6.1716908302093; Tue, 28 May 2024 07:58:22 -0700 (PDT) Date: Tue, 28 May 2024 14:58:04 +0000 In-Reply-To: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> Mime-Version: 1.0 References: <20240528-alice-mm-v7-0-78222c31b8f4@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=9020; i=aliceryhl@google.com; h=from:subject:message-id; bh=yYu+EAbmrLlEDaJXxUlWd5cGuX40snAODQjVSX7+z6k=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmVfEB6oia3O2ePKqSvHFP2bMtfCznNnjJ6XHWK p+dntQJgACJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZlXxAQAKCRAEWL7uWMY5 RuYID/0Zn/Ekx3yhhKl8ze+ZbQzTKxxhXSitWFq4evNnN7TxwgP5on/9bu3I4gtYDFe787qYSj9 BOCif2gFbd/W7XnW2o0c4X44ErtiRtxHIxRN9v+BKfZCw5QQARt8Ajgsui4ZfRYwEWk44TPZI1Y ZQTmnG9HQ1sfgWJZDxSWzWPnFQ/y3r7fHtuFkKQ0eT5vm738ccBDWCX4XX19tH9Mr7CgaOoMQnu OquFHYfIDW84czELfZA/wxol/7ce8K8ryQibE6naSMDfDSInpHzGfx8/ip8PtM9Mi/jDby2llEO nT0Zl8jquE9Pe7raOb3reL8EWbRnIQpOF4/IIYqakQtDvI5fM4Z+TgS2S6kD1o83Hpg3ku22YvS syoIxmuGiZ8E4R1mMfy9mU/qoQGf6OTWSfNu+EycjF7B2+bWIRSXAiu8zEyfuXbJktrruMZFHWV fsvstUp7l71TeB77N1rF2vyk7xgkxGRylsQPfG/ED3UuJEO8Xx7FdHMuAtBIzqJX64qyC/lh+Mq 1W7nAeH1p02ib0EQGuTuP20f5kPoK8dQqaILUGYUKSoVf8OJlZIcoZobaU+TMGjtE9ZFjaTEZHZ Kmcyjbt85Yq0OSAPNijN/SRH7zbXdnauNWXi3h+wi7DmKTGme5m2Rc26ifu9o9W9e8qOef1bzSQ q8YkdHOAa9SgfJA== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240528-alice-mm-v7-3-78222c31b8f4@google.com> Subject: [PATCH v7 3/4] rust: uaccess: add typed accessors for userspace pointers From: Alice Ryhl To: Miguel Ojeda , Matthew Wilcox , Al Viro , Andrew Morton , Kees Cook Cc: Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj=C3=B8?= =?utf-8?q?nnev=C3=A5g?= " , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Arnd Bergmann , Trevor Gross , linux-mm@kvack.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Christian Brauner X-Rspamd-Queue-Id: 54B8AC0020 X-Stat-Signature: caxexob7mipzntcpx48erg1qdtxsc8r7 X-Rspam-User: X-Rspamd-Server: rsp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RqdsNXb2S3q/vkPU/5KUzzghSLp5Ee5aZZ2+t9TEhN9vdZRIYuZBrYyS1fJg9F9kZiEW2rTBfkddMBT2YJKU8TW1MbaQlLVu2+dZX4CYNYAiJhoXwGFTO5BIYgQOmFrw4BSGIT2PJg14TbLt7AwkZ4I1RZJirDO0JWkfRwzJST0zEbfeuzujEf4BOJtcEAvDSV4130JIOO2oby6Il2IB8fgH0iXz+50KzTWZepQVQoGutZJBdZuFn0LGHsXQyYZGQsvURW2i0HMj8mx5ezwKXMvEA/1JxMNyYGfbZuF9APPTapteaKeqiX6kH3hq6RGvPpbYOXhIQB2IAw9qJObPzS+pmd0EIFlKSph7WV1QKZoyE/H3QoUk0PFPAndqjMlRSZlOpjrUc3lTXMG3HvG12G3LOq7MIdJVev0g9WD43lwjJ5h8txug2aaeGqg+tmSPDnoT7HQyiIewAIZzM1d4r6Wq9TBV76Fi6n0iu4k/DLAr94GttTpfBxqQFRDL6WGjk4fVaVTCDgwTCemp8zsHHVqgj50UnF/09+5q/MyMotdcFSwVQ5WyyB6XVRSWnbsruGIzU5tlxSnXWjqFUpsxUhhRiipZiu9q/LJntnSspkxrroFgW94Tp+/nPqJA== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Add safe methods for reading and writing Rust values to and from userspace pointers. The C methods for copying to/from userspace use a function called `check_object_size` to verify that the kernel pointer is not dangling. However, this check is skipped when the length is a compile-time constant, with the assumption that such cases trivially have a correct kernel pointer. In this patch, we apply the same optimization to the typed accessors. For both methods, the size of the operation is known at compile time to be size_of of the type being read or written. Since the C side doesn't provide a variant that skips only this check, we create custom helpers for this purpose. The majority of reads and writes to userspace pointers in the Rust Binder driver uses these accessor methods. Benchmarking has found that skipping the `check_object_size` check makes a big difference for the cases being skipped here. (And that the check doesn't make a difference for the cases that use the raw read/write methods.) This code is based on something that was originally written by Wedson on the old rust branch. It was modified by Alice to skip the `check_object_size` check, and to update various comments, including the notes about kernel pointers in `WritableToBytes`. Co-developed-by: Wedson Almeida Filho Signed-off-by: Wedson Almeida Filho Reviewed-by: Benno Lossin Reviewed-by: Boqun Feng Reviewed-by: Trevor Gross Reviewed-by: Gary Guo Signed-off-by: Alice Ryhl --- rust/kernel/types.rs | 64 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/uaccess.rs | 79 ++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 141 insertions(+), 2 deletions(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 2e7c9008621f..bd189d646adb 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -409,3 +409,67 @@ pub enum Either { /// Constructs an instance of [`Either`] containing a value of type `R`. Right(R), } + +/// Types for which any bit pattern is valid. +/// +/// Not all types are valid for all values. For example, a `bool` must be either zero or one, so +/// reading arbitrary bytes into something that contains a `bool` is not okay. +/// +/// It's okay for the type to have padding, as initializing those bytes has no effect. +/// +/// # Safety +/// +/// All bit-patterns must be valid for this type. This type must not have interior mutability. +pub unsafe trait FromBytes {} + +// SAFETY: All bit patterns are acceptable values of the types below. +unsafe impl FromBytes for u8 {} +unsafe impl FromBytes for u16 {} +unsafe impl FromBytes for u32 {} +unsafe impl FromBytes for u64 {} +unsafe impl FromBytes for usize {} +unsafe impl FromBytes for i8 {} +unsafe impl FromBytes for i16 {} +unsafe impl FromBytes for i32 {} +unsafe impl FromBytes for i64 {} +unsafe impl FromBytes for isize {} +// SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit +// patterns are also acceptable for arrays of that type. +unsafe impl FromBytes for [T] {} +unsafe impl FromBytes for [T; N] {} + +/// Types that can be viewed as an immutable slice of initialized bytes. +/// +/// If a struct implements this trait, then it is okay to copy it byte-for-byte to userspace. This +/// means that it should not have any padding, as padding bytes are uninitialized. Reading +/// uninitialized memory is not just undefined behavior, it may even lead to leaking sensitive +/// information on the stack to userspace. +/// +/// The struct should also not hold kernel pointers, as kernel pointer addresses are also considered +/// sensitive. However, leaking kernel pointers is not considered undefined behavior by Rust, so +/// this is a correctness requirement, but not a safety requirement. +/// +/// # Safety +/// +/// Values of this type may not contain any uninitialized bytes. This type must not have interior +/// mutability. +pub unsafe trait AsBytes {} + +// SAFETY: Instances of the following types have no uninitialized portions. +unsafe impl AsBytes for u8 {} +unsafe impl AsBytes for u16 {} +unsafe impl AsBytes for u32 {} +unsafe impl AsBytes for u64 {} +unsafe impl AsBytes for usize {} +unsafe impl AsBytes for i8 {} +unsafe impl AsBytes for i16 {} +unsafe impl AsBytes for i32 {} +unsafe impl AsBytes for i64 {} +unsafe impl AsBytes for isize {} +unsafe impl AsBytes for bool {} +unsafe impl AsBytes for char {} +unsafe impl AsBytes for str {} +// SAFETY: If individual values in an array have no uninitialized portions, then the array itself +// does not have any uninitialized portions either. +unsafe impl AsBytes for [T] {} +unsafe impl AsBytes for [T; N] {} diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs index 77957d7ec011..80f7e7ca2f5e 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -4,10 +4,16 @@ //! //! C header: [`include/linux/uaccess.h`](srctree/include/linux/uaccess.h) -use crate::{alloc::Flags, bindings, error::Result, prelude::*}; +use crate::{ + alloc::Flags, + bindings, + error::Result, + prelude::*, + types::{AsBytes, FromBytes}, +}; use alloc::vec::Vec; use core::ffi::{c_ulong, c_void}; -use core::mem::MaybeUninit; +use core::mem::{size_of, MaybeUninit}; /// The type used for userspace addresses. pub type UserPtr = usize; @@ -247,6 +253,41 @@ pub fn read_slice(&mut self, out: &mut [u8]) -> Result { self.read_raw(out) } + /// Reads a value of the specified type. + /// + /// Fails with `EFAULT` if the read happens on a bad address, or if the read goes out of bounds + /// of this [`UserSliceReader`]. + pub fn read(&mut self) -> Result { + let len = size_of::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) = c_ulong::try_from(len) else { + return Err(EFAULT); + }; + let mut out: MaybeUninit = MaybeUninit::uninit(); + // SAFETY: The local variable `out` is valid for writing `size_of::()` bytes. + // + // By using the _copy_from_user variant, we skip the check_object_size check that verifies + // the kernel pointer. This mirrors the logic on the C side that skips the check when the + // length is a compile-time constant. + let res = unsafe { + bindings::_copy_from_user( + out.as_mut_ptr().cast::(), + self.ptr as *const c_void, + len_ulong, + ) + }; + if res != 0 { + return Err(EFAULT); + } + self.ptr = self.ptr.wrapping_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. + Ok(unsafe { out.assume_init() }) + } + /// Reads the entirety of the user slice, appending it to the end of the provided buffer. /// /// Fails with `EFAULT` if the read happens on a bad address. @@ -310,4 +351,38 @@ pub fn write_slice(&mut self, data: &[u8]) -> Result { self.length -= len; Ok(()) } + + /// Writes the provided Rust value to this userspace pointer. + /// + /// Fails with `EFAULT` if the write happens on a bad address, or if the write goes out of bounds + /// of this [`UserSliceWriter`]. This call may modify the associated userspace slice even if it + /// returns an error. + pub fn write(&mut self, value: &T) -> Result { + let len = size_of::(); + if len > self.length { + return Err(EFAULT); + } + let Ok(len_ulong) = c_ulong::try_from(len) else { + return Err(EFAULT); + }; + // SAFETY: The reference points to a value of type `T`, so it is valid for reading + // `size_of::()` bytes. + // + // By using the _copy_to_user variant, we skip the check_object_size check that verifies the + // kernel pointer. This mirrors the logic on the C side that skips the check when the length + // is a compile-time constant. + let res = unsafe { + bindings::_copy_to_user( + self.ptr as *mut c_void, + (value as *const T).cast::(), + len_ulong, + ) + }; + if res != 0 { + return Err(EFAULT); + } + self.ptr = self.ptr.wrapping_add(len); + self.length -= len; + Ok(()) + } }