From nobody Thu Nov 5 07:32:38 2026 Received: from mail-wm1-f47.google.com (mail-wm1-f47.google.com [209.85.128.47]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2B815282F05 for ; Fri, 3 Jul 2026 03:01:04 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.47 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1783047665; cv=none; b=NCYo6t1FXOQvB0Eflte6nXeYAilUyUL3Y5eRLsGeQnFyRi2lxZgZaVfkFxG8RqPCAqwcEjMKTD3u08J5BjTYXnP705qhD+V67Ys0XKauKZIpp/1ZXzcHMl1JFBKH/m/UbEPq6tAD7n9GkQTRpQcZsGp6qMFYstqKzYo5nUm0N6U= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1783047665; c=relaxed/simple; bh=JcssajxRi9PNX78hwKD3nC3DUtxZW5CBP4nY1hEy3WU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=Umpn/gy9u6kbchIHARaHk0qxLi2kI0vLImwK4mVolnSdL07FA3aFO6oHjNKpzut8T80QC1Y3/Vj8kiIKSMyhtguyI92r/R5COQAA8V2xFGKnVgaeW7KrYL49vznT0zSN42jVbBqKyDdd9dq7u8JmYVvpSOplMi6ZDqKjDlUTsi4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=fireburn.co.uk; spf=none smtp.mailfrom=fireburn.co.uk; dkim=pass (2048-bit key) header.d=fireburn-co-uk.20251104.gappssmtp.com header.i=@fireburn-co-uk.20251104.gappssmtp.com header.b=ADeFgD6m; arc=none smtp.client-ip=209.85.128.47 Authentication-Results: smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=fireburn.co.uk Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=fireburn.co.uk Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=fireburn-co-uk.20251104.gappssmtp.com header.i=@fireburn-co-uk.20251104.gappssmtp.com header.b="ADeFgD6m" Received: by mail-wm1-f47.google.com with SMTP id 5b1f17b1804b1-493c2b3dc8bso341555e9.2 for ; Thu, 02 Jul 2026 20:01:03 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=fireburn-co-uk.20251104.gappssmtp.com; s=20251104; t=1783047662; x=1783652462; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=AHdvnoaQNk7ls45hnvahZXx3/d9yXQUlDlEG/vvXbjU=; b=ADeFgD6m3ecRtaSL3WIRUFFK3v9yuAeYxyudJ3c/Cq/4DCddXFLJM2KC1VFozOVR/k 8Y7ZT94GuC3mGVDX9BB8u60uThznVnNajB0boWn3mCW1wvJbexmFqK26XYvaCvaQb0Cf Yqa39CL5/EiYzGa6jpK2oE1PXLFVCGofw/inNaUpOOB27AnODqctEYGVRWMwcc9rpvzd 3lr4EpEMxLjdP0i7O91/lFXhORFa2QVK5vCASvOTTeym3/uaOa9zWASSWDcjGvbcn9bL L8cJIqJ0pNM6dvOs3c16wE2BBxuh8v0AN8Xt+p+NVqRp32e/agWV8K3KrEIl3tTwQoqE HYcg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1783047662; x=1783652462; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-gg:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to; bh=AHdvnoaQNk7ls45hnvahZXx3/d9yXQUlDlEG/vvXbjU=; b=P0+k6CJ6kYBfOtCb0RkTSwRfANXNj1/Mi+q9LVYxz97g43fgfuIbm9/rKvAU3honuO FoKdmTBjmRSmITEBMOxVruXZKgYATbqfJs7vc8NYpgCpbjmvNrhDSpOyIFpMfsLqmfYk G/zpiFU35qDhX5Esf/jl2WvGOmNIQ8dMm36FZVsnJJFbdf5X9TYQYan3/cBErWZuiXed X9ZQlxv3FKA0hVzuVcmEIJlGSukXxcCwMGYUmtsAB9SYgTp0BfSFIk43CYdA3tzpfKkN JHJKaUFPD4etOfU/1AVo815UAgE53f9nBRmY2TZBAkvoEEeXCQ0fr2860N+4+Yo64uvM nH/w== X-Forwarded-Encrypted: i=1; AFNElJ8GHsrkrwMm8FJNTlLcN2U0JVQkraH41KZB8GT2TeyHzH/y1qIPzgZEiT3fi3ojg8OT+jIVHXgmJEoz7OU=@vger.kernel.org X-Gm-Message-State: AOJu0YypwLjqV3pMTKudWoReDDq/Rqrjnp9S3hZ4UtHGWsoPyFWI1U2/ mPZibqZilNRaeE14e5z2Ihx7udUVLDWcgKxtWAl0HqrNjlQKuQY9CZw7clA39gPdJg== X-Gm-Gg: AfdE7cnWJDrn6RA6epGtHuFlCRqkf1Nn7UsaDOg6eydqUy9aZ6irBFawP0EGATHcQS2 /vTPXhzRwDAbPSOxlhI6xf0WwiJJ7UDiCvV9VLfvc/Hh6f853yMPyhyGCcHHsV4f8uxrG/MlI29 gGkE2a6yxfw/7sUjKo9x4hvZY2s5fA0Kt/QPFAQf3GK+Az++OXqFMLYX3zTY7tBZzykQ+qS5t2k 39NudMaHvib8ZB7FGSbkLpCv8QXjOAH2WngTefCuaVD6UpsfYjQLDlnJfj7TWR70+Zrb+60kChT Y3zBnssSU6TEro1LgFS+mF5eJWaSMjc4O7UlJmT88Xqr5asBMxeqThd1fC7aUw1UFidV3297xik pcDTAK3ivaJGaEjxy7/g1T2Kb6uM+8qpFr4s/a9o91r2bJ4Dh1bWyHsIniEhJgDin2cY///4Han 3YMnxTUK7Sw7r6OwXGlt5pMPWEolxel0rv8ertdOfPiGDs0DYhHOCguiTKvOUACIVFRos= X-Received: by 2002:a05:600c:8590:b0:490:9588:bdb6 with SMTP id 5b1f17b1804b1-493c2ba43a2mr103955105e9.33.1783047662567; Thu, 02 Jul 2026 20:01:02 -0700 (PDT) Received: from axion.fireburn.co.uk ([137.220.119.72]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-493bef183e7sm199495015e9.2.2026.07.02.20.01.00 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 02 Jul 2026 20:01:01 -0700 (PDT) From: Mike Lothian To: rust-for-linux@vger.kernel.org Cc: linux-crypto@vger.kernel.org, Eric Biggers , Herbert Xu , "David S. Miller" , Ard Biesheuvel , Miguel Ojeda , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , linux-kernel@vger.kernel.org, Mike Lothian Subject: [RFC PATCH v2 1/3] rust: crypto: add library AES-128 / SHA-256 / HMAC-SHA256 bindings Date: Fri, 3 Jul 2026 04:00:51 +0100 Message-ID: <20260703030056.2763-2-mike@fireburn.co.uk> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20260703030056.2763-1-mike@fireburn.co.uk> References: <20260617150143.2152-1-mike@fireburn.co.uk> <20260703030056.2763-1-mike@fireburn.co.uk> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Add a small `kernel::crypto` module exposing the kernel's synchronous library crypto (lib/crypto) to Rust: SHA-256, HMAC-SHA256 and single-block AES-128 ECB. These are one-shot, allocation-free and run in the calling context, suitable for in-kernel Rust users that need a hash or a block cipher without the full asynchronous crypto API. SHA-256 (`sha256()`) and HMAC-SHA256 (`hmac_sha256_usingrawkey()`) are plain exported functions and are bound directly via bindgen, so their header `` is added to bindings_helper.h. AES single-block encryption goes through a `rust_helper_` shim because `aes_encrypt()` takes a transparent union (`aes_encrypt_arg`) that bindgen cannot express; the shim also zeroes the expanded key schedule before returning. The Rust API: `crypto::sha256(&[u8]) -> [u8; 32]`, `crypto::hmac_sha256(key, data) -> [u8; 32]`, and the `crypto::Aes128` type, created with `Aes128::new(key)` and used via `encrypt_block(&[u8; 16]) -> Result<[u8; 16]>`. Signed-off-by: Mike Lothian Assisted-by: Claude:claude-opus-4-8 [Claude-Code] --- rust/bindings/bindings_helper.h | 2 + rust/helpers/crypto.c | 25 +++++++++++ rust/helpers/helpers.c | 1 + rust/kernel/crypto.rs | 77 +++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 5 files changed, 106 insertions(+) create mode 100644 rust/helpers/crypto.c create mode 100644 rust/kernel/crypto.rs diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 1124785e210b..14671e1825bb 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -28,6 +28,8 @@ */ #include =20 +#include + #include #include #include diff --git a/rust/helpers/crypto.c b/rust/helpers/crypto.c new file mode 100644 index 000000000000..dc9614f6fc8e --- /dev/null +++ b/rust/helpers/crypto.c @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include +#include + +/* + * AES-128 single-block ECB encryption: out =3D AES(key, in). + * + * A helper because aes_encrypt() takes a transparent union (aes_encrypt_a= rg) + * that bindgen cannot express. SHA-256 and HMAC-SHA256 are plain extern + * functions and are bound directly. + */ +__rust_helper int +rust_helper_aes128_encrypt_block(const u8 *key, const u8 *in, u8 *out) +{ + struct aes_enckey enckey; + int ret; + + ret =3D aes_prepareenckey(&enckey, key, AES_KEYSIZE_128); + if (ret) + return ret; + aes_encrypt(&enckey, out, in); + memzero_explicit(&enckey, sizeof(enckey)); + return 0; +} diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 998e31052e66..4f8a1d6d129c 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -56,6 +56,7 @@ #include "cpufreq.c" #include "cpumask.c" #include "cred.c" +#include "crypto.c" #include "device.c" #include "dma.c" #include "dma-resv.c" diff --git a/rust/kernel/crypto.rs b/rust/kernel/crypto.rs new file mode 100644 index 000000000000..c8f2cb994cfd --- /dev/null +++ b/rust/kernel/crypto.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Safe wrappers over the kernel's synchronous library crypto. +//! +//! Exposes the one-shot `lib/crypto` primitives =E2=80=94 AES-128 single-= block ECB, +//! SHA-256 and HMAC-SHA256 =E2=80=94 for use from Rust. They run synchron= ously in the +//! calling context with no allocation; the hashes are infallible. +//! +//! C headers: [`include/crypto/aes.h`](srctree/include/crypto/aes.h), +//! [`include/crypto/sha2.h`](srctree/include/crypto/sha2.h). + +use crate::{bindings, error::to_result, prelude::*}; + +/// Size of a SHA-256 / HMAC-SHA256 digest, in bytes. +pub const SHA256_DIGEST_SIZE: usize =3D 32; +/// AES-128 block and key size, in bytes. +pub const AES128_BLOCK_SIZE: usize =3D 16; + +/// Returns the SHA-256 digest of `data`. +pub fn sha256(data: &[u8]) -> [u8; SHA256_DIGEST_SIZE] { + let mut out =3D [0u8; SHA256_DIGEST_SIZE]; + // SAFETY: `data` is valid for `data.len()` reads and `out` is a valid + // `SHA256_DIGEST_SIZE`-byte output buffer, as `sha256()` requires. + unsafe { bindings::sha256(data.as_ptr(), data.len(), out.as_mut_ptr())= }; + out +} + +/// Returns `HMAC-SHA256(key, data)`. +pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; SHA256_DIGEST_SIZE] { + let mut out =3D [0u8; SHA256_DIGEST_SIZE]; + // SAFETY: `key` and `data` are valid for their respective lengths and= `out` + // is a valid `SHA256_DIGEST_SIZE`-byte output buffer, as required. + unsafe { + bindings::hmac_sha256_usingrawkey( + key.as_ptr(), + key.len(), + data.as_ptr(), + data.len(), + out.as_mut_ptr(), + ) + }; + out +} + +/// An AES-128 key usable for single-block ECB encryption. +/// +/// # Examples +/// +/// ``` +/// use kernel::crypto::Aes128; +/// let cipher =3D Aes128::new([0u8; 16]); +/// let _ct =3D cipher.encrypt_block(&[0u8; 16])?; +/// # Ok::<(), Error>(()) +/// ``` +pub struct Aes128([u8; AES128_BLOCK_SIZE]); + +impl Aes128 { + /// Creates an AES-128 key from 16 raw key bytes. + pub fn new(key: [u8; AES128_BLOCK_SIZE]) -> Self { + Self(key) + } + + /// Encrypts one 16-byte block: returns `AES-128-ECB(key, block)`. + pub fn encrypt_block( + &self, + block: &[u8; AES128_BLOCK_SIZE], + ) -> Result<[u8; AES128_BLOCK_SIZE]> { + let mut out =3D [0u8; AES128_BLOCK_SIZE]; + // SAFETY: `self.0`, `block` and `out` are all valid 16-byte buffe= rs, as + // the helper requires. + let ret =3D unsafe { + bindings::aes128_encrypt_block(self.0.as_ptr(), block.as_ptr()= , out.as_mut_ptr()) + }; + to_result(ret)?; + Ok(out) + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 9512af7156df..7fcbf3e7d7af 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -59,6 +59,7 @@ pub mod cpufreq; pub mod cpumask; pub mod cred; +pub mod crypto; pub mod debugfs; pub mod device; pub mod device_id; --=20 2.55.0 From nobody Thu Nov 5 07:32:38 2026 Received: from mail-wm1-f52.google.com (mail-wm1-f52.google.com [209.85.128.52]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1370F2C375A for ; Fri, 3 Jul 2026 03:01:05 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.52 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1783047667; cv=none; b=Ri7o6gPDwZ4ggn9vh+nYZvNopfyDAEStagFhtNEOP89YdZRABGT+DJb1WdsAnhm99WlvJ+kcshwJ8cRfVpxoIpVRU5S5sIu714cgeYjDURktZXtnQMjkyNf2NSiT4Nes2JeM0+d+fxzfl4JYMKNIGGKHorV7Wf0BZv12Na46Y+M= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1783047667; c=relaxed/simple; bh=ShOpn9kF3gVYKwCMKMLMTSxS22TbosQNRw0NgktUOnQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=Qw9ozEzGZsdyh0dQyuZlpS9sdzqehc+2P/Emym0HDU7jZC9Zqvn3YZJlqjCZiN2O44/fPODYwArga+FqYjelItbMWcW2tWOj0neSrENhGIBBIqyUdW+Z0N4owKIWqGzqu9RCufdzbph7gTYt1WGUaJOmMzRKOfsYdZa9D3W9M64= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=fireburn.co.uk; spf=none smtp.mailfrom=fireburn.co.uk; dkim=pass (2048-bit key) header.d=fireburn-co-uk.20251104.gappssmtp.com header.i=@fireburn-co-uk.20251104.gappssmtp.com header.b=rlSY2hBI; arc=none smtp.client-ip=209.85.128.52 Authentication-Results: smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=fireburn.co.uk Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=fireburn.co.uk Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=fireburn-co-uk.20251104.gappssmtp.com header.i=@fireburn-co-uk.20251104.gappssmtp.com header.b="rlSY2hBI" Received: by mail-wm1-f52.google.com with SMTP id 5b1f17b1804b1-493bf73ec2aso268955e9.2 for ; Thu, 02 Jul 2026 20:01:05 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=fireburn-co-uk.20251104.gappssmtp.com; s=20251104; t=1783047664; x=1783652464; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=QmFFr1nVwg9qMyBj4UlMZMNsqttnsXWZbsMMOlcBB2E=; b=rlSY2hBIPOIos4V9yAoBwJQvAg51TQWcAu4XivE7Z+B/pHxyyz16vE8mvkpwOpXqGP ia9s9MaBr1lEJkZCoB9ba9LN346xHwW4CYbL+SO2J/ilKrIbA3kqzz9KOf28dTQg6JGU YXC3jjZfNpbpdXggfaIDuoj/DG30S1OpRk9FJzcLxmMGC+MjnXjAmbAXxwm4GL4Y8rdL fFE4tnUZ+aAUP6g9miQss8MQNHGaBMordY81AKGnyHxpuzhof6TTl5YdJzPq6f9myJMM +hqdP4DUY4VfaGHAzTHiB/6g3jPfAaJSYDouxnoBYmSyfiHKqk4P8dRJLLOuRvQkqt/V pjog== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1783047664; x=1783652464; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-gg:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to; bh=QmFFr1nVwg9qMyBj4UlMZMNsqttnsXWZbsMMOlcBB2E=; b=QtNbAvFoho8dxf9blRo6UVd0+qtQTyW3M3YiAtf4DM8ZBwPSFiYFvjGNHf6H8MWJsq uRbrtwWrx4thIRHtH1ZZ/LbeSzC9UGvZ12dguXEQQrGyKNe95k1Wh72mFCdy53jrI8Lq EQSOX9Hoy4BxIUnw8eheWakMuo4seQi/NcRkwZFIdWPeglq/uXhECtrUIA9nRJKhzFvm ee70h7Ihk4vP0rQOPCNOHQOs1eMVhZYFv6eRiM1DUashXWAgVHc/luwE2EodoY3Ww4G7 LAGxUVvmFUK34yJe3YQnHIPNR4ObtiVMkxW/Qhu2aXYmTd9DHtSqr25zJy2O0SLCRLo7 bdSg== X-Forwarded-Encrypted: i=1; AFNElJ860vuWV2i6QSADKKhpB4DGqgOoYf7jeFcxv308zDtj4XOBbs9WIvN5fo+SeAdAcgCS3DFDcNTz/DEbTng=@vger.kernel.org X-Gm-Message-State: AOJu0YxrQwx9MU8sL/BSUUeSqdaLhEndQzvbaOWiDNXJZvDEwM4InxGi ed0CRsGAmXPNU6sszyAyWFGV/FilX+i8ngiXXyN6uI4VZHt194ttHhH1d3yxCHc5Yg== X-Gm-Gg: AfdE7ckHtyTbqgl/69m0yCtKbshf/Vf5USv7wYZXuy8EsdRiVT9vY+omOimDAKcTK+l NURmhHLv9hgwjaLiKfoRDIXUKv3nJJh0tHYrmdI2RZ1waRni49246576ZfcvvPQpQt1rYscFJqH DwHJOYrsITeGjfcXNCKSfMyXF2431BUFcDDZW1n02BQ0SX0cPizcE2i5HJNOyiiUu070lOK1UrX aZFIsr3RVyBIMx9MNlOOfVdtlVZdtk2i+UhE+I/xQd2vaqyXqawXMEEWeGVvlwZswXdYIK5+kN9 OgzHL4zS+4xrRf1MKvJ3RYwohsNw9rMzINzJMJbYeQ4Y2H/xWwWGr6BRdIZee2pExOxOieCOkex xq330k+WNqiUi2WKfL49iedOxwbiVLZ03ilzsJVDnZy1IQiq2D3Kd6TmuhfiGh1coTVqNGrlB2R cPMH6t9tTvjn7AtR+8QvVygxS0Kij3JNE2coSXkCBb6DPwmD1bXI4qmjWA X-Received: by 2002:a05:600c:4f94:b0:493:adc3:cced with SMTP id 5b1f17b1804b1-493c2b9826fmr119242225e9.34.1783047663925; Thu, 02 Jul 2026 20:01:03 -0700 (PDT) Received: from axion.fireburn.co.uk ([137.220.119.72]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-493bef183e7sm199495015e9.2.2026.07.02.20.01.02 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 02 Jul 2026 20:01:03 -0700 (PDT) From: Mike Lothian To: rust-for-linux@vger.kernel.org Cc: linux-crypto@vger.kernel.org, Eric Biggers , Herbert Xu , "David S. Miller" , Ard Biesheuvel , Miguel Ojeda , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , linux-kernel@vger.kernel.org, Mike Lothian Subject: [RFC PATCH v2 2/3] rust: crypto: use the in-tree AES-CMAC library Date: Fri, 3 Jul 2026 04:00:52 +0100 Message-ID: <20260703030056.2763-3-mike@fireburn.co.uk> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20260703030056.2763-1-mike@fireburn.co.uk> References: <20260617150143.2152-1-mike@fireburn.co.uk> <20260703030056.2763-1-mike@fireburn.co.uk> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Address the v1 RFC review (Eric Biggers): - Drop the bare single-block ECB helper (`aes128_encrypt_block`), which re-expanded the AES key on every block and exposed bare ECB instead of a mode of operation. `Aes128::new()` now prepares the key schedule once (v= ia `aes_prepareenckey()`) and `encrypt_block()` reuses it, so a keystream l= oop (e.g. AES-CTR, which `lib/crypto` does not yet provide) no longer re-exp= ands the key per block. This stays a low-level building block for the modes t= he library is missing. - Add `crypto::aes_cmac()` over the in-tree AES-CMAC library () instead of building CMAC out of bare AES, so t= he one mode of operation vino needs that the library already ships comes fr= om the library. Signed-off-by: Mike Lothian Assisted-by: Claude:claude-opus-4-8 [Claude-Code] --- rust/bindings/bindings_helper.h | 1 + rust/helpers/crypto.c | 40 ++++++++++------ rust/kernel/crypto.rs | 85 ++++++++++++++++++++++++++------- 3 files changed, 94 insertions(+), 32 deletions(-) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 14671e1825bb..60effaf3af16 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -28,6 +28,7 @@ */ #include =20 +#include #include =20 #include diff --git a/rust/helpers/crypto.c b/rust/helpers/crypto.c index dc9614f6fc8e..a18780231ce0 100644 --- a/rust/helpers/crypto.c +++ b/rust/helpers/crypto.c @@ -1,25 +1,37 @@ // SPDX-License-Identifier: GPL-2.0 =20 #include +#include #include =20 /* - * AES-128 single-block ECB encryption: out =3D AES(key, in). - * - * A helper because aes_encrypt() takes a transparent union (aes_encrypt_a= rg) - * that bindgen cannot express. SHA-256 and HMAC-SHA256 are plain extern + * aes_encrypt() takes a transparent union (aes_encrypt_arg) that bindgen = cannot + * express, so the single-block encrypt step is wrapped here. The key sche= dule + * is prepared once (aes_prepareenckey() is a plain extern bound directly)= and + * the resulting struct aes_enckey is reused across blocks by the caller, = so the + * key is not re-expanded per block. SHA-256 and HMAC-SHA256 are plain ext= ern * functions and are bound directly. */ -__rust_helper int -rust_helper_aes128_encrypt_block(const u8 *key, const u8 *in, u8 *out) +__rust_helper void +rust_helper_aes_enckey_encrypt_block(const struct aes_enckey *key, u8 *out, + const u8 *in) { - struct aes_enckey enckey; - int ret; + aes_encrypt(key, out, in); +} + +/* + * AES-CMAC one-shot over the in-tree library (crypto/aes-cbc-macs.h): pre= pares + * the 128-bit key, MACs @data and writes the 16-byte tag to @out. A helper + * because both aes_cmac_preparekey()'s struct and the aes_cmac() one-shot= are + * not expressible from Rust directly. The key length is fixed at 128 bits= , so + * aes_cmac_preparekey() cannot fail; the prepared key is wiped before ret= urn. + */ +__rust_helper void +rust_helper_aes_cmac(const u8 *key, const u8 *data, size_t data_len, u8 *o= ut) +{ + struct aes_cmac_key cmac_key; =20 - ret =3D aes_prepareenckey(&enckey, key, AES_KEYSIZE_128); - if (ret) - return ret; - aes_encrypt(&enckey, out, in); - memzero_explicit(&enckey, sizeof(enckey)); - return 0; + aes_cmac_preparekey(&cmac_key, key, AES_KEYSIZE_128); + aes_cmac(&cmac_key, data, data_len, out); + memzero_explicit(&cmac_key, sizeof(cmac_key)); } diff --git a/rust/kernel/crypto.rs b/rust/kernel/crypto.rs index c8f2cb994cfd..7d96c1c710a4 100644 --- a/rust/kernel/crypto.rs +++ b/rust/kernel/crypto.rs @@ -2,11 +2,15 @@ =20 //! Safe wrappers over the kernel's synchronous library crypto. //! -//! Exposes the one-shot `lib/crypto` primitives =E2=80=94 AES-128 single-= block ECB, -//! SHA-256 and HMAC-SHA256 =E2=80=94 for use from Rust. They run synchron= ously in the -//! calling context with no allocation; the hashes are infallible. +//! Exposes the one-shot `lib/crypto` primitives =E2=80=94 AES-128 (an [`A= es128`] key +//! prepared once for single-block encryption, the building block for mode= s the +//! library does not yet provide such as AES-CTR), the in-tree AES-CMAC +//! ([`aes_cmac`]), SHA-256 and HMAC-SHA256 =E2=80=94 for use from Rust. T= hey run +//! synchronously in the calling context with no allocation; the hashes an= d the +//! MAC are infallible. //! //! C headers: [`include/crypto/aes.h`](srctree/include/crypto/aes.h), +//! [`include/crypto/aes-cbc-macs.h`](srctree/include/crypto/aes-cbc-macs.= h), //! [`include/crypto/sha2.h`](srctree/include/crypto/sha2.h). =20 use crate::{bindings, error::to_result, prelude::*}; @@ -42,36 +46,81 @@ out } =20 -/// An AES-128 key usable for single-block ECB encryption. +/// Returns `AES-CMAC-128(key, data)` (RFC 4493), computed by the in-tree +/// AES-CMAC library ([`include/crypto/aes-cbc-macs.h`]). The 128-bit key = is +/// prepared and wiped internally; the call is infallible. +/// +/// [`include/crypto/aes-cbc-macs.h`]: srctree/include/crypto/aes-cbc-macs= .h +pub fn aes_cmac( + key: &[u8; AES128_BLOCK_SIZE], + data: &[u8], +) -> [u8; AES128_BLOCK_SIZE] { + let mut out =3D [0u8; AES128_BLOCK_SIZE]; + // SAFETY: `key` is a valid 16-byte key, `data` is valid for `data.len= ()` + // reads, and `out` is a valid `AES128_BLOCK_SIZE`-byte output buffer,= as the + // helper requires. + unsafe { + bindings::aes_cmac(key.as_ptr(), data.as_ptr(), data.len(), out.as= _mut_ptr()) + }; + out +} + +/// An AES-128 key, expanded once for single-block encryption. +/// +/// The key schedule is computed in [`Aes128::new`] and reused across every +/// [`encrypt_block`](Aes128::encrypt_block) call, so encrypting a stream = of +/// blocks (e.g. an AES-CTR keystream) does not re-expand the key per bloc= k. This +/// is a low-level building block: prefer a full mode of operation where t= he +/// library provides one (see [`aes_cmac`]); the bare block cipher is here= only +/// for modes `lib/crypto` does not yet expose, such as AES-CTR. /// /// # Examples /// /// ``` /// use kernel::crypto::Aes128; -/// let cipher =3D Aes128::new([0u8; 16]); -/// let _ct =3D cipher.encrypt_block(&[0u8; 16])?; +/// let cipher =3D Aes128::new(&[0u8; 16])?; +/// let _ct =3D cipher.encrypt_block(&[0u8; 16]); /// # Ok::<(), Error>(()) /// ``` -pub struct Aes128([u8; AES128_BLOCK_SIZE]); +pub struct Aes128(bindings::aes_enckey); =20 impl Aes128 { - /// Creates an AES-128 key from 16 raw key bytes. - pub fn new(key: [u8; AES128_BLOCK_SIZE]) -> Self { - Self(key) + /// Expands an AES-128 key from 16 raw key bytes. + pub fn new(key: &[u8; AES128_BLOCK_SIZE]) -> Result { + // SAFETY: `aes_enckey` is a plain-old-data key schedule (integer = arrays + // in a union of integer arrays); an all-zero bit pattern is a val= id, + // inert initial value, fully overwritten by `aes_prepareenckey()`= below. + let mut enckey: bindings::aes_enckey =3D unsafe { core::mem::zeroe= d() }; + // SAFETY: `enckey` is a valid, owned `aes_enckey`; `key` is a val= id + // 16-byte buffer; `AES128_BLOCK_SIZE` (16) is a supported key len= gth. + let ret =3D unsafe { + bindings::aes_prepareenckey(&mut enckey, key.as_ptr(), AES128_= BLOCK_SIZE) + }; + to_result(ret)?; + Ok(Self(enckey)) } =20 - /// Encrypts one 16-byte block: returns `AES-128-ECB(key, block)`. + /// Encrypts one 16-byte block with the prepared key: returns + /// `AES-128-ECB(key, block)`. pub fn encrypt_block( &self, block: &[u8; AES128_BLOCK_SIZE], - ) -> Result<[u8; AES128_BLOCK_SIZE]> { + ) -> [u8; AES128_BLOCK_SIZE] { let mut out =3D [0u8; AES128_BLOCK_SIZE]; - // SAFETY: `self.0`, `block` and `out` are all valid 16-byte buffe= rs, as - // the helper requires. - let ret =3D unsafe { - bindings::aes128_encrypt_block(self.0.as_ptr(), block.as_ptr()= , out.as_mut_ptr()) + // SAFETY: `self.0` is a prepared encryption key; `block` and `out= ` are + // valid 16-byte buffers, as the helper requires. + unsafe { + bindings::aes_enckey_encrypt_block(&self.0, out.as_mut_ptr(), = block.as_ptr()) }; - to_result(ret)?; - Ok(out) + out + } +} + +impl Drop for Aes128 { + fn drop(&mut self) { + // SAFETY: `self.0` is a valid, owned `aes_enckey`; overwriting it= with + // an all-zero `aes_enckey` clears the expanded key schedule. + // `write_volatile` keeps the store from being optimised away. + unsafe { core::ptr::write_volatile(&mut self.0, core::mem::zeroed(= )) }; } } --=20 2.55.0 From nobody Thu Nov 5 07:32:38 2026 Received: from mail-wm1-f45.google.com (mail-wm1-f45.google.com [209.85.128.45]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id EB6742727EB for ; Fri, 3 Jul 2026 03:01:06 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.45 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1783047668; cv=none; b=rSKq/ndDeMteFttH/+xJq+jTeSNLzQveE/rbjMXYtJv9yX3UAlPy8RLxcfdwB4UcheznCyZilEQLj9O/1Q8U5H+EOx9TntWk0TNBUWedLTd0UOjd8BWD6gRI4dmrDbxA5O5QCopCtsXlHXCaCJM2Jj8eRV7nObWHJ4lDNzTO40c= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1783047668; c=relaxed/simple; bh=vNMwT10aUyIs/UOUOeCfpeIMwXxkHRgS5Z5j0voWgjU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=SjA/Z8FQrHRqSLESKXCTCnvaSaXKhYyG0wn0gIhXfliEY51PYsNS29tU2e90lYRpB/5FwQ980xsv23OTxkG9vYDRLER1c9S4LxaE+yosaux490/YxJHLJARzQWD+zK9bX0KhyKOkLb2v4xh4/wsvk3hlNW9kssa+AYOrax0lZn4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=fireburn.co.uk; spf=none smtp.mailfrom=fireburn.co.uk; dkim=pass (2048-bit key) header.d=fireburn-co-uk.20251104.gappssmtp.com header.i=@fireburn-co-uk.20251104.gappssmtp.com header.b=M1JHDGGu; arc=none smtp.client-ip=209.85.128.45 Authentication-Results: smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=fireburn.co.uk Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=fireburn.co.uk Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=fireburn-co-uk.20251104.gappssmtp.com header.i=@fireburn-co-uk.20251104.gappssmtp.com header.b="M1JHDGGu" Received: by mail-wm1-f45.google.com with SMTP id 5b1f17b1804b1-493be1b9564so290515e9.2 for ; Thu, 02 Jul 2026 20:01:06 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=fireburn-co-uk.20251104.gappssmtp.com; s=20251104; t=1783047665; x=1783652465; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=vFxVq+fsBKcws494QRfz2Vi1lFIC+br0mAAxV3ScsVg=; b=M1JHDGGuH/yeWD7ZoZS1518kHzSk/KMusnuNjFQuo4lYkev92pQLtL/m+i+EtlnAvH OEa3ALUYqHZlqITQpBH/n+3nMQI/t37TDaEbvA82RzQUQ/y7aMziyqHq3/cV5gJlQzPl KoDJuMWBhakcMyXmgrMFuz22d+LYYvBEztilExNfCctMXtZuled3mS8oqleRJTccLKrV 1yy53Hj5AgMXHc4hf6BflNTzBrPUHi/s0FwII6ImdPpteBt7aS9XzfVOXqO6R4Rawhtj cjBlxbx/IpbqB7cepLGDkK9IdJOaiU2PzXIXlysx5Q2ziBg8iLshbkcZ1o6C7iIkz+ds 594w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1783047665; x=1783652465; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-gg:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to; bh=vFxVq+fsBKcws494QRfz2Vi1lFIC+br0mAAxV3ScsVg=; b=gBbW3IPBMSB8tzHfOwzyJx/tOG+Z/q5ATzCdANTkHqwEeuA9IbHKRT/SlstsUBoyBn P5a7eMyjb0h30yX4ZrOGdN9vwSl8nb9vMgKXNoGVZzFCAlFuCnLshaJyFt9rjtgbh1+m zMMSjeWM4s6c0J0mlwgThW+AbHsjesUYhRf4Ql3MuYKTEuX1fu05ywqdGGlhzZ1gtyLl jyfFE68JwmiymsTxSbChcaQNuzUQutHuHK33gQDEdgzW+0JgiqkpJgK82VsdBrVbJNP9 SV45fkEOniLkowrUn1qvRw9WIhAm+VP17Vcx6JQyEjs/5zuDzziZpP3RAjtEL+F3cGi4 MYqg== X-Forwarded-Encrypted: i=1; AFNElJ9arZdnqpiTA6G7txKJo1SAsVbiMDMJXS5Y/o93G6Xp7TCtlo2ZeOtMqqIs6IVMBKCyo925OQhvPqZsyxI=@vger.kernel.org X-Gm-Message-State: AOJu0Yw6Jr8U6fO2Jl5uU8M1Jub74NWWwwQMfKfXNeIS+ngn+PzC5VYB vgJwNB1EKxm3U3Tq3Ty01q7aVMOyp0mRrHsEJZey2/iUneItxvpNsR2fb4D8ER/HmQ== X-Gm-Gg: AfdE7cn8zooYJlgMSJb/1Ql/L/9LKQ1t74fO5Gok7ygVbTrGrK3YUO1KMIv1I0KMBxq yxCZaLhx1+mVLewyV2nZeYzyTfocI/IJEdZ8hOmf2B3z6vx5PibMXbabd7OT5hNIPfvKcXHzxNa +yNbInQmg/z4UZurkCZE4ZaXNRHOhVI/pcL0PJRAQCR2f6UnYHWFoPjtR1cdfED2WLeMpYKM8MH E88LIvYrAtDT2NbqY6oLIZxEUkrtxnp+g0AKGBBPDcpD2wsStt0eY8TFbkTbWOn6/aod9gfKHfV v8tlVn58rgv9IIGDWmj8AAiqyyYsR2rDWxiYDr/O6+mPwLK/LSpv+VjiEarISkbBr+EpndWXHzp knGX3OneYcclz8W39Vsares2FJKDbZv0nFzZST+n7hDJacR8WhcWECyHmFRlKLpg5dxRNFY+UUl 75krPUzG+LaEXRrb/RDgRQB/rYpesDwi4wEN+iaN/UdMY1UO3OnEP2yF5ayt5K/0k4wzg= X-Received: by 2002:a05:600c:524a:b0:493:af0d:484c with SMTP id 5b1f17b1804b1-493c3df2fb5mr108882145e9.34.1783047665359; Thu, 02 Jul 2026 20:01:05 -0700 (PDT) Received: from axion.fireburn.co.uk ([137.220.119.72]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-493bef183e7sm199495015e9.2.2026.07.02.20.01.04 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 02 Jul 2026 20:01:04 -0700 (PDT) From: Mike Lothian To: rust-for-linux@vger.kernel.org Cc: linux-crypto@vger.kernel.org, Eric Biggers , Herbert Xu , "David S. Miller" , Ard Biesheuvel , Miguel Ojeda , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , linux-kernel@vger.kernel.org, Mike Lothian Subject: [RFC PATCH v2 3/3] rust: crypto: add an RSA public-key primitive in lib/crypto Date: Fri, 3 Jul 2026 04:00:53 +0100 Message-ID: <20260703030056.2763-4-mike@fireburn.co.uk> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20260703030056.2763-1-mike@fireburn.co.uk> References: <20260617150143.2152-1-mike@fireburn.co.uk> <20260703030056.2763-1-mike@fireburn.co.uk> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Address the v1 RFC review (Eric Biggers): rather than binding crypto_akcipher ("a very bad API"), add the RSA public-key operation as a small lib/crypto primitive and bind that. New lib/crypto/rsa.c exports int rsa_pubkey_encrypt(const u8 *n, size_t n_len, const u8 *e, size_t e_len, const u8 *in, size_t in_len, u8 *out, size_t out_len); the bare RSAEP primitive c =3D m^e mod n [RFC8017 sec 5.1.1], computed with the MPI big-integer library (the same arithmetic crypto/rsa.c uses) but without the akcipher tfm, DER key encoding, scatterlists or async completion. It rejects m >=3D n (which mpi_powm() would otherwise silently reduce, yielding an undecryptable ciphertext), writes the result fixed-width big-endian left zero-padded to out_len, and zeroes out on every error path. Callers apply their own padding (RSAES-OAEP, ...). Declared in include/crypto/rsa.h, gated by a new CONFIG_CRYPTO_LIB_RSA (selects MPILIB). crypto::rsa_pubkey_encrypt() wraps it directly. Because the wrapper is compiled into and exported from the built-in kernel crate, the C symbol must live in vmlinux: CONFIG_CRYPTO_LIB_RSA is therefore a bool (a select forces it built-in) and the wrapper is #[cfg(CONFIG_CRYPTO_LIB_RSA)]-gated so no vmlinux dependency is introduced for kernels that do not configure it. A consumer (e.g. the vino driver) selects it. A from-scratch constant-time/allocation-free RSA is out of scope; this is the lib/crypto entry point that lets a Rust caller avoid crypto_akcipher. Signed-off-by: Mike Lothian Assisted-by: Claude:claude-opus-4-8 [Claude-Code] --- include/crypto/rsa.h | 15 +++++ lib/crypto/Kconfig | 9 +++ lib/crypto/Makefile | 3 + lib/crypto/rsa.c | 102 ++++++++++++++++++++++++++++++++ rust/bindings/bindings_helper.h | 1 + rust/kernel/crypto.rs | 43 ++++++++++++++ 6 files changed, 173 insertions(+) create mode 100644 include/crypto/rsa.h create mode 100644 lib/crypto/rsa.c diff --git a/include/crypto/rsa.h b/include/crypto/rsa.h new file mode 100644 index 000000000000..c11d7b5cae9a --- /dev/null +++ b/include/crypto/rsa.h @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * RSA public-key primitive (RSAEP), library interface. + * + * Copyright (c) 2026 Mike Lothian + */ +#ifndef _CRYPTO_RSA_H +#define _CRYPTO_RSA_H + +#include + +int rsa_pubkey_encrypt(const u8 *n, size_t n_len, const u8 *e, size_t e_le= n, + const u8 *in, size_t in_len, u8 *out, size_t out_len); + +#endif /* _CRYPTO_RSA_H */ diff --git a/lib/crypto/Kconfig b/lib/crypto/Kconfig index 591c1c2a7fb3..04655c104e65 100644 --- a/lib/crypto/Kconfig +++ b/lib/crypto/Kconfig @@ -45,6 +45,15 @@ config CRYPTO_LIB_AESGCM config CRYPTO_LIB_ARC4 tristate =20 +config CRYPTO_LIB_RSA + bool + select MPILIB + help + The RSA public-key primitive (RSAEP, out =3D in^e mod n), built on the + MPI big-integer library. The bare primitive only; callers apply their + own padding. Bool rather than tristate: the in-kernel consumer is the + built-in Rust crypto bindings, so it must live in vmlinux. + config CRYPTO_LIB_GF128MUL tristate =20 diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile index f1e9bf89785f..486557df59e3 100644 --- a/lib/crypto/Makefile +++ b/lib/crypto/Makefile @@ -69,6 +69,9 @@ libaesgcm-y :=3D aesgcm.o obj-$(CONFIG_CRYPTO_LIB_ARC4) +=3D libarc4.o libarc4-y :=3D arc4.o =20 +obj-$(CONFIG_CRYPTO_LIB_RSA) +=3D librsa.o +librsa-y :=3D rsa.o + obj-$(CONFIG_CRYPTO_LIB_GF128MUL) +=3D gf128mul.o =20 ##########################################################################= ###### diff --git a/lib/crypto/rsa.c b/lib/crypto/rsa.c new file mode 100644 index 000000000000..21c1d6c9ea26 --- /dev/null +++ b/lib/crypto/rsa.c @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * RSA public-key primitive (RSAEP) [RFC8017 sec 5.1.1]. + * + * A minimal synchronous library entry point for the RSA public-key operat= ion, + * built on the MPI big-integer library (the same arithmetic the crypto_ak= cipher + * "rsa" transform uses), but without the akcipher tfm allocation, DER key + * encoding, scatterlists or asynchronous completion machinery. It perform= s only + * the bare RSAEP primitive; callers apply any encoding/padding (RSAES-OAE= P, + * RSAES-PKCS1-v1_5, ...) themselves. + * + * Copyright (c) 2026 Mike Lothian + */ + +#include +#include +#include +#include +#include +#include + +/** + * rsa_pubkey_encrypt() - RSA public-key operation, out =3D (in ^ e) mod n + * @n: modulus, unsigned big-endian + * @n_len: length of @n, in bytes + * @e: public exponent, unsigned big-endian + * @e_len: length of @e, in bytes + * @in: input, unsigned big-endian; already padded by the caller + * @in_len: length of @in, in bytes + * @out: output buffer; receives the result big-endian, left zero-padded to + * exactly @out_len bytes + * @out_len: size of @out; pass the modulus length (e.g. 128 for RSA-1024) + * + * Computes the bare RSAEP primitive c =3D m^e mod n, where m is @in inter= preted + * as a big-endian integer. This is the raw public-key operation [RFC8017 = sec + * 5.1.1]; the caller is responsible for any message encoding/padding. + * + * @in interpreted as an integer must be numerically less than @n, as RSA + * requires: a larger value would be silently reduced mod n by the modular + * exponentiation and yield a ciphertext the peer cannot decrypt, so it is + * rejected. On any error path @out is zeroed, so it never retains data fr= om a + * partial computation. + * + * Return: 0 on success; -EINVAL on a malformed key or out-of-range input; + * -EOVERFLOW if the result does not fit in @out_len; -ENOMEM on allocation + * failure. + */ +int rsa_pubkey_encrypt(const u8 *n, size_t n_len, const u8 *e, size_t e_le= n, + const u8 *in, size_t in_len, u8 *out, size_t out_len) +{ + MPI mn, me, mbase, mres; + unsigned int nbytes; + int ret =3D -ENOMEM; + + if (!n_len || !e_len || !in_len || !out_len) + return -EINVAL; + + mn =3D mpi_read_raw_data(n, n_len); + me =3D mpi_read_raw_data(e, e_len); + mbase =3D mpi_read_raw_data(in, in_len); + mres =3D mpi_alloc(0); + if (!mn || !me || !mbase || !mres) + goto out; + + /* + * RSA requires 0 <=3D m < n; reject m >=3D n rather than let mpi_powm() + * silently reduce it and produce an undecryptable ciphertext. + */ + if (mpi_cmp(mbase, mn) >=3D 0) { + ret =3D -EINVAL; + goto out; + } + + ret =3D mpi_powm(mres, mbase, me, mn); + if (ret) + goto out; + + /* + * mpi_read_buffer() writes the minimal big-endian form left-aligned + * (and returns -EOVERFLOW without writing if @out_len is too small); + * right-align it into the fixed-width output and zero-pad the front. + */ + ret =3D mpi_read_buffer(mres, out, out_len, &nbytes, NULL); + if (ret) + goto out; + if (nbytes < out_len) { + memmove(out + (out_len - nbytes), out, nbytes); + memset(out, 0, out_len - nbytes); + } +out: + if (ret) + memzero_explicit(out, out_len); + mpi_free(mn); + mpi_free(me); + mpi_free(mbase); + mpi_free(mres); + return ret; +} +EXPORT_SYMBOL_GPL(rsa_pubkey_encrypt); + +MODULE_DESCRIPTION("RSA public-key primitive (RSAEP)"); +MODULE_LICENSE("GPL"); diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 60effaf3af16..7bb04d68f9d2 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -29,6 +29,7 @@ #include =20 #include +#include #include =20 #include diff --git a/rust/kernel/crypto.rs b/rust/kernel/crypto.rs index 7d96c1c710a4..b6836e771cfa 100644 --- a/rust/kernel/crypto.rs +++ b/rust/kernel/crypto.rs @@ -9,8 +9,12 @@ //! synchronously in the calling context with no allocation; the hashes an= d the //! MAC are infallible. //! +//! Also exposes the `lib/crypto` RSA public-key primitive +//! ([`rsa_pubkey_encrypt`]) for callers that do their own padding. +//! //! C headers: [`include/crypto/aes.h`](srctree/include/crypto/aes.h), //! [`include/crypto/aes-cbc-macs.h`](srctree/include/crypto/aes-cbc-macs.= h), +//! [`include/crypto/rsa.h`](srctree/include/crypto/rsa.h), //! [`include/crypto/sha2.h`](srctree/include/crypto/sha2.h). =20 use crate::{bindings, error::to_result, prelude::*}; @@ -124,3 +128,42 @@ fn drop(&mut self) { unsafe { core::ptr::write_volatile(&mut self.0, core::mem::zeroed(= )) }; } } + +/// Computes the RSA public-key primitive `out =3D (input ^ exponent) mod = modulus` +/// using the in-tree `lib/crypto` RSA library (`rsa_pubkey_encrypt()` in +/// [`lib/crypto/rsa.c`](srctree/lib/crypto/rsa.c)). +/// +/// All buffers are unsigned big-endian. `out` is written fixed-width to e= xactly +/// `out.len()` bytes (left zero-padded); pass `out.len()` equal to the mo= dulus +/// size (e.g. 128 for RSA-1024). This is the bare primitive: the caller a= pplies +/// any padding (PKCS#1 v1.5, EME-OAEP, =E2=80=A6) to `input` first. +/// +/// `input` interpreted as an integer must be less than `modulus`, as RSA +/// requires; otherwise an error is returned. On any error `out` is zeroed= by the +/// library, so it never retains data from a partial computation. +/// +/// Only available when `CONFIG_CRYPTO_LIB_RSA` is enabled (a consumer sel= ects +/// it); the backing library is then built into the kernel. +#[cfg(CONFIG_CRYPTO_LIB_RSA)] +pub fn rsa_pubkey_encrypt( + modulus: &[u8], + exponent: &[u8], + input: &[u8], + out: &mut [u8], +) -> Result { + // SAFETY: each slice is valid for its stated length; the library func= tion + // reads `modulus`/`exponent`/`input` and writes exactly `out.len()` b= ytes + // into `out` (left zero-padded), zeroing it on any error. + to_result(unsafe { + bindings::rsa_pubkey_encrypt( + modulus.as_ptr(), + modulus.len(), + exponent.as_ptr(), + exponent.len(), + input.as_ptr(), + input.len(), + out.as_mut_ptr(), + out.len(), + ) + }) +} --=20 2.55.0