From patchwork Thu Apr 18 08:59:19 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Alice Ryhl X-Patchwork-Id: 13634365 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 D2BD1C4345F for ; Thu, 18 Apr 2024 08:59:43 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 643056B0096; Thu, 18 Apr 2024 04:59:43 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 5CC1C6B0098; Thu, 18 Apr 2024 04:59:43 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3D0CC6B0099; Thu, 18 Apr 2024 04:59:43 -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 1B2FA6B0096 for ; Thu, 18 Apr 2024 04:59:43 -0400 (EDT) Received: from smtpin25.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id C80A516109B for ; Thu, 18 Apr 2024 08:59:42 +0000 (UTC) X-FDA: 82022054604.25.10E9294 Received: from mail-lf1-f74.google.com (mail-lf1-f74.google.com [209.85.167.74]) by imf27.hostedemail.com (Postfix) with ESMTP id BECE64000A for ; Thu, 18 Apr 2024 08:59:40 +0000 (UTC) Authentication-Results: imf27.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b="I9K3XJG/"; spf=pass (imf27.hostedemail.com: domain of 3--AgZgkKCHgWheYanudhckkcha.Ykihejqt-iigrWYg.knc@flex--aliceryhl.bounces.google.com designates 209.85.167.74 as permitted sender) smtp.mailfrom=3--AgZgkKCHgWheYanudhckkcha.Ykihejqt-iigrWYg.knc@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=1713430780; 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=HgZdNi+a47HOfHsTxDpJlGILwCywia5g2y3UnrPe+eU=; b=pAJwx2MmIw6Jo1GhIe6v5g3Wf9Sg33pm29EMot+Acs7EHQLeANjuPVn+f/5v3Ng+3DQt+P lCQTQ6/i1d3M7EoM9KXhCwmNJ9W9IvjFViRIjGbly1F7qkLwHj8AwF3wRwx4xKy0VxRW+A LwI8bQRB6WkyGdSfsb09UBz21BONQpw= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1713430781; a=rsa-sha256; cv=none; b=iIjv5hbyK7IvRgbBJrrwG5ndtLVYeJzuu4W2haK5sQVMaR8QYMckrEA85d2Jfchw9br0eR kbNUixpPgh/WasPku5qSp2ekZ+vCWt4CNzvneN9rjCDQbPffozBZcOCdTSQNzbact9Vgga NzfS6JQ90JnopCjhQgdzTII8FZSJCvE= ARC-Authentication-Results: i=1; imf27.hostedemail.com; dkim=pass header.d=google.com header.s=20230601 header.b="I9K3XJG/"; spf=pass (imf27.hostedemail.com: domain of 3--AgZgkKCHgWheYanudhckkcha.Ykihejqt-iigrWYg.knc@flex--aliceryhl.bounces.google.com designates 209.85.167.74 as permitted sender) smtp.mailfrom=3--AgZgkKCHgWheYanudhckkcha.Ykihejqt-iigrWYg.knc@flex--aliceryhl.bounces.google.com; dmarc=pass (policy=reject) header.from=google.com Received: by mail-lf1-f74.google.com with SMTP id 2adb3069b0e04-5195b8410d7so417115e87.2 for ; Thu, 18 Apr 2024 01:59:40 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1713430779; x=1714035579; 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=HgZdNi+a47HOfHsTxDpJlGILwCywia5g2y3UnrPe+eU=; b=I9K3XJG/MAxtIrvVwBqlulygzGUo61+jVbcncKREy4DORYRHKJd8b/sm4XkMKL+lZQ us1ZZjtbQwYaPvo+ETwruxS6GwJ8FTrnNvAwDOrEE/EXwJ35GeNnZcTWK6z0at1cTq8v qli6lXliQQWjTFeCGiPZaHzBmrCvaDpIwWrWMpj7l5speM8UkDer3p7Nr6Ucg+He9rS9 vNHOsm5qd9aENg8LY0XGIQ9Q7PVpmUPBxZ1adsZYOxYWuu7yWPe44dpkHzDgMDKMAmmX JptaG/osFUHFJF51mA+aoeqW5A/LRs2ltd5tgHxs+YetpWTJpxKbFHOe5Mz11EaLP7qs s+MA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1713430779; x=1714035579; 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=HgZdNi+a47HOfHsTxDpJlGILwCywia5g2y3UnrPe+eU=; b=HWEJ10Rxe7nr7bGwSusOwIxIRpu4Wq0uGCPBYvkoCbLRTNRT7S4os5JIDvtkPzdyDY GaAQhbVRgq06+msXI5Vg7zkNNYmh4g/WefVdC5Ub6MX0UqF8wLFuGoQO50OblDAag2br oKrObJxoodeAbc3cgn2c3Sd+SmS0bxg5AOHkPIv6oGsqGe9p3/+ktQ8xJS4WRwnq5hIj AlYgqzDl5Cib1K8aGeFZ0Pmx9blKRCam1LLIMx7wWvSg+1grqLIy1D6y1QedmQBvvSwG HGEv96ksqAAwXmLCZYxFxYSwzVvzeKQ/AzJ38gL9re59IDmcRqbTbF4fWG5ehGW+A+KM dhlQ== X-Forwarded-Encrypted: i=1; AJvYcCUra2x0AXlDZ97ChjyYd9vrGDGY9f69QlMQi+8xurx62GyRfZG+nQjQ51Ry0FRva6WySJ6xcdjpzkdqjWzMK8yf9rE= X-Gm-Message-State: AOJu0Yw4xbVgZZBOmm3s4moGw6kqUpC0Ocbwoj5mOo9n4uBEhbWtrtH2 LVDYK20QobqxMq1eT3n+qa0TUgioVc7PKQQ6R+x6bZ/EAkU2GUWlzEDnDNXy0l+/ZZliN09erc5 cbRryID4jn+VQtw== X-Google-Smtp-Source: AGHT+IH6ScDtDrgw+IgQwpvtBZKJlRmNiyvFjb4gONlBnfX6IBw590w36dZkN+MXAX42+StYgo9t80UV0fKV/JE= X-Received: from aliceryhl2.c.googlers.com ([fda3:e722:ac3:cc00:68:949d:c0a8:572]) (user=aliceryhl job=sendgmr) by 2002:a05:6512:512:b0:518:bd37:87f2 with SMTP id o18-20020a056512051200b00518bd3787f2mr1938lfb.4.1713430779142; Thu, 18 Apr 2024 01:59:39 -0700 (PDT) Date: Thu, 18 Apr 2024 08:59:19 +0000 In-Reply-To: <20240418-alice-mm-v6-0-cb8f3e5d688f@google.com> Mime-Version: 1.0 References: <20240418-alice-mm-v6-0-cb8f3e5d688f@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=8978; i=aliceryhl@google.com; h=from:subject:message-id; bh=nI8Gb6Ut6mQQFRyrF/IoMMXllmm0f2L2teM9nYy0pQk=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBmIODvS6oNsms6X0YHcmuKs7EizEym1tAEymjog Q30/NA20CSJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCZiDg7wAKCRAEWL7uWMY5 RncsEACrSjtg5WqYkwrxGPaVxe3pCJO44xelyaMAJzezxUveUUN5hRIaFILfZELJj21aJsGBbVu l5N9yhyek7O3RPzQFGOzyapoR0QkuNWswj8JdEFq34/xHTp02Dy0WRmgxYUeIyQo+CkH+epFXbA yLxSgdLPnaqwYLFkJL6W5fwIbas8WiKJyS7u/Udsd+14bj2lHYAYCKosI5sSyJbIaRX4ODOrp9F BNHlogeI0A9yixFtpGGvN8z+kLxbDNafpriT58EFMWb5WmrXUjW6w+nxdvj3byMBWWqo3FxHHmt O80OQrBHRpoM5az1Xz7ctWqayHAL1Q8VsbQCu87jrGxP8BFwhvnYpHS1G9LtlkuBXeKLEKmlx+U D+fcJj9z/3j1P8biVsbOFvv/64U8re5ZdjqRyOqBygddDFvMEVkY9jW7n7Z3NtPyMuw8vQn8Prz DEAp2pVwpkf7Luo7EZhM431ixMB1xM1F0M9590356xT26n8/qycKA8X6ApHtnC30MoQLF8PXEte 4eMs4UvJmDodAIddQUXiz+Kj0FhmLVKyq85a2LEXuJuocTEzIoW7G1ytgOSkfmWFxmzjfa241x8 MrruNrGto/mokKkTJkN9fr0Yr5NZeVs2OmcAPCWihtjiUChNskjqHNalBFknaZUrbLknfBkVYee XKo2SmbVJZgp8vg== X-Mailer: b4 0.13-dev-26615 Message-ID: <20240418-alice-mm-v6-3-cb8f3e5d688f@google.com> Subject: [PATCH v6 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-Server: rspam01 X-Rspamd-Queue-Id: BECE64000A X-Stat-Signature: ja7jdi1i7c5c1915m83q7b8xd1yhp8ap X-Rspam-User: X-HE-Tag: 1713430780-167649 X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RU8RzHsoo5JOhh49cqfnjm8bhF5JYg5BBkhlGLF379xbWtvnPdGzbA0+vWQyoSr+q2WNh9wnMC7dnKC+xnLisN5nOxI22k5unkVUstn4x9Vp+MxZqSvGEMDq9wclbbGmdYkMWsc1j09lX2n7ninpjSXTnEeSFumfJsSYe/CtR68038B3f5xCUGzXUPZ2MqJ9nbfD7ZVnmLsa2yPFcyO0Gg1xQ9AZjO259p0All4MUnfoLteUT5kc8zdqLq0reGjoR0uH284BAuaLJ14FO1INsPZDXsbr4qJPTwSBzCmmzHaLEn+dm1EUyaJZGMigW4HxkhKg/b+DP1Y1jtIgBTaLIEtPa7rAXLHWbbGJZQlYHJZgfMrCD+e/tVmIggQCrS/CI11l0Y0lVyDVCwBFz4PJIgIY8aWpEJ+bvyDj+ZlialIhUM6aHIG5UEnn6yo63FpXWvATWW0/ofj61Azm+LlJ07j6SW9/c4grV/f+mDTzZfMJFYWmm0IfU14O43KOgiHsmRHlMhagLCcDMYySkJHCr0uxt8B/zH1LaV+FVseV7XGULoXcfSp9jdk9nqQMGKnIy/2rCtC2vsdXmul/Gl9frw0DWc5tSwXOGvyRTXiHJxCYCZ41YMDbrLal9k2X20wxerFFDPfv3DXFr57nggJyycLfsg== 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 Signed-off-by: Alice Ryhl Reviewed-by: Gary Guo --- 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 8fad61268465..9c57c6c75553 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 ee5623d7b98f..39481e374c40 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(()) + } }