1 /*
2 * Copyright (C) 2024 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 //! Module providing access to platform specific functions used by the library.
18 use hwcryptohal_common::{err::HwCryptoError, hwcrypto_err};
19 use kmr_common::crypto;
20 use log::error;
21
22 use crate::ffi_bindings;
23
24 const NANOSECONDS_IN_1_MS: u64 = 1000000;
25
26 // Placeholder for function to compare VM identities. Identities will probably be based on DICE,
27 // a simple comparison could be done if the DICE chains are unencrypted and the order of fields is
28 // always the same.
29 #[allow(dead_code)]
compare_vm_identities(vm1_identity: &[u8], vm2_identity: &[u8]) -> bool30 pub(crate) fn compare_vm_identities(vm1_identity: &[u8], vm2_identity: &[u8]) -> bool {
31 (vm1_identity.len() == vm2_identity.len()) && openssl::memcmp::eq(vm1_identity, vm2_identity)
32 }
33
34 #[derive(Default)]
35 pub(crate) struct PlatformRng;
36
37 impl crypto::Rng for PlatformRng {
add_entropy(&mut self, data: &[u8])38 fn add_entropy(&mut self, data: &[u8]) {
39 trusty_rng_add_entropy(data);
40 }
fill_bytes(&mut self, dest: &mut [u8])41 fn fill_bytes(&mut self, dest: &mut [u8]) {
42 openssl::rand::rand_bytes(dest)
43 .expect("shouldn't happen, function never fails on BoringSSL");
44 }
45 }
46
47 /// Add entropy to Trusty's RNG.
trusty_rng_add_entropy(data: &[u8])48 pub fn trusty_rng_add_entropy(data: &[u8]) {
49 // Safety: `data` is a valid slice
50 let rc = unsafe { ffi_bindings::sys::trusty_rng_add_entropy(data.as_ptr(), data.len()) };
51 if rc != 0 {
52 panic!("trusty_rng_add_entropy() failed, {}", rc)
53 }
54 }
55
current_epoch_time_ms() -> Result<u64, HwCryptoError>56 pub fn current_epoch_time_ms() -> Result<u64, HwCryptoError> {
57 let mut secure_time_ns = 0;
58 // Safety: external syscall gets valid raw pointer to a `u64`.
59 let rc = unsafe { trusty_sys::gettime(0, 0, &mut secure_time_ns) };
60 if rc < 0 {
61 // Couldn't get time
62 error!("Error calling trusty_gettime: {:#x}", rc);
63 Err(hwcrypto_err!(GENERIC_ERROR, "error calling trusty_gettime: {:#x}", rc))
64 } else {
65 // secure_time_ns is positive, so casting is correct
66 Ok((secure_time_ns as u64) / NANOSECONDS_IN_1_MS)
67 }
68 }
69