blob: b45538aa1b7c13d58248a5ff2b1130833832ad49 [file] [log] [blame]
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +00001// Copyright 2023, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000015use crate::hvc;
16use core::fmt;
17use core::mem::size_of;
18
19pub enum Error {
20 /// Error during SMCCC TRNG call.
21 Trng(hvc::trng::Error),
22 /// Unsupported SMCCC TRNG version.
23 UnsupportedVersion((u16, u16)),
24}
25
26impl From<hvc::trng::Error> for Error {
27 fn from(e: hvc::trng::Error) -> Self {
28 Self::Trng(e)
29 }
30}
31
32pub type Result<T> = core::result::Result<T, Error>;
33
34impl fmt::Display for Error {
35 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36 match self {
37 Self::Trng(e) => write!(f, "SMCCC TRNG error: {e}"),
38 Self::UnsupportedVersion((x, y)) => {
39 write!(f, "Unsupported SMCCC TRNG version v{x}.{y}")
40 }
41 }
42 }
43}
44
Pierre-Clément Tosi78b68512023-06-22 09:40:16 +000045impl fmt::Debug for Error {
46 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
47 write!(f, "{self}")
48 }
49}
50
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000051/// Configure the source of entropy.
52pub fn init() -> Result<()> {
53 match hvc::trng_version()? {
54 (1, _) => Ok(()),
55 version => Err(Error::UnsupportedVersion(version)),
56 }
57}
58
59fn fill_with_entropy(s: &mut [u8]) -> Result<()> {
60 const MAX_BYTES_PER_CALL: usize = size_of::<hvc::TrngRng64Entropy>();
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000061
62 let (aligned, remainder) = s.split_at_mut(s.len() - s.len() % MAX_BYTES_PER_CALL);
63
64 for chunk in aligned.chunks_exact_mut(MAX_BYTES_PER_CALL) {
Pierre-Clément Tosicb0340c2023-03-06 11:49:39 +000065 let (r, s, t) = repeat_trng_rnd(chunk.len())?;
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000066
67 let mut words = chunk.chunks_exact_mut(size_of::<u64>());
68 words.next().unwrap().clone_from_slice(&t.to_ne_bytes());
69 words.next().unwrap().clone_from_slice(&s.to_ne_bytes());
70 words.next().unwrap().clone_from_slice(&r.to_ne_bytes());
71 }
72
73 if !remainder.is_empty() {
74 let mut entropy = [0; MAX_BYTES_PER_CALL];
Pierre-Clément Tosicb0340c2023-03-06 11:49:39 +000075 let (r, s, t) = repeat_trng_rnd(remainder.len())?;
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000076
77 let mut words = entropy.chunks_exact_mut(size_of::<u64>());
78 words.next().unwrap().clone_from_slice(&t.to_ne_bytes());
79 words.next().unwrap().clone_from_slice(&s.to_ne_bytes());
80 words.next().unwrap().clone_from_slice(&r.to_ne_bytes());
81
82 remainder.clone_from_slice(&entropy[..remainder.len()]);
83 }
84
85 Ok(())
86}
87
Pierre-Clément Tosicb0340c2023-03-06 11:49:39 +000088fn repeat_trng_rnd(n_bytes: usize) -> hvc::trng::Result<hvc::TrngRng64Entropy> {
89 let bits = usize::try_from(u8::BITS).unwrap();
90 let n_bits = (n_bytes * bits).try_into().unwrap();
91 loop {
92 match hvc::trng_rnd64(n_bits) {
93 Err(hvc::trng::Error::NoEntropy) => continue,
94 res => return res,
95 }
96 }
97}
98
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000099pub fn random_array<const N: usize>() -> Result<[u8; N]> {
100 let mut arr = [0; N];
101 fill_with_entropy(&mut arr)?;
102 Ok(arr)
103}
104
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000105#[no_mangle]
106extern "C" fn CRYPTO_sysrand_for_seed(out: *mut u8, req: usize) {
107 CRYPTO_sysrand(out, req)
108}
109
110#[no_mangle]
111extern "C" fn CRYPTO_sysrand(out: *mut u8, req: usize) {
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +0000112 // SAFETY - We need to assume that out points to valid memory of size req.
113 let s = unsafe { core::slice::from_raw_parts_mut(out, req) };
Pierre-Clément Tosi78b68512023-06-22 09:40:16 +0000114 fill_with_entropy(s).unwrap()
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000115}