rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
From: FUJITA Tomonori <fujita.tomonori@gmail.com>
To: benno.lossin@proton.me
Cc: fujita.tomonori@gmail.com, rust-for-linux@vger.kernel.org
Subject: Re: [RFC PATCH v2 2/2] rust: add Random Number Generator algorithms support
Date: Thu, 06 Jul 2023 13:05:30 +0900 (JST)	[thread overview]
Message-ID: <20230706.130530.28972016277282041.ubuntu@gmail.com> (raw)
In-Reply-To: <0_ad81AiwBp5KWLfbBfeHP4ABr4cPr7B1WaKdx__tWLIZI75vsBSVA4Yzk9_5q7MAgTlafWxIMX86-SoHhWwEQ8FWs7anjul0a2wjIwqTGc=@proton.me>

Hi,

On Mon, 19 Jun 2023 11:41:29 +0000
Benno Lossin <benno.lossin@proton.me> wrote:

>> 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.
> 
> This safety comment should explain why it is safe to access this mutable
> static variable.
> 
>> +        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) };
>> +        }
>> +    }
>> +}

crypto_get_default_rng() is called during the initialization so it's
safe to access to bindings::crypto_default_rng. However, it's cleaner
to use an internal type like the following?

diff --git a/rust/kernel/crypto/rng.rs b/rust/kernel/crypto/rng.rs
new file mode 100644
index 000000000000..1d5d16577f3e
--- /dev/null
+++ b/rust/kernel/crypto/rng.rs
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Random number generator.
+//!
+//! C headers: [`include/crypto/rng.h`](../../../../include/crypto/rng.h)
+
+use crate::{
+    error::{code::EINVAL, from_err_ptr, to_result, Result},
+    str::CStr,
+};
+
+/// Type of Random number generator.
+///
+/// # Invariants
+///
+/// The pointer is valid.
+enum RngType {
+    /// Uses `crypto_default_rng`
+    Default(*mut bindings::crypto_rng),
+
+    /// Allocated via `crypto_alloc_rng.
+    Allocated(*mut bindings::crypto_rng),
+}
+
+/// Corresponds to the kernel's `struct crypto_rng`.
+pub struct Rng(RngType);
+
+impl Drop for Rng {
+    fn drop(&mut self) {
+        match self.0 {
+            RngType::Default(_) => {
+                // SAFETY: it's safe because `crypto_get_default_rng()` was called during
+                // the initialization.
+                unsafe {
+                    bindings::crypto_put_default_rng();
+                }
+            }
+            RngType::Allocated(ptr) => {
+                // SAFETY: The type invariants of `RngType` guarantees that the pointer is valid.
+                unsafe { bindings::crypto_free_rng(ptr) };
+            }
+        }
+    }
+}
+
+impl Rng {
+    /// Creates a [`Rng`] instance.
+    pub fn new(name: &CStr, t: u32, mask: u32) -> Result<Self> {
+        // SAFETY: There are no safety requirements for this 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(RngType::Allocated(ptr)))
+    }
+
+    /// Creates a [`Rng`] instance with a default algorithm.
+    pub fn new_with_default() -> Result<Self> {
+        // SAFETY: There are no safety requirements for this FFI call.
+        to_result(unsafe { bindings::crypto_get_default_rng() })?;
+        // INVARIANT: The C API guarantees that `crypto_default_rng` is valid until
+        // `crypto_put_default_rng` is called.
+        Ok(Self(RngType::Default(unsafe {
+            bindings::crypto_default_rng
+        })))
+    }
+
+    /// Get a random number.
+    pub fn generate(&mut self, src: &[u8], dst: &mut [u8]) -> Result {
+        if src.len() > u32::MAX as usize || dst.len() > u32::MAX as usize {
+            return Err(EINVAL);
+        }
+        let ptr = match self.0 {
+            RngType::Default(ptr) => ptr,
+            RngType::Allocated(ptr) => ptr,
+        };
+        // SAFETY: The type invariants of `RngType' guarantees that the pointer is valid.
+        to_result(unsafe {
+            bindings::crypto_rng_generate(
+                ptr,
+                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 {
+        if seed.len() > u32::MAX as usize {
+            return Err(EINVAL);
+        }
+        let ptr = match self.0 {
+            RngType::Default(ptr) => ptr,
+            RngType::Allocated(ptr) => ptr,
+        };
+        // SAFETY: The type invariants of `RngType' guarantees that the pointer is valid.
+        to_result(unsafe { bindings::crypto_rng_reset(ptr, seed.as_ptr(), seed.len() as u32) })
+    }
+}
-- 
2.34.1


      reply	other threads:[~2023-07-06  4:08 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 ` [RFC PATCH v2 2/2] rust: add Random Number Generator algorithms support FUJITA Tomonori
2023-06-19 11:41   ` Benno Lossin
2023-07-06  4:05     ` FUJITA Tomonori [this message]

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=20230706.130530.28972016277282041.ubuntu@gmail.com \
    --to=fujita.tomonori@gmail.com \
    --cc=benno.lossin@proton.me \
    --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 a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).