blob: a5a5f5f99d868509b5970a4f1aa60ca36a52fb2c [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 Tosicb38e6d2023-06-22 10:51:00 +000015//! Functions and drivers for obtaining true entropy.
16
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000017use crate::hvc;
18use core::fmt;
19use core::mem::size_of;
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000020use smccc::{self, Hvc};
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000021
Pierre-Clément Tosicb38e6d2023-06-22 10:51:00 +000022/// Error type for rand operations.
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000023pub enum Error {
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000024 /// No source of entropy found.
25 NoEntropySource,
26 /// Error during architectural SMCCC call.
27 Smccc(smccc::arch::Error),
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000028 /// Error during SMCCC TRNG call.
29 Trng(hvc::trng::Error),
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000030 /// Unsupported SMCCC version.
31 UnsupportedSmcccVersion(smccc::arch::Version),
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000032 /// Unsupported SMCCC TRNG version.
33 UnsupportedVersion((u16, u16)),
34}
35
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000036impl From<smccc::arch::Error> for Error {
37 fn from(e: smccc::arch::Error) -> Self {
38 Self::Smccc(e)
39 }
40}
41
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000042impl From<hvc::trng::Error> for Error {
43 fn from(e: hvc::trng::Error) -> Self {
44 Self::Trng(e)
45 }
46}
47
Pierre-Clément Tosicb38e6d2023-06-22 10:51:00 +000048/// Result type for rand operations.
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000049pub type Result<T> = core::result::Result<T, Error>;
50
51impl fmt::Display for Error {
52 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
53 match self {
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000054 Self::NoEntropySource => write!(f, "No source of entropy available"),
55 Self::Smccc(e) => write!(f, "Architectural SMCCC error: {e}"),
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000056 Self::Trng(e) => write!(f, "SMCCC TRNG error: {e}"),
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000057 Self::UnsupportedSmcccVersion(v) => write!(f, "Unsupported SMCCC version {v}"),
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000058 Self::UnsupportedVersion((x, y)) => {
59 write!(f, "Unsupported SMCCC TRNG version v{x}.{y}")
60 }
61 }
62 }
63}
64
Pierre-Clément Tosi78b68512023-06-22 09:40:16 +000065impl fmt::Debug for Error {
66 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
67 write!(f, "{self}")
68 }
69}
70
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000071/// Configure the source of entropy.
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000072pub(crate) fn init() -> Result<()> {
73 // SMCCC TRNG requires SMCCC v1.1.
74 match smccc::arch::version::<Hvc>()? {
75 smccc::arch::Version { major: 1, minor } if minor >= 1 => (),
76 version => return Err(Error::UnsupportedSmcccVersion(version)),
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000077 }
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000078
79 // TRNG_RND requires SMCCC TRNG v1.0.
80 match hvc::trng_version()? {
81 (1, _) => (),
82 version => return Err(Error::UnsupportedVersion(version)),
83 }
84
85 // TRNG_RND64 doesn't define any special capabilities so ignore the successful result.
86 let _ = hvc::trng_features(hvc::ARM_SMCCC_TRNG_RND64).map_err(|e| {
87 if e == hvc::trng::Error::NotSupported {
88 // SMCCC TRNG is currently our only source of entropy.
89 Error::NoEntropySource
90 } else {
91 e.into()
92 }
93 })?;
94
95 Ok(())
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +000096}
97
Pierre-Clément Tosi62ffc0d2023-06-30 09:31:56 +000098/// Fills a slice of bytes with true entropy.
99pub fn fill_with_entropy(s: &mut [u8]) -> Result<()> {
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +0000100 const MAX_BYTES_PER_CALL: usize = size_of::<hvc::TrngRng64Entropy>();
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +0000101
102 let (aligned, remainder) = s.split_at_mut(s.len() - s.len() % MAX_BYTES_PER_CALL);
103
104 for chunk in aligned.chunks_exact_mut(MAX_BYTES_PER_CALL) {
Pierre-Clément Tosicb0340c2023-03-06 11:49:39 +0000105 let (r, s, t) = repeat_trng_rnd(chunk.len())?;
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +0000106
107 let mut words = chunk.chunks_exact_mut(size_of::<u64>());
108 words.next().unwrap().clone_from_slice(&t.to_ne_bytes());
109 words.next().unwrap().clone_from_slice(&s.to_ne_bytes());
110 words.next().unwrap().clone_from_slice(&r.to_ne_bytes());
111 }
112
113 if !remainder.is_empty() {
114 let mut entropy = [0; MAX_BYTES_PER_CALL];
Pierre-Clément Tosicb0340c2023-03-06 11:49:39 +0000115 let (r, s, t) = repeat_trng_rnd(remainder.len())?;
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +0000116
117 let mut words = entropy.chunks_exact_mut(size_of::<u64>());
118 words.next().unwrap().clone_from_slice(&t.to_ne_bytes());
119 words.next().unwrap().clone_from_slice(&s.to_ne_bytes());
120 words.next().unwrap().clone_from_slice(&r.to_ne_bytes());
121
122 remainder.clone_from_slice(&entropy[..remainder.len()]);
123 }
124
125 Ok(())
126}
127
Pierre-Clément Tosicb0340c2023-03-06 11:49:39 +0000128fn repeat_trng_rnd(n_bytes: usize) -> hvc::trng::Result<hvc::TrngRng64Entropy> {
129 let bits = usize::try_from(u8::BITS).unwrap();
130 let n_bits = (n_bytes * bits).try_into().unwrap();
131 loop {
132 match hvc::trng_rnd64(n_bits) {
133 Err(hvc::trng::Error::NoEntropy) => continue,
134 res => return res,
135 }
136 }
137}
138
Pierre-Clément Tosicb38e6d2023-06-22 10:51:00 +0000139/// Generate an array of fixed-size initialized with true-random bytes.
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +0000140pub fn random_array<const N: usize>() -> Result<[u8; N]> {
141 let mut arr = [0; N];
142 fill_with_entropy(&mut arr)?;
143 Ok(arr)
144}
145
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000146#[no_mangle]
147extern "C" fn CRYPTO_sysrand_for_seed(out: *mut u8, req: usize) {
148 CRYPTO_sysrand(out, req)
149}
150
151#[no_mangle]
152extern "C" fn CRYPTO_sysrand(out: *mut u8, req: usize) {
Andrew Walbranc06e7342023-07-05 14:00:51 +0000153 // SAFETY: We need to assume that out points to valid memory of size req.
Pierre-Clément Tosia59103d2023-02-02 14:46:55 +0000154 let s = unsafe { core::slice::from_raw_parts_mut(out, req) };
Pierre-Clément Tosi78b68512023-06-22 09:40:16 +0000155 fill_with_entropy(s).unwrap()
Pierre-Clément Tosi90cd4f12023-02-17 11:19:56 +0000156}