From patchwork Thu Feb 8 15:47:53 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13549983 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 40456C4829C for ; Thu, 8 Feb 2024 15:48:52 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id BFD6B6B0083; Thu, 8 Feb 2024 10:48:51 -0500 (EST) Received: by kanga.kvack.org (Postfix, from userid 40) id B88036B0085; Thu, 8 Feb 2024 10:48:51 -0500 (EST) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 963C56B0087; Thu, 8 Feb 2024 10:48:51 -0500 (EST) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id 7F7916B0083 for ; Thu, 8 Feb 2024 10:48:51 -0500 (EST) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id 3EA69A0F51 for ; Thu, 8 Feb 2024 15:48:51 +0000 (UTC) X-FDA: 81769069662.10.76F7433 Received: from mail-yb1-f201.google.com (mail-yb1-f201.google.com [209.85.219.201]) by imf11.hostedemail.com (Postfix) with ESMTP id 584964001B for ; Thu, 8 Feb 2024 15:48:49 +0000 (UTC) Authentication-Results: imf11.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b="e0/Qz4Jv"; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf11.hostedemail.com: domain of 34PfEZQkKCBkzA713GN6A5DD5A3.1DBA7CJM-BB9Kz19.DG5@flex--aliceryhl.bounces.google.com designates 209.85.219.201 as permitted sender) smtp.mailfrom=34PfEZQkKCBkzA713GN6A5DD5A3.1DBA7CJM-BB9Kz19.DG5@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1707407329; a=rsa-sha256; cv=none; b=NCGdO2oV0F1tgZfsjk225FOwUW1xDsp5OSg+5FLUKN7ae1Hdvuaer/QuDZo3lD3WJ2UAuH 0Y5FdWiCUpAAHxSw+TdMO6NRLQbx716125FkorB4Oahhj+zr/DbtNaJKYDYZGTyY8MxBEI 65hgtyW3bD4316PwUx6fyBLNyhMivK0= ARC-Authentication-Results: i=1; imf11.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b="e0/Qz4Jv"; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf11.hostedemail.com: domain of 34PfEZQkKCBkzA713GN6A5DD5A3.1DBA7CJM-BB9Kz19.DG5@flex--aliceryhl.bounces.google.com designates 209.85.219.201 as permitted sender) smtp.mailfrom=34PfEZQkKCBkzA713GN6A5DD5A3.1DBA7CJM-BB9Kz19.DG5@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1707407329; 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=flngb/LA8uzIdl5igbJEwBtu/PZHJPBIGQxF8CY4PhE=; b=XwSZAYjDMkzgJgB1SvXW0A/Mel9oyfRBHamX9SOOxpLIPK4x7xbcPTPu3wqYESx3vPU/WT eHCgQHdPGaMm41w67P6ORXQEbyN1W6b2sJuUvU3sLov07/xJNT8jeJVkzKXXZfrrw+kl97 eXee9f1lKoRL525GLixKdtVgI2C4U2c= Received: by mail-yb1-f201.google.com with SMTP id 3f1490d57ef6-dc64b659a9cso3506215276.3 for ; Thu, 08 Feb 2024 07:48:49 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1707407328; x=1708012128; 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=flngb/LA8uzIdl5igbJEwBtu/PZHJPBIGQxF8CY4PhE=; b=e0/Qz4JveqDRf8LzupWNsmg1wTxfDcgUZ6O20Bs4Ln3Lkxt/928DG3wnO13qlTYQY1 X0MJKEfjO5JVMroWlptlRoKE0aKwN3vzJobLbmdQHS55duCcDjFhVL4XmZJ9GafL23Nd 6lVYLOALoa1T8EeRK30CeH9iyFrwIoUEZbwjBtn6KI+4exY1ryADlUZBXciSEEV6UD7y pUBtzDGmBFdgFJDMHZYb8BiETrPgGbWaWH6pMZ9/5tFF3FJbS4XxE7dWVkacJSmShhTI GkfmE4f0tZX/18NenLye+eL9MJyDh9h5VZEa/wcsFBU+l/mvKGbTMG2HKE7tdzh19ymk vh4Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1707407328; x=1708012128; 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=flngb/LA8uzIdl5igbJEwBtu/PZHJPBIGQxF8CY4PhE=; b=s8R8WbBmpXr/+bR/G+GF/f1pHdyOaq8EGrPhV4KJGiJnFBTlRkHgDq99GTPK8mGLqP YUSdDUx8K58xWhOjF2+P303ajPMAGd9jA58/C7zbG6lOUmfYD619IhJhhkJXRtPcLeD2 JRTLayXkobEV0/hGzjkac+8LA/EgFqg2GoZLhN3+4aIz3OjbvV0RMrk8MbDVeyMgnBFz RRYwX8cmQRGLCg2UjrBLjERXLferAyypkeITxDfIhEa4Nj6/i0Co2CsYglLI1N4pzn4X U3S/vZxlTO+xgDyVbk6pfB1IAPTsceyLpaVp3QonmCxLlsZUn3XEqLvXYJZUWnBjMeiJ 0ryg== X-Forwarded-Encrypted: i=1; AJvYcCVt7Cd+bOLAjvsBGsqHK+MXm1xwbsr9i3HhkFlb3R2tsg+YF7HCk+YEccwji1ZAone3WJbhf3qA5++if/nqu91PE7Y= X-Gm-Message-State: AOJu0YxN6zVgBWBGWHG5CdDKwv8M6Aix5eeiX6kh177CsJV05z91zahn eJ2r5roAyFBjx+DLxY1rKy5lW1J3xtAGKqxJ//Pzm6rsai3hQVGkV1BSQP+X/dB+jbR8qaLt8yl 4PneFxuSTcTTFFw== X-Google-Smtp-Source: AGHT+IHMYibPwpZ1RVGfZRX8AKyfUjB+V8DP1294a1PT4LdcHAG0vKr/hwfx2FdORpWP56VfcaTlftChXStJdqM= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6902:2186:b0:dc6:eea0:1578 with SMTP id dl6-20020a056902218600b00dc6eea01578mr2142900ybb.13.1707407328528; Thu, 08 Feb 2024 07:48:48 -0800 (PST) Date: Thu, 08 Feb 2024 15:47:53 +0000 In-Reply-To: <20240208-alice-mm-v2-0-d821250204a6@google.com> Mime-Version: 1.0 References: <20240208-alice-mm-v2-0-d821250204a6@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=8719; i=aliceryhl@google.com; h=from:subject:message-id; bh=0g42SIX3ikqPGex8zhN70IRWhPIkHg4UCYLIFxFrPfU=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBlxPfTuOB96U/Lj40fHe9/xmDSElLomqfJO0cdJ oS0DmyNDKGJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZcT30wAKCRAEWL7uWMY5 RhsAEACE9BLmNvDC79FcWLHl6NT6PpjTFGYzMx6E6caaaLeVuWDJ6hhRZ+WM5x1fY68NMh4jTze sSCcxDNl9i1VJtQx5DN5Dvxw8ZOheHmix6sYH2u6nzHLQB+ka5eT56u/j1JvtGhjDE+JN/FtLLi Ku7kHIhYAmrNWQ71Ccpdl9TmLyg9b+F3CewVZsPpMR8BiA7M8IMyElJgb2Qy8QK+2UyagQNkNck vUAOTl7XVhllYkzh7aNkH++irEYMD7l1Pzq6i0ark1Oh5QLENHbz6p9GrtKtibC8Y31d+5ahqGQ ofpIQmg4DLhYUbcdbSgHuvaSvA2aNvb3I4hI/CHF3ItH5GKHeZ1II37sZzwtQIDhW/jx3tI7cM7 8fyu+b1eAvqo91GJyU9GKh6nyq+s/ft37vk5y7EsOCZVStX5wJkMW/fhvtHOQOQhIYU+yta/+3l gstUIDdyj8IP4sslt6FxHuMV/LEvQYzA/gw6mcz3plT02alcLP8CCjofOcmuw2A0U4BQkqvt4vf gdBiHa/nU9fHplEV10UtrZrwIchhpw29NoAzW9Log+xqOYBfvEJED/LBawfR0KQXivClAID7XvG 9u9w6oeJ6ZDYHCsI/brqznI4Um6gkWFG6YsPqFD1HyYPlG6VCo28FcfELn8as/Nz5rkkkTm8zjW 7WgDIC5F4sLMOdA== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240208-alice-mm-v2-3-d821250204a6@google.com> Subject: [PATCH v2 3/4] rust: uaccess: add typed accessors for userspace pointers From: Alice Ryhl To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , " =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= " , Benno Lossin , Andreas Hindborg , Kees Cook , Al Viro , Andrew Morton Cc: Greg Kroah-Hartman , " =?utf-8?q?Arve_Hj?= =?utf-8?q?=C3=B8nnev=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-Rspam-User: X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 584964001B X-Stat-Signature: q53x4xdgoyi6cgiuj4wpfsoq7xymupc3 X-HE-Tag: 1707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ZdyQLVQK2Geckoo4CMSwNSewWraXLMPm3uXWPMOBKqv7VKS2UYac+NziF2a3WrkuWSpo5DWHCeMSa+RaBG0bcpN61HxPqUPuysBTeuDw6nF+gU3oU/ulkIOEppaQ5oT2SrRWRVibAi+1bjSUbp1MXr1bYtPCUiU+k0808Hm17Iqv8TKbF9PMHKE11hsaRL0D814wzJMPmgz+whjEXSYIKhWPTKMby65nbzzNWA4IuEWOlfQUZs1ijoLQD6InqGLDcPn6Yjbpwa7rzIQ6db3nxKPn490UtFxrEEUMMZxTjg3iQOHJQPj1eL9KIFs+9FTDOc5hXIPHTyax2/OBO+7wizyDb1rjMZRuDj+NMXLigajyzepYmjlI0oRlDLMzVgqctgNbCPmZh6OvJeAZLzZ1Wf/KZRSMcaQi24qGbNQM35V3ZlySj/Puh+VzyOiE+RCCjB0SOsF/4huM7GaM53FgTd2t+LxOJMyBHBi1sieYBnBXkXIz7jbmSSe3ur1AkdLve6wEzfkvkctz+PMtgdyo0NmxqDL6Vox6sLfVRQ+oiILQ3IACmGG/ClTsQfdP7jfNq8ugD+ITFqUgQFWskl0X7oUzarJ+LmKcnuxMfnfM9KY6z8kfViGt6NJkEEjX5nzJhJuYxPXP3HMRC89mH2yBpqBaCKFGe6VMx 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 Signed-off-by: Alice Ryhl --- rust/kernel/types.rs | 67 ++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/uaccess.rs | 75 +++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 141 insertions(+), 1 deletion(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index fdb778e65d79..33d175a3a6ed 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -387,3 +387,70 @@ 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 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 f07821184bd6..71a00177a4b9 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -4,9 +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::{size_of, MaybeUninit}; /// A pointer to an area in userspace memory, which can be either read-only or /// read-write. @@ -237,6 +243,41 @@ pub unsafe fn read_raw(&mut self, out: *mut u8, len: usize) -> Result { Ok(()) } + /// 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. /// @@ -311,4 +352,36 @@ pub fn write_slice(&mut self, data: &[u8]) -> Result { // `len`, so the pointer is valid for reading `len` bytes. unsafe { self.write_raw(ptr, len) } } + + /// 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(()) + } }