From patchwork Mon Apr 15 07:13:55 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13629529 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 E0006C4345F for ; Mon, 15 Apr 2024 07:14:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7094E6B0096; Mon, 15 Apr 2024 03:14:27 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 6BA716B0098; Mon, 15 Apr 2024 03:14:27 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 534DD6B0099; Mon, 15 Apr 2024 03:14:27 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0013.hostedemail.com [216.40.44.13]) by kanga.kvack.org (Postfix) with ESMTP id 2CD8B6B0096 for ; Mon, 15 Apr 2024 03:14:27 -0400 (EDT) Received: from smtpin20.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id F2404A04B9 for ; Mon, 15 Apr 2024 07:14:26 +0000 (UTC) X-FDA: 82010902932.20.AF3C810 Received: from mail-yb1-f202.google.com (mail-yb1-f202.google.com [209.85.219.202]) by imf17.hostedemail.com (Postfix) with ESMTP id 0E5BC4000C for ; Mon, 15 Apr 2024 07:14:24 +0000 (UTC) Authentication-Results: imf17.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=mcKcP5Fn; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf17.hostedemail.com: domain of 30NMcZgkKCCM9KHBDQXGKFNNFKD.BNLKHMTW-LLJU9BJ.NQF@flex--aliceryhl.bounces.google.com designates 209.85.219.202 as permitted sender) smtp.mailfrom=30NMcZgkKCCM9KHBDQXGKFNNFKD.BNLKHMTW-LLJU9BJ.NQF@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1713165265; 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=MhdlP5JlKNtstcGdifj2bRw8BnPpw/8WvVvi1+ODuPA=; b=3pWmZfMdYEjiOXlVFnxEbRrabRoOAWUs52O1/C0Sb8/ZC0rh6rJZ413S2WfbTFiLmJYTrn BfcOaOjXG/hIzDT91AkT83OPyvZuynBN3hd/Y0hDHyfUWZFSEIRMxNPFqJ+lzTs3tzrwZi +5iphbpqDSPaK6FUiReYg1Zo8pUp2eA= ARC-Authentication-Results: i=1; imf17.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=mcKcP5Fn; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf17.hostedemail.com: domain of 30NMcZgkKCCM9KHBDQXGKFNNFKD.BNLKHMTW-LLJU9BJ.NQF@flex--aliceryhl.bounces.google.com designates 209.85.219.202 as permitted sender) smtp.mailfrom=30NMcZgkKCCM9KHBDQXGKFNNFKD.BNLKHMTW-LLJU9BJ.NQF@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1713165265; a=rsa-sha256; cv=none; b=Lj/LzFR4x9HOPW+sZmvKlff7zfucsXdNyNFIX2UBNBGrTAgitc2AmElZt+H8+kIiHsW11k 3lqNaO0EkSQ6yAkuwdt3gRPQ048Tc4j8tsjV2+p5NOOCmHQVJmcBjxPp0x+FMuMUHvodJD xohIJlcjzVOTPJNnBhPtGEzFElKJ248= Received: by mail-yb1-f202.google.com with SMTP id 3f1490d57ef6-dd1395fd1bfso5156932276.0 for ; Mon, 15 Apr 2024 00:14:24 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1713165264; x=1713770064; 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=MhdlP5JlKNtstcGdifj2bRw8BnPpw/8WvVvi1+ODuPA=; b=mcKcP5FneBixtdJVY7GpCXNPK9ajWrk9YxvVHzUAKpLQCi+rKU5q5NKvn9XhMrrbCZ KR/eQg3jaU6DRNQWxiB7zJesI8c3ypko5aHJAK2eYVatX2JB3tScdAaUY1ofE6O47HIC nJjP9/HhJQmudbV34KlQkbH5ydjwASXc9PN7YhNXIrp74V0SZo8tG2H7V7cgBsY2RT0b onkORk13aDoEPnatU+1gBYxI0/fpBcjZ+nsLr6dEZZEPGoGhCwpS1wrwR1SOik1tC6qD UfyAJDvdlTxZqZuSDgsEsttah6nlwi2Qa6OoLPpKhL/farpVu37D+7BkFzeX4t6E2NcA J0sA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1713165264; x=1713770064; 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=MhdlP5JlKNtstcGdifj2bRw8BnPpw/8WvVvi1+ODuPA=; b=e9QqOYr7XCb0ubB5fzwvAejMRgqCoQZjCqCdUnCcOyDNJH49vceohR8N7Qq7aV0jkm Zp4ZCvBcf6ey4rdOVfOeBqu4YBqEGq4/RolWE2wMGcMn0uLgkisdZMuTk1QDbVp5Y1OD 66bdnZnLqEcaRECVPSpS/4x+iJkfsqgYbfq302jXthHCmhwa+mi4lMrriicNDpF+DtHJ ncH1LoMxkdEDi1hkpvtBALcm4qZzb63vdtmbhtfKiKQLN65SBrbl9dEw1LHXje/7wCEr GOlqo5dc8UEfXJUA2Y2bVfDRz9EbZcNJlFpglcjpo5xd95nFzyl+jNPl4Ej3uWHxpy6R BLUg== X-Forwarded-Encrypted: i=1; AJvYcCUYLBpJ6h9qp7hbowgYU9gBl/r21HYv680ElCgoMGOEcoD6uTs58kQlAXyKq71T+keskX6JabPXt8Gne8Uv4OIp3QI= X-Gm-Message-State: AOJu0YyOtXPxa7S/pXYGWViCTF2VM/jRMapn7MI15xzxqfZYbAalwIa1 jqXQTXUzEYOwGmAnoyYfv/sUQ41al8QeRkjHM4PMt9BPwCq8Av4dH51qvSHyMPfEwC4DRv766XR gf8syKjCOcmLbEQ== X-Google-Smtp-Source: AGHT+IHwi6w0lDXo5tZreR0tVkBy1RTj7mLjFE+yjLToXnPFfw726W8T3Ei3bLcl/Sjj7d4uVRnPuHJYNVD4lW0= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:1502:b0:dc7:49a9:6666 with SMTP id q2-20020a056902150200b00dc749a96666mr3155257ybu.3.1713165264142; Mon, 15 Apr 2024 00:14:24 -0700 (PDT) Date: Mon, 15 Apr 2024 07:13:55 +0000 In-Reply-To: <20240415-alice-mm-v5-0-6f55e4d8ef51@google.com> Mime-Version: 1.0 References: <20240415-alice-mm-v5-0-6f55e4d8ef51@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=8745; i=aliceryhl@google.com; h=from:subject:message-id; bh=BPvxCnQU8QVu2tTG/MzhVBESR9s1ykEepxIFWcgj764=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmHNPCpIenedGq5y7NqOIo3z3RQyWrBzGEt1gNy 6aXpXjCwQWJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZhzTwgAKCRAEWL7uWMY5 Rk10D/9rglwh8dFgKcRzxbw+8GX1BZNX08YZpvZd/17rL32smdZiZTKPJd75K2m/Uw2pN+V6Zmd UvNUMMkIUcPwF8PpoPJcm0hhQQ2sj1A2yS6Kcr2CXrGkj9E4xdH3I+2hY+6UQqiKXYHS13XwenS rSQ5sgsLOkGh3CgtKyd+52Dptr5ZdGAjugEmG5uP/m2ZwBX+JecqZcTCROMyO/mgZvD0EoMoy29 wLiOeA1yWDMq0+Tnm0xmUIgX3wmgm7kHxa0rnK1CMapZ7o/fwXC7BsDTiQTOlR9jgei0FBGeMVo wUbt7E9pHZMGIY3y8lIUxcrsu8fOvAr3FVAGazwWYIUCp5dB1JMZFQd3FWdMSFA+Ivbz//PS/XG sI/GrjEhtjJKAnmaoV5KlkXr0EvIZFEdFp+LU3T35weYFXrkaVM2Wz/HuTKoW6e+R7m2EZyRsks LF1s5nNZMpli7Aae4sXdVvkRrHtJP9adKd8cr7v9WtK7+VLE/K8uqbu264A/KUskT9wkFduxdbO 3SV3bWG6uARUGmgJLvJYoaCuQl3wS36vsQVeBlV/EJiYZvo7bm7I20ejyJuXFjH8cpNw6lrBL68 +JDQthtx6tOI8tOa2+Q6fZgRVERlT8kyZ5cYmtwEyTPq+Bvi2odqaqrtdV4Wn6ikMAcXyTI9RyK oSV1ESaJlxi79Jg== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240415-alice-mm-v5-3-6f55e4d8ef51@google.com> Subject: [PATCH v5 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 , linux-mm@kvack.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alice Ryhl , Christian Brauner X-Rspamd-Server: rspam09 X-Rspamd-Queue-Id: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/MlzW4 ik3uXdHT6raW6GTPSEqQ+e5RdMRBAybMOaeFqPEK/OedpI/AUlwqUnysoPry7ejFGDgYA/29g05aCCJYL6FwEwvHL0TM6W87VGMzi4cm8wGN+nP3Fg6+16K8h2AYso0Vqnl2BkiPdMfRFSIUNXLDRFOyWGhxDfDtheTvZ4tG2J45pO8F/BQTCmvj12kYuWyF0LfNDytWy7CFJIkrPLupQ8MEuSpMVulcsdo7v0P6bT9vTsOOuCAVvg1r1MiM3t9xz+jJNg7UiChnj3dwA4651b0MatP4zfQNYvSLc7C6vHmT9lgJWoTt2MRCYzzA99Ssuc0SG82PnZqxq//FO8RwAT/JC6DMfsdlYyYYmeQGdZ3ifAS37Ow/SbGYI8epWIqDUq40gVvsnlHpFzI0mDLHbt8KSEIVCKJGQH5vf8Nr+OKNzBfmAhdrwK4AE6YilH2QQny3P0B4EFI0bV+sxJztCB9edOZsQZuaQqC+fRqXSvMRoXJrHzcS1oyTFNJii713X0ds0FtEqMXvkSJj/JHMhLSXie4Xo1HxH2ekt48FkEys7oB29fr8JRkVei8QtX+xa39g3p1LLuTZndosNjpK6n6ulKZbnX+nnusscH9tp9yQCv1vCtf4yGWS+HQJBcVmbRd8s6hIGBNS/jPAb4acaVH6JZN9cN3Fq8iy4VmleUc/vSqh5YUtAL4vtvtCoFXjLCcuKk6BvOjXRf14em/c/j81MxFjOeLU5yaJe 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 Signed-off-by: Alice Ryhl Reviewed-by: Trevor Gross --- rust/kernel/types.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/uaccess.rs | 71 ++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 132 insertions(+), 2 deletions(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index aa77bad9bce4..414ba602fc5b 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -409,3 +409,66 @@ 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. +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. +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 c97029cdeba1..e3953eec61a3 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -4,10 +4,15 @@ //! //! C header: [`include/linux/uaccess.h`](srctree/include/linux/uaccess.h) -use crate::{bindings, error::code::*, error::Result}; +use crate::{ + bindings, + error::code::*, + error::Result, + types::{AsBytes, FromBytes}, +}; use alloc::vec::Vec; use core::ffi::{c_ulong, c_void}; -use core::mem::MaybeUninit; +use core::mem::{size_of, MaybeUninit}; /// A pointer to an area in userspace memory, which can be either read-only or read-write. /// @@ -238,6 +243,38 @@ 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 encounters a page fault. + 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, len_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.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. + 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. @@ -301,4 +338,34 @@ 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 encounters a page fault. + 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, (value as *const T).cast::(), len_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.ptr = self.ptr.wrapping_byte_add(len); + self.length -= len; + Ok(()) + } }