All of lore.kernel.org
 help / color / mirror / Atom feed
From: FUJITA Tomonori <fujita.tomonori@gmail.com>
To: rust-for-linux@vger.kernel.org
Subject: [RFC PATCH v2 2/2] rust: add Random Number Generator algorithms support
Date: Thu, 15 Jun 2023 23:23:11 +0900	[thread overview]
Message-ID: <20230615142311.4055228-3-fujita.tomonori@gmail.com> (raw)
In-Reply-To: <20230615142311.4055228-1-fujita.tomonori@gmail.com>

Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
---
 rust/bindings/bindings_helper.h |  1 +
 rust/helpers.c                  | 12 ++++++
 rust/kernel/crypto.rs           |  1 +
 rust/kernel/crypto/rng.rs       | 72 +++++++++++++++++++++++++++++++++
 4 files changed, 86 insertions(+)
 create mode 100644 rust/kernel/crypto/rng.rs

diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index 2f198c6d5de5..089ac38c6461 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -7,6 +7,7 @@
  */
 
 #include <crypto/hash.h>
+#include <crypto/rng.h>
 #include <linux/errname.h>
 #include <linux/slab.h>
 #include <linux/refcount.h>
diff --git a/rust/helpers.c b/rust/helpers.c
index 7966902ed8eb..e4dcd611738f 100644
--- a/rust/helpers.c
+++ b/rust/helpers.c
@@ -19,6 +19,7 @@
  */
 
 #include <crypto/hash.h>
+#include <crypto/rng.h>
 #include <linux/bug.h>
 #include <linux/build_bug.h>
 #include <linux/err.h>
@@ -52,6 +53,17 @@ int rust_helper_crypto_shash_init(struct shash_desc *desc) {
 	return crypto_shash_init(desc);
 }
 EXPORT_SYMBOL_GPL(rust_helper_crypto_shash_init);
+
+void rust_helper_crypto_free_rng(struct crypto_rng *tfm) {
+	crypto_free_rng(tfm);
+}
+EXPORT_SYMBOL_GPL(rust_helper_crypto_free_rng);
+
+int rust_helper_crypto_rng_generate(struct crypto_rng *tfm, const u8 *src,
+	unsigned int slen, u8 *dst, unsigned int dlen) {
+	return crypto_rng_generate(tfm, src, slen, dst, dlen);
+}
+EXPORT_SYMBOL_GPL(rust_helper_crypto_rng_generate);
 #endif
 
 __noreturn void rust_helper_BUG(void)
diff --git a/rust/kernel/crypto.rs b/rust/kernel/crypto.rs
index f80dd7bd3381..a1995e6c85d4 100644
--- a/rust/kernel/crypto.rs
+++ b/rust/kernel/crypto.rs
@@ -3,3 +3,4 @@
 //! Cryptography.
 
 pub mod hash;
+pub mod rng;
diff --git a/rust/kernel/crypto/rng.rs b/rust/kernel/crypto/rng.rs
new file mode 100644
index 000000000000..2215a8344669
--- /dev/null
+++ b/rust/kernel/crypto/rng.rs
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Random number generator.
+//!
+//! C headers: [`include/crypto/rng.h`](../../../../include/crypto/rng.h)
+
+use crate::{
+    error::{from_err_ptr, to_result, Result},
+    str::CStr,
+};
+
+/// Corresponds to the kernel's `struct crypto_rng`.
+///
+/// # Invariants
+///
+/// The pointer is valid.
+pub struct Rng(*mut bindings::crypto_rng);
+
+impl Drop for Rng {
+    fn drop(&mut self) {
+        // SAFETY: The type invariant guarantees that `self.0` is valid.
+        if unsafe { bindings::crypto_default_rng } == self.0 {
+            // SAFETY: FFI call.
+            unsafe {
+                bindings::crypto_put_default_rng();
+            }
+        } else {
+            // SAFETY: The type invariant guarantees that `self.0` is valid.
+            unsafe { bindings::crypto_free_rng(self.0) };
+        }
+    }
+}
+
+impl Rng {
+    /// Creates a [`Rng`] instance.
+    pub fn new(name: &CStr, t: u32, mask: u32) -> Result<Self> {
+        // SAFETY: FFI call.
+        let ptr = unsafe { from_err_ptr(bindings::crypto_alloc_rng(name.as_char_ptr(), t, mask)) }?;
+        // INVARIANT: `ptr` is valid and non-null since `crypto_alloc_rng`
+        // returned a valid pointer which was null-checked.
+        Ok(Self(ptr))
+    }
+
+    /// Creates a [`Rng`] instance with a default algorithm.
+    pub fn new_with_default() -> Result<Self> {
+        // SAFETY: FFI call.
+        to_result(unsafe { bindings::crypto_get_default_rng() })?;
+        // SAFETY: The C API guarantees that `crypto_default_rng` is valid until
+        // `crypto_put_default_rng` is called.
+        Ok(Self(unsafe { bindings::crypto_default_rng }))
+    }
+
+    /// Get a random number.
+    pub fn generate(&mut self, src: &[u8], dst: &mut [u8]) -> Result {
+        // SAFETY: The type invariant guarantees that the pointer is valid.
+        to_result(unsafe {
+            bindings::crypto_rng_generate(
+                self.0,
+                src.as_ptr(),
+                src.len() as u32,
+                dst.as_mut_ptr(),
+                dst.len() as u32,
+            )
+        })
+    }
+
+    /// Re-initializes the [`Rng`] instance.
+    pub fn reset(&mut self, seed: &[u8]) -> Result {
+        // SAFETY: The type invariant guarantees that the pointer is valid.
+        to_result(unsafe { bindings::crypto_rng_reset(self.0, seed.as_ptr(), seed.len() as u32) })
+    }
+}
-- 
2.34.1


  parent reply	other threads:[~2023-06-15 14:23 UTC|newest]

Thread overview: 17+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2023-06-15 14:23 [RFC PATCH v2 0/2] Rust abstractions for Crypto API FUJITA Tomonori
2023-06-15 14:23 ` [RFC PATCH v2 1/2] rust: add synchronous message digest support FUJITA Tomonori
2023-06-15 15:01   ` Greg KH
2023-06-15 15:33     ` FUJITA Tomonori
2023-06-15 15:02   ` Alex Gaynor
2023-06-15 15:24     ` FUJITA Tomonori
2023-06-19 11:40   ` Benno Lossin
2023-06-22  2:14     ` FUJITA Tomonori
2023-06-25 10:08       ` Benno Lossin
2023-06-25 11:55         ` FUJITA Tomonori
2023-06-30 14:48         ` Benno Lossin
2023-06-30 19:50           ` Greg KH
2023-07-03 23:19           ` Herbert Xu
2023-07-10 19:59             ` Benno Lossin
2023-06-15 14:23 ` FUJITA Tomonori [this message]
2023-06-19 11:41   ` [RFC PATCH v2 2/2] rust: add Random Number Generator algorithms support Benno Lossin
2023-07-06  4:05     ` FUJITA Tomonori

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20230615142311.4055228-3-fujita.tomonori@gmail.com \
    --to=fujita.tomonori@gmail.com \
    --cc=rust-for-linux@vger.kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.