From patchwork Thu Apr 4 12:31:41 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13617774 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 A89A7CD1296 for ; Thu, 4 Apr 2024 12:32:15 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 299816B009A; Thu, 4 Apr 2024 08:32:14 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 246BD6B009C; Thu, 4 Apr 2024 08:32:14 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 0C01D6B009D; Thu, 4 Apr 2024 08:32:13 -0400 (EDT) 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 D82516B009A for ; Thu, 4 Apr 2024 08:32:13 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 9FBB4120411 for ; Thu, 4 Apr 2024 12:32:13 +0000 (UTC) X-FDA: 81971786946.10.DB74003 Received: from mail-yw1-f202.google.com (mail-yw1-f202.google.com [209.85.128.202]) by imf29.hostedemail.com (Postfix) with ESMTP id B409B120020 for ; Thu, 4 Apr 2024 12:32:11 +0000 (UTC) Authentication-Results: imf29.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=ExQZeNXW; spf=pass (imf29.hostedemail.com: domain of 3yp0OZgkKCHcVgdXZmtcgbjjbgZ.Xjhgdips-hhfqVXf.jmb@flex--aliceryhl.bounces.google.com designates 209.85.128.202 as permitted sender) smtp.mailfrom=3yp0OZgkKCHcVgdXZmtcgbjjbgZ.Xjhgdips-hhfqVXf.jmb@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1712233931; 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=taakBWKWpiwoIIU3/+JYifQ+UJK0O86XOZIW+qgXD8k=; b=ShOQf/pg1hK2eMmQBxY9XpK9uWFZVJiT75P0rdM5PdMoK9Cy3HOdgM0kBiPJb/nPN1hG32 gxezPYjfw9hImfciaTlcx/rPEeAQPF8X3b/Pc+TetBmjPK4zWIsC0cUUez5cx2qs+S6tls WRAg9BsjOv/bz/G1dpONTbWw/9LJ2EE= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1712233931; a=rsa-sha256; cv=none; b=pJaCNwG11lmrWrnp3TKko+ABLegPOsK44iLLlrHcGxWu6hVUqqB2EOvNHnDexz3oJ754yU PMvLkyMjO8OZyiBd5RHGWlCorkKA1pvbgNAEC6QxcVhbMIRKDiRwQj4XkjLFemRHimbNvW S9vzkLfXy/SQC795N7OWOMPzr4uKHMA= ARC-Authentication-Results: i=1; imf29.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b=ExQZeNXW; spf=pass (imf29.hostedemail.com: domain of 3yp0OZgkKCHcVgdXZmtcgbjjbgZ.Xjhgdips-hhfqVXf.jmb@flex--aliceryhl.bounces.google.com designates 209.85.128.202 as permitted sender) smtp.mailfrom=3yp0OZgkKCHcVgdXZmtcgbjjbgZ.Xjhgdips-hhfqVXf.jmb@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com Received: by mail-yw1-f202.google.com with SMTP id 00721157ae682-60ccc3cfa39so14690727b3.2 for ; Thu, 04 Apr 2024 05:32:11 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1712233931; x=1712838731; 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=taakBWKWpiwoIIU3/+JYifQ+UJK0O86XOZIW+qgXD8k=; b=ExQZeNXWJmWWJEt3B9MSZbZ7R4VTel0hPBW0DueEuWXXKlkJMFhYh8Z/j3OCjfiUTh XGm4veaNGBDJJUc2gAmntPPANoEJ33fpE5aFT/5uV8YctaXx9T2dD4WOZjP6HmrvV8T2 iI0zDqpSBaXfWrPboFwq/JCmogKf7lydMhEZl7MJGgdPca9cSTek/1m3D+5uu8FHKZDk dtd+uc9AoBmP0gQ6b7qns9rwI80uUaFoBymmvYsQu1+90n3PS/OwsrOz6oQki2/V0SnL F1mZ/43YET7gIcobo1IKll196EqPprHj9yA52OJLquzUIMQT/YD/ptACsCEX5dWWGnPn R4Ww== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1712233931; x=1712838731; 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=taakBWKWpiwoIIU3/+JYifQ+UJK0O86XOZIW+qgXD8k=; b=NS4le5WyfLG0LfAHAdqY6RpcbyENWnkx4mqNR96nBbuF4yedbqrCQk4X/91FHeyu+F ibGLC6eh05MfCfKDUd60TltWC31qPk0vSgLZc08rxoYQiHoOAY4NJSqFKU8mcozbAh4x 9xQH6V8QEpPoxzwOJT9IDJcN0J9QWgQugkMKHP7/7mBksYeKV5LQ6Qw+vWAY7bdOsFmQ PT75zIIjRokuwIJ+c7QuWbXqljETGK068qePvVKDzl1ojnFeGggtk+2SCJTbZ6jC1sS5 Dztce9dQI9Qk9JNDV1+zRzZvGsGmBlIn352ykxKGOKPZ8mhrQrc+snnRL6Wl/HkbG3SW bWfw== X-Forwarded-Encrypted: i=1; AJvYcCWlKG2gsPORB0+8MagfHMReJ6f7T5EEGNyxdIKAK8LAWLNo2TkRuiVr1i7rs0g71ROSpE+olZR4jbHxKbILXiWWPJU= X-Gm-Message-State: AOJu0Yx+3r8F/45+7N2lGSwsxzIKjn82cA+lKCH48T/luPe6d9KuGut+ 4AmqGhPrxiUjsjNCU9CKm5hr0xJi8ZBOth+1+/xPQxs0QtnZVPluJI45cnwGNy97v0oiZFtWwnu dXgTme8e0BBoifA== X-Google-Smtp-Source: AGHT+IFmI9GK0405EKKeFUihI1V2MMV978wCRRUD+IF2RG+iw2g50ENG8068UenBApb8aTochDt6fXyIgyqbaIU= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a81:a0c6:0:b0:615:36af:1997 with SMTP id x189-20020a81a0c6000000b0061536af1997mr657526ywg.1.1712233930863; Thu, 04 Apr 2024 05:32:10 -0700 (PDT) Date: Thu, 04 Apr 2024 12:31:41 +0000 In-Reply-To: <20240404-alice-mm-v4-0-49a84242cf02@google.com> Mime-Version: 1.0 References: <20240404-alice-mm-v4-0-49a84242cf02@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=8776; i=aliceryhl@google.com; h=from:subject:message-id; bh=UiZpIf3BFNfRYXQgX1pbRbLKUYIHeSA1dkwNj3p46PY=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmDp2+LY7YpSqabe2ORUZvWo4bVNMZVV5WG3R5Y mu1KHdru/OJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZg6dvgAKCRAEWL7uWMY5 Rg/hD/9idXpq7JAUwrsPqCMHE5ebfdee6X+qjWYNVVMCWAAHPuysFc6BuRDOAS3ksrtD6I64Hdx 0SzqKoLWlb5G84cPRR3FsBvS9LZFniXIOnGP89k0MzHz4LCLcgAzuSZR+8nWh1P8kikjfhh9XDM bIWO2k3E02cCC1VRTNmUWEv1dP7BrbQi6KTZWo9JrlqKuAaYH850u+ULTuThr4fL+Ht81FSKiw6 Z4pBcshiar3zqMhPz1UUyMk/oFXv0nGcmfkp+hRKzAgoWf6dEvxs+2IB/x1i7lm1DrhhIqb2U3F kjheC6V5Y8QcshSdG7ezsMEsLByCbEgrq2jQ3Hk3Hd48w869oYE0COHGY6cMHt5S619qGi0TV3r xnKuoInK826bagIN4wbiDkFKzfImcdzZ0+3AwdKjoUfrX8rQdwtBZ7N0N2/OQdNJnjJiGIUiJx/ q99e8A13V4pcSappEdzwx7wc6TzfPwDI95gpDV+6n4DF/I0WiPOVpdO8vYZhY3LQfoZqWopPS4N ruTmP8hGyabWfrAD0Ja82KS+WKqXuHFPQuuOnpqUQiYX+f68M4WJ/oTzC+Cpy+61hKIpC8Y0RVB ZCzUv+hAM1RIW280T6WS1qMu3Qj9oSrVLjpmlpGcavdbg3jbArrgOsMCpCFkVE3JRdu+mbqVW4S /wWNwuGpAnPGO1Q== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240404-alice-mm-v4-3-49a84242cf02@google.com> Subject: [PATCH v4 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-Queue-Id: B409B120020 X-Rspam-User: X-Rspamd-Server: rspam11 X-Stat-Signature: 1thn3wic6c99puhjm3phxdyyo6fp7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/ec3agqXLWYb4xdlUVLsCjAi+Hxp8PtpTLT8X2/zhc00AhJHRtyQZTMHUt52hMdvVKCbtppqGpvtX8K1aa2BuwRpt9CuxIcJizV+owF8sKiaQbJrrIjS4bp4DrP6FwwpX9BXm5mzgLFGwmrsaIdEwsFWb60GChf2iPPKstFCiG5fa4vh/UyAIUm+gqBS9wVUG4mpijBVdLHN4nUZBiczFV0I4eU8NNowh+QNk7IkYOMvsPqN/AyTBBrSelMzk0nETdhFl/nK0Rl4OV/oQay31zgsWnVZiwxRlprD3c63jWkXpcIy4EPC8ePDgS2hCD2Ipl66WuW28lDbyT2WiK2+6kagVgLzZZ7+Q5ItZSN/K58qyTIh1iGFYUTbQqiUUuooKrJUfkjmrfl6+4oX10DOrMcmUpNmjhS6x5wGfPKKRbzp5ZYK1Hd5Gf4Cz8/2h/7DE0AyKtV5Y4AYUk+nTJ1FRjBBbe2RMGtLTUoUmrhCjjOgsyBhpdU+E4hnXUlSVqre5hahw0qXnCEXJTGvvv3VNyO7KvoeTxF/g0vv9oTqZF5lBi5ItssKjTqX7mQHW45+TeWQkHCc3cFiwAGZLZH3b7DfUQXFmNEf7EUeOh+nrogVY6oBXWZX2mpd+0OPZtswnu+g4XDw1V0mBgALfdNb6WQAMKzqFs165S2zbDfANSbZrsMWIsed9 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 --- rust/kernel/types.rs | 67 ++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/uaccess.rs | 76 ++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 141 insertions(+), 2 deletions(-) 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 3f8ad4dc13c4..6566b8cc2541 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. @@ -246,6 +251,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 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. /// @@ -308,4 +348,36 @@ 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(()) + } }