From patchwork Mon Mar 11 10:47:15 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13588581 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 D580EC54E58 for ; Mon, 11 Mar 2024 10:47:34 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 6290A6B0080; Mon, 11 Mar 2024 06:47:34 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 5B1E06B0085; Mon, 11 Mar 2024 06:47:34 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3912A6B0083; Mon, 11 Mar 2024 06:47:34 -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 2090E6B0080 for ; Mon, 11 Mar 2024 06:47:34 -0400 (EDT) Received: from smtpin02.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id B48E4807AD for ; Mon, 11 Mar 2024 10:47:33 +0000 (UTC) X-FDA: 81884431986.02.C76BCA7 Received: from mail-lf1-f74.google.com (mail-lf1-f74.google.com [209.85.167.74]) by imf28.hostedemail.com (Postfix) with ESMTP id DD9D8C0008 for ; Mon, 11 Mar 2024 10:47:31 +0000 (UTC) Authentication-Results: imf28.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=b7V94V28; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf28.hostedemail.com: domain of 3QeHuZQkKCPQWheYanudhckkcha.Ykihejqt-iigrWYg.knc@flex--aliceryhl.bounces.google.com designates 209.85.167.74 as permitted sender) smtp.mailfrom=3QeHuZQkKCPQWheYanudhckkcha.Ykihejqt-iigrWYg.knc@flex--aliceryhl.bounces.google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1710154052; 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=2c6bMPArnt8D9kdvoHKALHQQ9grE3IbZuTFkAk5bFxs=; b=IapgnA2AwCRHNA7lcwCKe5udKXh4vJ8HUTp8sqA4+5RyGvPX3s+k66A/R9otvD0/MxmJeC HpbYEZzztUG2/WUlxE69da00sQigy+TzEL83rKRfMCHiu4fIFY5Bg+qiTSY3sw+a7JUNur 5WyWPly0u5h/BiDzkLOdhBhNvE/uuF8= ARC-Authentication-Results: i=1; imf28.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=b7V94V28; dmarc=pass (policy=reject) header.from=google.com; spf=pass (imf28.hostedemail.com: domain of 3QeHuZQkKCPQWheYanudhckkcha.Ykihejqt-iigrWYg.knc@flex--aliceryhl.bounces.google.com designates 209.85.167.74 as permitted sender) smtp.mailfrom=3QeHuZQkKCPQWheYanudhckkcha.Ykihejqt-iigrWYg.knc@flex--aliceryhl.bounces.google.com ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1710154052; a=rsa-sha256; cv=none; b=E1E+YWvQM+86FEW6hFPmFuOLp1nfT/JE3RkLf+R1QO/ph9cfInrOCmuQB8nAGMBec86Abz bZFxuNByZLr4dK03NE7aVfsWLImiH88z0Nwr3gIenSiPmbaeScdwKMceVs+al5uXi76gK2 wG2A8DWJP+TyGRclP6iSwCJ6hnNeCa0= Received: by mail-lf1-f74.google.com with SMTP id 2adb3069b0e04-5131d042b1aso2149993e87.0 for ; Mon, 11 Mar 2024 03:47:31 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1710154050; x=1710758850; 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=2c6bMPArnt8D9kdvoHKALHQQ9grE3IbZuTFkAk5bFxs=; b=b7V94V288yXYtGQO1EcIxl9EUZ0+pEu9+I1u87Hhl/9wANXfdZCldT+sph38d9W07z hDhFxcnbkkVEpcElSnahLp/PLZmNtIgqa/kOpPc2VEIvWY898/Tv7yqHGns9rC2rGBTD KJJFb/PN+jxrQB6qMSk5oBq5xI36w34+ytZVIVSRHhNKJf7KGEyDg1b87Oxgq5nhosE1 SwmlshT3/hN5atMxzRHDW5/jBAke6hb8BicLk/oTE2a5DKiadfGUhh1xhvGo1jc2nPdB rGMMUWXkArtrbUnmZMi7x+U/dR8CmDZGOU8dH/XRCgbEly/5BNGeToMmq91saE7UOGca spCw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1710154050; x=1710758850; 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=2c6bMPArnt8D9kdvoHKALHQQ9grE3IbZuTFkAk5bFxs=; b=uCcsB6Ln70ua4+RF0QFxqXababuAsBHQxCOuPZf6UNCpT90SJoum5gB74oVvDJM8b3 FxXmPpqLHuf525c/leEor9IeWmX4GyqTfIuDmkwujx5DmB9mu1xHo742jFuXfJLlKBE4 28Rdpl8SF0fz5jTSASVpos0O0J6nVjJhGNVS0hs0xVQqAWPHkjSF4inwPBR3qLE7PD8c mOHXdhVc9hzNflF4rN+GSoBNl/1sqxxGmtaHdEOAqxk/TdV1DpxSKC82Pq/j0mJPtAbG /S6/UGcLChXfSzL58gZiUp6Nvguf1DlPlRNkqhaZDqUko0K7EtVL2JnhnxzkYkp9Uoiu nX3w== X-Forwarded-Encrypted: i=1; AJvYcCX/Y3oKnw5Ba6aFqtTrHhm6c8Wdu/Yfv0pO86Zsj6EkZWJtFB1gv0ieeimCK6KAecb9BrgBO9JFsHnB4zzEkBKAtgE= X-Gm-Message-State: AOJu0YyFMF0h8Bk/7xhNJ8Di/nAJIGHb7RDSYyVvQSIkqXSJBiMabK1M rlsR63LUOZPccG5TCbhjYoNvV9i3bQPKhGIJ+SW5isizMW4auZ3kgRAlVJifCq2VoxliuWaCneU bosXXSW8o6cpB9A== X-Google-Smtp-Source: AGHT+IF2Vt5V8eujOxNumBXozXKhQ/7eLs0zX0F5tRH0T9iuVNAdf86I2d84KVYWqXVZsAGntbB8mh+8UU6oXgA= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6512:251e:b0:513:b15a:c2b7 with SMTP id be30-20020a056512251e00b00513b15ac2b7mr610lfb.6.1710154049688; Mon, 11 Mar 2024 03:47:29 -0700 (PDT) Date: Mon, 11 Mar 2024 10:47:15 +0000 In-Reply-To: <20240311-alice-mm-v3-0-cdf7b3a2049c@google.com> Mime-Version: 1.0 References: <20240311-alice-mm-v3-0-cdf7b3a2049c@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=8715; i=aliceryhl@google.com; h=from:subject:message-id; bh=O8zC2lgk3iljbnvk5ax/PRPoOoGfwC7mnB92Tq28bps=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBl7uE0gI7mwBhBKAktav0IYVr2x44RfFVlQeCJ/ r5KHT4GM4SJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZe7hNAAKCRAEWL7uWMY5 RgDaD/9CIQWLbBRhAR+VU/Z4XfgkfK+S6xaMQ0IxoLJqhiaETkwMy/uyjInFXb6u7diGVZTH+9k du+csjmxKR4IFkHrC+1NSlR83gaONd+HvAsrt6cZLrmXvGkT0DssMzwlW0RG6o/cFPaQ+OaEl8K kWsSiIv9CkYMGvG93ScxhlagwGgyLrWQ6AYxuDr3W9Fvfqtuf2NIQ2K72VXUk2EmBE2b696F5h7 /M3NUihppcd/bjMJDlq7vxRZ/1msuLZTucpotKSoRYdGKhgLMetCWmZDWRDZFKXCFHqoxwOZ88e 0ChUkKfBrmf+XbhsNE2vO6cYbGElVfaVT+URBjbP4o876YOg8VAJIN7stWYWJA744W1dlQxi+9H Uf/5U2FIf3R4wwSFXfw9EjUFQyTrRio9xzEHgiFWg1USMdFmNXf7UTYyOmyPr3EHjxu5IW4V0S+ 75CFlA6FeNtV1opclUn/2ScgG7h2BeFPKTlur/eyYkEzGO/fturmuluG35NO+gOFe0STlw8HELK b1DpVGvIzBBzmymt4nOjuFiYlgZMjFYzn4nwL5l8UJn8j1j1OtCl1xZoZh1gtk1CV00GrcuEpq8 Qp68iEbRP8iBY8W5U1kNYAh2VgX5kmri2Sch7c6W3pp7GWgoGZ0DP/G7aPhQb86ZU6HEbEpoiue nrg/PIkXQyJQnvQ== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240311-alice-mm-v3-3-cdf7b3a2049c@google.com> Subject: [PATCH v3 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-Rspam-User: X-Stat-Signature: 7fos1a6dpzy47kajec6md1tis9bd7cps X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: DD9D8C0008 X-HE-Tag: 1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Nrmmgw7aYLpUgptoS9561dzeKA8pUJtsGTAiPJm+/+mv7FeCYsa5MSeEU5mtjfYk8l8bH8pxYZFGjryIe6rg0w3zS3rp/ADsdLigVSLoBbpv7wMDukSZ7msK37ZD4xSH+cUaHlPm+w6IukuVa2q/5aom1qiMMhcbq1Dy2rAn0K0pET8UR2nza7VLdcxqaVXFyGLCYwfS+hyF7Wh5EHFicWuoCS+xiZO+AOt8xvZaHJAs7L7gClTCsit86ZTWTySvdKhsm+4huYVqoZm6LUqCwTHTMLRxO7mjigwsHa6sYKnr2ADv5fM07ujIec3xkhZctu2NFt/M0vGpVi9860ixveMVh0wginKAZSY0fp293EwN4IS/FaAYe9sdB/Pc6+paNW4Szx 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 Reviewed-by: Benno Lossin Reviewed-by: Boqun Feng --- 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 aa77bad9bce4..f72b82efdbfa 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -409,3 +409,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 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 020f3847683f..72d55b2b33c9 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. /// @@ -312,4 +353,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(()) + } }