-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathmain.rs
More file actions
443 lines (364 loc) · 13.4 KB
/
Copy pathmain.rs
File metadata and controls
443 lines (364 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/*++
Licensed under the Apache-2.0 license.
File Name:
main.rs
Abstract:
File contains main entry point for Caliptra ROM
--*/
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), no_main)]
#![cfg_attr(feature = "fake-rom", allow(unused_imports))]
#![cfg_attr(feature = "fips-test-hooks", allow(dead_code))]
use crate::rom_env::RomEnvFips;
use crate::{lock::lock_registers, print::HexBytes};
use caliptra_cfi_lib::{cfi_assert_eq, CfiCounter};
use caliptra_common::RomBootStatus::{KatComplete, KatStarted};
use caliptra_common::{handle_fatal_error, RomBootStatus};
use caliptra_kat::*;
use caliptra_registers::soc_ifc::SocIfcReg;
use core::hint::black_box;
use crate::lock::lock_cold_reset_reg;
use caliptra_drivers::{
cprintln, report_boot_status, report_fw_error_non_fatal, CaliptraError, ResetReason, Sha1,
ShaAccLockState, Trng,
};
use caliptra_error::CaliptraResult;
use caliptra_image_types::RomInfo;
use caliptra_kat::KatsEnv;
use rom_env::RomEnv;
use zeroize::Zeroize;
#[cfg(not(feature = "std"))]
core::arch::global_asm!(include_str!(concat!(
env!("OUT_DIR"),
"/start_preprocessed.S"
)));
mod crypto;
mod exception;
mod fht;
mod flow;
mod fuse;
mod key_ladder;
mod lock;
mod pcr;
mod rom_env;
mod wdt;
use caliptra_drivers::printer as print;
#[cfg(feature = "std")]
pub fn main() {}
const BANNER: &str = r#"
Running Caliptra ROM ...
"#;
extern "C" {
static CALIPTRA_ROM_INFO: RomInfo;
}
#[no_mangle]
pub extern "C" fn rom_entry() -> ! {
cprintln!("{}", BANNER);
// Create TRNG first for CFI initialization
let mut trng = match unsafe { rom_env::RomEnv::create_trng() } {
Ok(trng) => trng,
Err(e) => handle_fatal_error(e.into()),
};
// Initialize CFI before creating the rest of the environment and running KATs.
if cfg!(feature = "cfi") {
let mut entropy_gen = || {
trng.generate4()
.map_err(|e| caliptra_cfi_lib::CfiError(u32::from(e)))
};
CfiCounter::reset(&mut entropy_gen);
CfiCounter::reset(&mut entropy_gen);
CfiCounter::reset(&mut entropy_gen);
}
// Report CFI initialized immediately after CFI counters are reset,
// before any code that might use memcpy/memset (like AES KATs).
report_boot_status(RomBootStatus::CfiInitialized.into());
// Now create the rest of the environment and start the WDT.
let mut env = match unsafe { rom_env::RomEnv::new_from_registers(trng) } {
Ok(env) => env,
Err(e) => handle_fatal_error(e.into()),
};
// Seed the ABR entropy registers for SCA countermeasures
if let Err(e) = env.abr.seed_entropy(&mut env.trng) {
handle_fatal_error(e.into());
}
// Check if TRNG is correctly sourced as per hw config.
validate_trng_config(&mut env);
let reset_reason = env.soc_ifc.reset_reason();
// Lock the Cold Reset registers since they need to remain locked on an Update or Warm reset.
if reset_reason != ResetReason::ColdReset {
lock_cold_reset_reg(&mut env);
}
let lifecycle = match env.soc_ifc.lifecycle() {
caliptra_drivers::Lifecycle::Unprovisioned => "Unprovisioned",
caliptra_drivers::Lifecycle::Manufacturing => "Manufacturing",
caliptra_drivers::Lifecycle::Production => "Production",
caliptra_drivers::Lifecycle::Reserved2 => "Unknown",
};
cprintln!("[state] LifecycleState = {}", lifecycle);
// UDS programming.
if let Err(err) = crate::flow::UdsProgrammingFlow::program_uds(&mut env) {
handle_fatal_error(err.into());
}
if cfg!(feature = "fake-rom")
&& (env.soc_ifc.lifecycle() == caliptra_drivers::Lifecycle::Production)
&& !(env.soc_ifc.prod_en_in_fake_mode())
{
handle_fatal_error(CaliptraError::ROM_GLOBAL_FAKE_ROM_IN_PRODUCTION.into());
}
cprintln!(
"[state] DebugLocked = {}",
if env.soc_ifc.debug_locked() {
"Yes"
} else {
"No"
}
);
if env.soc_ifc.ocp_lock_enabled() {
cprintln!("[ROM] OCP-LOCK Supported");
}
// Set the ROM version
let rom_info = unsafe { &CALIPTRA_ROM_INFO };
if !cfg!(feature = "fake-rom") {
env.soc_ifc.set_rom_fw_rev_id(rom_info.version);
} else {
env.soc_ifc.set_rom_fw_rev_id(0xFFFF);
}
// Start the watchdog timer
wdt::start_wdt(&mut env.soc_ifc);
let initialized = if cfg!(feature = "fake-rom") {
InitializedDrivers {
sha1: Sha1::new().unwrap(),
}
} else {
let result = env.abr.with_mldsa87(|mut mldsa87| {
let mut kats_env = caliptra_kat::KatsEnv {
// sha256
sha256: &mut env.sha256,
// SHA2-512/384 Engine
sha2_512_384: &mut env.sha2_512_384,
// SHA2-512/384 Accelerator
sha2_512_384_acc: &mut env.sha2_512_384_acc,
// SHA3/SHAKE
sha3: &mut env.sha3,
// Hmac-512/384 Engine
hmac: &mut env.hmac,
// Cryptographically Secure Random Number Generator
trng: &mut env.trng,
// LMS Engine
lms: &mut env.lms,
// MLDSA87 Engine
mldsa87: &mut mldsa87,
// Ecc384 Engine
ecc384: &mut env.ecc384,
// AES-GCM Engine (for GCM and CMAC-KDF KATs)
aes_gcm: &mut env.aes_gcm,
// SHA Acc lock state.
// SHA Acc is guaranteed to be locked on Cold and Warm Resets;
// On an Update Reset, it is expected to be unlocked.
// Not having it unlocked will result in a fatal error.
sha_acc_lock_state: if reset_reason == ResetReason::UpdateReset {
ShaAccLockState::NotAcquired
} else {
ShaAccLockState::AssumedLocked
},
};
run_fips_tests(&mut kats_env)
});
match result {
Err(err) => handle_fatal_error(err.into()),
Ok(initialized) => initialized,
}
};
let mut env = RomEnvFips::from_non_crypto(env, initialized);
// Only run DBG unlock after KAT succeed since we use the sha acc peripherals
if let Err(err) = crate::flow::debug_unlock::debug_unlock(&mut env) {
handle_fatal_error(err.into());
}
if let Err(err) = flow::run(&mut env) {
//
// For the update reset case, when we fail the image validation
// we will need to continue to jump to the FMC after
// reporting the error in the registers.
//
if reset_reason == ResetReason::UpdateReset {
handle_non_fatal_error(err.into());
} else {
handle_fatal_error(err.into());
}
}
// Lock the datavault registers.
lock_registers(&mut env, reset_reason);
// Reset the CFI counter.
if cfg!(feature = "cfi") {
CfiCounter::corrupt();
}
// FIPS test hooks mode does not allow handoff to FMC to prevent incorrect/accidental usage
#[cfg(feature = "fips-test-hooks")]
handle_fatal_error(CaliptraError::ROM_GLOBAL_FIPS_HOOKS_ROM_EXIT.into());
#[cfg(not(any(feature = "no-fmc", feature = "fips-test-hooks")))]
launch_fmc(&mut env);
#[cfg(feature = "no-fmc")]
caliptra_drivers::ExitCtrl::exit(0);
}
fn run_fips_tests(env: &mut KatsEnv<'_, '_>) -> CaliptraResult<InitializedDrivers> {
report_boot_status(KatStarted.into());
cprintln!("[kat] SHA2-256");
Sha256Kat::default().execute(env.sha256)?;
#[cfg(feature = "fips-test-hooks")]
unsafe {
caliptra_drivers::FipsTestHook::halt_if_hook_set(
caliptra_drivers::FipsTestHook::HALT_SELF_TESTS,
)
};
// ROM integrity check needs SHA2-256 KAT to be executed first per FIPS requirement AS10.20.
let rom_info = unsafe { &CALIPTRA_ROM_INFO };
rom_integrity_test(env, &rom_info.sha256_digest)?;
let initialized_drivers = caliptra_kat::execute_kat(env)?;
report_boot_status(KatComplete.into());
Ok(initialized_drivers)
}
fn rom_integrity_test(env: &mut KatsEnv<'_, '_>, expected_digest: &[u32; 8]) -> CaliptraResult<()> {
// WARNING: It is undefined behavior to dereference a zero (null) pointer in
// rust code. This is only safe because the dereference is being done by an
// an assembly routine ([`caliptra_ureg::opt_riscv::copy_16_words`]) rather
// than dereferencing directly in Rust.
#[allow(clippy::zero_ptr)]
let rom_start = 0 as *const [u32; 16];
let n_blocks = unsafe { &CALIPTRA_ROM_INFO as *const RomInfo as usize / 64 };
let mut digest = unsafe { env.sha256.digest_blocks_raw(rom_start, n_blocks)? };
cprintln!("ROM Digest: {}", HexBytes(&<[u8; 32]>::from(digest)));
if digest.0 != *expected_digest {
digest.zeroize();
return Err(CaliptraError::ROM_INTEGRITY_FAILURE);
}
digest.zeroize();
Ok(())
}
fn launch_fmc(env: &mut RomEnv) -> ! {
// Function is defined in start.S
extern "C" {
fn exit_rom(entry: u32) -> !;
}
// Get the fmc entry point from data vault
let entry = env.persistent_data.get().rom.data_vault.fmc_entry_point();
cprintln!("[exit] Launching FMC @ 0x{:08X}", entry);
// Exit ROM and jump to specified entry point
unsafe { exit_rom(entry) }
}
#[no_mangle]
#[inline(never)]
extern "C" fn exception_handler(exception: &exception::ExceptionRecord) {
cprintln!(
"EXCEPTION mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X} ra=0x{:08X}",
exception.mcause,
exception.mscause,
exception.mepc,
exception.ra
);
{
let mut soc_ifc = unsafe { SocIfcReg::new() };
let soc_ifc = soc_ifc.regs_mut();
let ext_info = soc_ifc.cptra_fw_extended_error_info();
ext_info.at(0).write(|_| exception.mcause);
ext_info.at(1).write(|_| exception.mscause);
ext_info.at(2).write(|_| exception.mepc);
ext_info.at(3).write(|_| exception.ra);
}
handle_fatal_error(CaliptraError::ROM_GLOBAL_EXCEPTION.into());
}
#[no_mangle]
#[inline(never)]
extern "C" fn nmi_handler(exception: &exception::ExceptionRecord) {
let mut soc_ifc = unsafe { SocIfcReg::new() };
// If the NMI was fired by caliptra instead of the uC, this register
// contains the reason(s)
let err_interrupt_status = u32::from(
soc_ifc
.regs()
.intr_block_rf()
.error_internal_intr_r()
.read(),
);
cprintln!(
"NMI mcause=0x{:08X} mscause=0x{:08X} mepc=0x{:08X} ra=0x{:08X} error_internal_intr_r={:08X}",
exception.mcause,
exception.mscause,
exception.mepc,
exception.ra,
err_interrupt_status,
);
{
let soc_ifc = soc_ifc.regs_mut();
let ext_info = soc_ifc.cptra_fw_extended_error_info();
ext_info.at(0).write(|_| exception.mcause);
ext_info.at(1).write(|_| exception.mscause);
ext_info.at(2).write(|_| exception.mepc);
ext_info.at(3).write(|_| exception.ra);
ext_info.at(4).write(|_| err_interrupt_status);
}
// Check if the NMI was due to WDT expiry.
let mut error = CaliptraError::ROM_GLOBAL_NMI;
let wdt_status = soc_ifc.regs().cptra_wdt_status().read();
if wdt_status.t1_timeout() || wdt_status.t2_timeout() {
error = CaliptraError::ROM_GLOBAL_WDT_EXPIRED;
}
handle_fatal_error(error.into());
}
#[panic_handler]
#[inline(never)]
#[cfg(not(feature = "std"))]
fn rom_panic(_: &core::panic::PanicInfo) -> ! {
cprintln!("Panic!!");
panic_is_possible();
handle_fatal_error(CaliptraError::ROM_GLOBAL_PANIC.into());
}
fn handle_non_fatal_error(code: u32) {
cprintln!("ROM Non-Fatal Error: 0x{:08X}", code);
report_fw_error_non_fatal(code);
}
#[no_mangle]
extern "C" fn cfi_panic_handler(code: u32) -> ! {
cprintln!("[ROM] CFI Panic");
handle_fatal_error(code);
}
#[no_mangle]
#[inline(never)]
fn panic_is_possible() {
black_box(());
// The existence of this symbol is used to inform test_panic_missing
// that panics are possible. Do not remove or rename this symbol.
}
#[inline(always)]
fn validate_trng_config(env: &mut RomEnv) {
// NOTE: The usage of non-short-circuiting boolean operations (| and &) is
// explicit here, and necessary to prevent the compiler from inserting a ton
// of glitch-susceptible jumps into the generated code.
cfi_assert_eq(
env.soc_ifc.hw_config_internal_trng()
& (!env.soc_ifc.mfg_flag_rng_unavailable() | env.soc_ifc.debug_locked()),
matches!(env.trng, Trng::Internal(_)),
);
cfi_assert_eq(
!env.soc_ifc.hw_config_internal_trng()
& (!env.soc_ifc.mfg_flag_rng_unavailable() | env.soc_ifc.debug_locked()),
matches!(env.trng, Trng::External(_)),
);
cfi_assert_eq(
env.soc_ifc.mfg_flag_rng_unavailable() & !env.soc_ifc.debug_locked(),
matches!(env.trng, Trng::MfgMode()),
);
cfi_assert_eq(
env.soc_ifc.hw_config_internal_trng()
& (!env.soc_ifc.mfg_flag_rng_unavailable() | env.soc_ifc.debug_locked()),
matches!(env.trng, Trng::Internal(_)),
);
cfi_assert_eq(
!env.soc_ifc.hw_config_internal_trng()
& (!env.soc_ifc.mfg_flag_rng_unavailable() | env.soc_ifc.debug_locked()),
matches!(env.trng, Trng::External(_)),
);
cfi_assert_eq(
env.soc_ifc.mfg_flag_rng_unavailable() & !env.soc_ifc.debug_locked(),
matches!(env.trng, Trng::MfgMode()),
);
}