blob: 284cac04b8fd1615f5f7398504f33006332c1d9c [file] [log] [blame]
David Brownc8d62012021-10-27 15:03:48 -06001// Copyright (c) 2017-2021 Linaro LTD
David Browne2acfae2020-01-21 16:45:01 -07002// Copyright (c) 2017-2019 JUUL Labs
Roland Mikheld6703522023-04-27 14:24:30 +02003// Copyright (c) 2019-2023 Arm Limited
David Browne2acfae2020-01-21 16:45:01 -07004//
5// SPDX-License-Identifier: Apache-2.0
6
7//! Interface wrappers to C API entering to the bootloader
David Brownde7729e2017-01-09 10:41:35 -07008
David Brown65de6d12019-01-02 11:38:38 -07009use crate::area::AreaDesc;
David Brown76101572019-02-28 11:29:03 -070010use simflash::SimMultiFlash;
David Brown65de6d12019-01-02 11:38:38 -070011use crate::api;
David Brownde7729e2017-01-09 10:41:35 -070012
Antonio de Angelis65eb35c2022-11-22 14:11:47 +000013#[allow(unused)]
14use std::sync::Once;
15
David Brown5d155132024-06-10 14:07:32 -060016use std::borrow::Borrow;
17
David Brownc423ac42021-06-04 13:47:34 -060018/// The result of an invocation of `boot_go`. This is intentionally opaque so that we can provide
19/// accessors for everything we need from this.
20#[derive(Debug)]
David Brown6d47d422021-06-04 14:41:33 -060021pub enum BootGoResult {
22 /// This run was stopped by the flash simulation mechanism.
23 Stopped,
24 /// The bootloader ran to completion with the following data.
25 Normal {
26 result: i32,
27 asserts: u8,
David Brownd82de8c2021-06-04 15:08:25 -060028
29 resp: api::BootRsp,
David Brown6d47d422021-06-04 14:41:33 -060030 },
David Brownc423ac42021-06-04 13:47:34 -060031}
32
33impl BootGoResult {
34 /// Was this run interrupted.
35 pub fn interrupted(&self) -> bool {
David Brown6d47d422021-06-04 14:41:33 -060036 matches!(self, BootGoResult::Stopped)
David Brownc423ac42021-06-04 13:47:34 -060037 }
38
39 /// Was this boot run successful (returned 0)
40 pub fn success(&self) -> bool {
David Brown6d47d422021-06-04 14:41:33 -060041 matches!(self, BootGoResult::Normal { result: 0, .. })
David Brownc423ac42021-06-04 13:47:34 -060042 }
43
44 /// Success, but also no asserts.
45 pub fn success_no_asserts(&self) -> bool {
David Brown6d47d422021-06-04 14:41:33 -060046 matches!(self, BootGoResult::Normal {
47 result: 0,
48 asserts: 0,
David Brownd82de8c2021-06-04 15:08:25 -060049 ..
David Brown6d47d422021-06-04 14:41:33 -060050 })
David Brownc423ac42021-06-04 13:47:34 -060051 }
52
David Brown6d47d422021-06-04 14:41:33 -060053 /// Get the asserts count. An interrupted run will be considered to have no asserts.
David Brownc423ac42021-06-04 13:47:34 -060054 pub fn asserts(&self) -> u8 {
David Brown6d47d422021-06-04 14:41:33 -060055 match self {
56 BootGoResult::Normal { asserts, .. } => *asserts,
57 _ => 0,
58 }
David Brownc423ac42021-06-04 13:47:34 -060059 }
David Brownd82de8c2021-06-04 15:08:25 -060060
61 /// Retrieve the 'resp' field that is filled in.
62 pub fn resp(&self) -> Option<&api::BootRsp> {
63 match self {
64 BootGoResult::Normal { resp, .. } => Some(resp),
65 _ => None,
66 }
67 }
David Brownc423ac42021-06-04 13:47:34 -060068}
69
David Brownde7729e2017-01-09 10:41:35 -070070/// Invoke the bootloader on this flash device.
David Brown76101572019-02-28 11:29:03 -070071pub fn boot_go(multiflash: &mut SimMultiFlash, areadesc: &AreaDesc,
Raef Coles3fd3ecc2021-10-15 11:14:12 +010072 counter: Option<&mut i32>, image_index: Option<i32>,
73 catch_asserts: bool) -> BootGoResult {
Antonio de Angelis65eb35c2022-11-22 14:11:47 +000074 init_crypto();
75
David Brown7cc45262021-03-10 05:13:44 -070076 for (&dev_id, flash) in multiflash.iter_mut() {
77 api::set_flash(dev_id, flash);
Fabio Utzig8000e322019-08-05 08:14:32 -030078 }
79 let mut sim_ctx = api::CSimContext {
80 flash_counter: match counter {
David Brownee61c832017-11-06 11:13:25 -070081 None => 0,
82 Some(ref c) => **c as libc::c_int
Fabio Utzig8000e322019-08-05 08:14:32 -030083 },
84 jumped: 0,
85 c_asserts: 0,
86 c_catch_asserts: if catch_asserts { 1 } else { 0 },
87 boot_jmpbuf: [0; 16],
88 };
David Brownd216b202021-06-04 10:14:33 -060089 let mut rsp = api::BootRsp {
90 br_hdr: std::ptr::null(),
91 flash_dev_id: 0,
92 image_off: 0,
93 };
Raef Coles3fd3ecc2021-10-15 11:14:12 +010094 let result: i32 = unsafe {
David Brown5d155132024-06-10 14:07:32 -060095 let adesc = areadesc.get_c();
Raef Coles3fd3ecc2021-10-15 11:14:12 +010096 match image_index {
97 None => raw::invoke_boot_go(&mut sim_ctx as *mut _,
David Brown5d155132024-06-10 14:07:32 -060098 adesc.borrow() as *const _,
Raef Coles3fd3ecc2021-10-15 11:14:12 +010099 &mut rsp as *mut _, -1) as i32,
100 Some(i) => raw::invoke_boot_go(&mut sim_ctx as *mut _,
David Brown5d155132024-06-10 14:07:32 -0600101 adesc.borrow() as *const _,
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100102 &mut rsp as *mut _,
103 i as i32) as i32
104 }
Fabio Utzig8000e322019-08-05 08:14:32 -0300105 };
106 let asserts = sim_ctx.c_asserts;
David Brown8608c532021-03-10 05:18:11 -0700107 if let Some(c) = counter {
108 *c = sim_ctx.flash_counter;
109 }
David Brown7cc45262021-03-10 05:13:44 -0700110 for &dev_id in multiflash.keys() {
111 api::clear_flash(dev_id);
112 }
David Brown6d47d422021-06-04 14:41:33 -0600113 if result == -0x13579 {
114 BootGoResult::Stopped
115 } else {
David Brownd82de8c2021-06-04 15:08:25 -0600116 BootGoResult::Normal { result, asserts, resp: rsp }
David Brown6d47d422021-06-04 14:41:33 -0600117 }
David Brownde7729e2017-01-09 10:41:35 -0700118}
119
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300120pub fn boot_trailer_sz(align: u32) -> u32 {
Christopher Collins2adef702019-05-22 14:37:31 -0700121 unsafe { raw::boot_trailer_sz(align) }
David Brownde7729e2017-01-09 10:41:35 -0700122}
123
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300124pub fn boot_status_sz(align: u32) -> u32 {
125 unsafe { raw::boot_status_sz(align) }
126}
127
Fabio Utziga0bc9b52017-06-28 09:19:55 -0300128pub fn boot_magic_sz() -> usize {
David Brown2b8a6952019-10-01 16:14:53 -0600129 unsafe { raw::boot_magic_sz() as usize }
Fabio Utziga0bc9b52017-06-28 09:19:55 -0300130}
131
132pub fn boot_max_align() -> usize {
David Browne0bb1f92019-10-01 15:57:01 -0600133 unsafe { raw::boot_max_align() as usize }
Fabio Utziga0bc9b52017-06-28 09:19:55 -0300134}
135
Fabio Utzig1e48b912018-09-18 09:04:18 -0300136pub fn rsa_oaep_encrypt(pubkey: &[u8], seckey: &[u8]) -> Result<[u8; 256], &'static str> {
137 unsafe {
138 let mut encbuf: [u8; 256] = [0; 256];
139 if raw::rsa_oaep_encrypt_(pubkey.as_ptr(), pubkey.len() as u32,
140 seckey.as_ptr(), seckey.len() as u32,
141 encbuf.as_mut_ptr()) == 0 {
142 return Ok(encbuf);
143 }
David Brownc20bbb22021-03-10 05:19:14 -0700144 Err("Failed to encrypt buffer")
Fabio Utzig1e48b912018-09-18 09:04:18 -0300145 }
146}
147
Salome Thirot6fdbf552021-05-14 16:46:14 +0100148pub fn kw_encrypt(kek: &[u8], seckey: &[u8], keylen: u32) -> Result<Vec<u8>, &'static str> {
Fabio Utzig1e48b912018-09-18 09:04:18 -0300149 unsafe {
Salome Thirot6fdbf552021-05-14 16:46:14 +0100150 let mut encbuf = vec![0u8; 24];
151 if keylen == 32 {
152 encbuf = vec![0u8; 40];
153 }
Fabio Utzig1e48b912018-09-18 09:04:18 -0300154 if raw::kw_encrypt_(kek.as_ptr(), seckey.as_ptr(), encbuf.as_mut_ptr()) == 0 {
155 return Ok(encbuf);
156 }
David Brownc20bbb22021-03-10 05:19:14 -0700157 Err("Failed to encrypt buffer")
Fabio Utzig1e48b912018-09-18 09:04:18 -0300158 }
159}
160
Roland Mikheld6703522023-04-27 14:24:30 +0200161pub fn set_security_counter(image_index: u32, security_counter_value: u32) {
162 api::sim_set_nv_counter_for_image(image_index, security_counter_value);
163}
164
165pub fn get_security_counter(image_index: u32) -> u32 {
166 let mut counter_val: u32 = 0;
167 api::sim_get_nv_counter_for_image(image_index, &mut counter_val as *mut u32);
168 return counter_val;
169}
170
David Brownde7729e2017-01-09 10:41:35 -0700171mod raw {
David Brown65de6d12019-01-02 11:38:38 -0700172 use crate::area::CAreaDesc;
David Brownd216b202021-06-04 10:14:33 -0600173 use crate::api::{BootRsp, CSimContext};
David Brownde7729e2017-01-09 10:41:35 -0700174
175 extern "C" {
176 // This generates a warning about `CAreaDesc` not being foreign safe. There doesn't appear to
177 // be any way to get rid of this warning. See https://github.com/rust-lang/rust/issues/34798
178 // for information and tracking.
David Brownd216b202021-06-04 10:14:33 -0600179 pub fn invoke_boot_go(sim_ctx: *mut CSimContext, areadesc: *const CAreaDesc,
Raef Coles3fd3ecc2021-10-15 11:14:12 +0100180 rsp: *mut BootRsp, image_index: libc::c_int) -> libc::c_int;
David Brownde7729e2017-01-09 10:41:35 -0700181
Fabio Utzig3fbbdac2019-12-19 15:18:23 -0300182 pub fn boot_trailer_sz(min_write_sz: u32) -> u32;
183 pub fn boot_status_sz(min_write_sz: u32) -> u32;
Fabio Utziga0bc9b52017-06-28 09:19:55 -0300184
David Brown2b8a6952019-10-01 16:14:53 -0600185 pub fn boot_magic_sz() -> u32;
David Browne0bb1f92019-10-01 15:57:01 -0600186 pub fn boot_max_align() -> u32;
Fabio Utzig92be3fb2017-12-05 08:52:53 -0200187
Fabio Utzig1e48b912018-09-18 09:04:18 -0300188 pub fn rsa_oaep_encrypt_(pubkey: *const u8, pubkey_len: libc::c_uint,
189 seckey: *const u8, seckey_len: libc::c_uint,
190 encbuf: *mut u8) -> libc::c_int;
191
192 pub fn kw_encrypt_(kek: *const u8, seckey: *const u8,
193 encbuf: *mut u8) -> libc::c_int;
Antonio de Angelis65eb35c2022-11-22 14:11:47 +0000194
195 #[allow(unused)]
196 pub fn psa_crypto_init() -> u32;
197
198 #[allow(unused)]
199 pub fn mbedtls_test_enable_insecure_external_rng();
David Brownde7729e2017-01-09 10:41:35 -0700200 }
201}
Antonio de Angelis65eb35c2022-11-22 14:11:47 +0000202
203#[allow(unused)]
204static PSA_INIT_SYNC: Once = Once::new();
205
206#[allow(unused)]
207static MBEDTLS_EXTERNAL_RNG_ENABLE_SYNC: Once = Once::new();
208
209#[cfg(feature = "psa-crypto-api")]
210fn init_crypto() {
211 PSA_INIT_SYNC.call_once(|| {
212 assert_eq!(unsafe { raw::psa_crypto_init() }, 0);
213 });
214
215 /* The PSA APIs require properly initialisation of the entropy subsystem
216 * The configuration adds the option MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG when the
217 * psa-crypto-api feature is enabled. As a result the tests use the implementation
218 * of the test external rng that needs to be initialised before being able to use it
219 */
220 MBEDTLS_EXTERNAL_RNG_ENABLE_SYNC.call_once(|| {
221 unsafe { raw::mbedtls_test_enable_insecure_external_rng() }
222 });
223}
224
225#[cfg(not(feature = "psa-crypto-api"))]
226fn init_crypto() {
227 // When the feature is not enabled, the init is just empty
228}