Software APIs
rom.c
1 // Copyright lowRISC contributors (OpenTitan project).
2 // Licensed under the Apache License, Version 2.0, see LICENSE for details.
3 // SPDX-License-Identifier: Apache-2.0
4 
5 #include "sw/device/silicon_creator/rom/rom.h"
6 
7 #include <assert.h>
8 #include <stdbool.h>
9 #include <stdint.h>
10 
13 #include "sw/device/lib/base/csr.h"
18 #include "sw/device/silicon_creator/lib/base/boot_measurements.h"
20 #include "sw/device/silicon_creator/lib/base/static_critical_version.h"
21 #include "sw/device/silicon_creator/lib/boot_data.h"
22 #include "sw/device/silicon_creator/lib/boot_log.h"
23 #include "sw/device/silicon_creator/lib/cfi.h"
24 #include "sw/device/silicon_creator/lib/chip_info.h"
25 #include "sw/device/silicon_creator/lib/drivers/alert.h"
26 #include "sw/device/silicon_creator/lib/drivers/ast.h"
27 #include "sw/device/silicon_creator/lib/drivers/flash_ctrl.h"
28 #include "sw/device/silicon_creator/lib/drivers/hmac.h"
29 #include "sw/device/silicon_creator/lib/drivers/ibex.h"
30 #include "sw/device/silicon_creator/lib/drivers/keymgr.h"
31 #include "sw/device/silicon_creator/lib/drivers/lifecycle.h"
32 #include "sw/device/silicon_creator/lib/drivers/otp.h"
33 #include "sw/device/silicon_creator/lib/drivers/pinmux.h"
34 #include "sw/device/silicon_creator/lib/drivers/pwrmgr.h"
35 #include "sw/device/silicon_creator/lib/drivers/retention_sram.h"
36 #include "sw/device/silicon_creator/lib/drivers/rnd.h"
37 #include "sw/device/silicon_creator/lib/drivers/rstmgr.h"
38 #include "sw/device/silicon_creator/lib/drivers/sensor_ctrl.h"
39 #include "sw/device/silicon_creator/lib/drivers/uart.h"
40 #include "sw/device/silicon_creator/lib/drivers/watchdog.h"
41 #include "sw/device/silicon_creator/lib/error.h"
42 #include "sw/device/silicon_creator/lib/otbn_boot_services.h"
43 #include "sw/device/silicon_creator/lib/shutdown.h"
44 #include "sw/device/silicon_creator/lib/sigverify/sigverify.h"
45 #include "sw/device/silicon_creator/lib/stack_utilization.h"
46 #include "sw/device/silicon_creator/rom/boot_policy.h"
47 #include "sw/device/silicon_creator/rom/boot_policy_ptrs.h"
48 #include "sw/device/silicon_creator/rom/bootstrap.h"
49 #include "sw/device/silicon_creator/rom/rom_epmp.h"
50 #include "sw/device/silicon_creator/rom/rom_state.h"
51 #include "sw/device/silicon_creator/rom/sigverify_keys_ecdsa_p256.h"
52 #include "sw/device/silicon_creator/rom/sigverify_keys_spx.h"
53 #include "sw/device/silicon_creator/rom/sigverify_otp_keys.h"
54 
55 #include "hmac_regs.h" // Generated.
57 #include "otp_ctrl_regs.h"
58 #include "rstmgr_regs.h"
59 
60 /**
61  * Table of forward branch Control Flow Integrity (CFI) counters.
62  *
63  * Columns: Name, Initital Value.
64  *
65  * Each counter is indexed by Name. The Initial Value is used to initialize the
66  * counters with unique values with a good hamming distance. The values are
67  * restricted to 11-bit to be able use immediate load instructions.
68 
69  * Encoding generated with
70  * $ ./util/design/sparse-fsm-encode.py -d 6 -m 6 -n 11 \
71  * -s 1630646358 --language=c
72  *
73  * Minimum Hamming distance: 6
74  * Maximum Hamming distance: 8
75  * Minimum Hamming weight: 5
76  * Maximum Hamming weight: 8
77  */
78 // clang-format off
79 #define ROM_CFI_FUNC_COUNTERS_TABLE(X) \
80  X(kCfiRomMain, 0x14b) \
81  X(kCfiRomInit, 0x7dc) \
82  X(kCfiRomVerify, 0x5a7) \
83  X(kCfiRomTryBoot, 0x235) \
84  X(kCfiRomPreBootCheck, 0x43a) \
85  X(kCfiRomBoot, 0x2e2)
86 // clang-format on
87 
88 // Define counters and constant values required by the CFI counter macros.
89 CFI_DEFINE_COUNTERS(rom_counters, ROM_CFI_FUNC_COUNTERS_TABLE);
90 
91 // Life cycle state of the chip.
92 lifecycle_state_t lc_state = (lifecycle_state_t)0;
93 // Boot data from flash.
95 // Whether we are "simply" waking from low power mode.
96 static hardened_bool_t waking_from_low_power = 0;
97 // First stage (ROM-->ROM_EXT) secure boot keys loaded from OTP.
98 static sigverify_otp_key_ctx_t sigverify_ctx;
99 // A ram copy of the OTP word controlling how to handle flash ECC errors.
100 uint32_t flash_ecc_exc_handler_en;
101 // A check value for the reset reason.
102 uint32_t reset_reason_check;
103 
104 static inline bool rom_console_enabled(void) {
105  return otp_read32(OTP_CTRL_PARAM_OWNER_SW_CFG_ROM_BANNER_EN_OFFSET) !=
107 }
108 
109 /**
110  * Prints a banner during bootup.
111  *
112  * OpenTitan:ssss-pppp-rr
113  *
114  * Where:
115  * - ssss: Silicon Creator ID.
116  * - pppp: Product ID.
117  * - rr: Revision ID.
118  */
119 static void rom_banner(void) {
120  if (!rom_console_enabled()) {
121  return;
122  }
123  // a t i T n e p O
124  const uint64_t kTitle1 = 0x617469546e65704f;
125  // : n
126  const uint32_t kTitle2 = 0x3a6e;
127  const uint32_t kNewline = 0x0a0d;
129  lifecycle_hw_rev_get(&hw);
130  uart_write_imm(kTitle1);
131  uart_write_imm(kTitle2);
132  uart_write_hex(hw.silicon_creator_id, sizeof(hw.silicon_creator_id), '-');
133  uart_write_hex(hw.product_id, sizeof(hw.product_id), '-');
134  uart_write_hex(hw.revision_id, sizeof(hw.revision_id), kNewline);
135 }
136 
137 /**
138  * Prints a status message indicating that the ROM is entering bootstrap mode.
139  */
140 static void rom_bootstrap_message(void) {
141  // a r t s t o o b
142  const uint64_t kBootstrap1 = 0x61727473746f6f62;
143  // \n\r 1 : p
144  const uint64_t kBootstrap2 = 0x0a0d313a70;
145  uart_write_imm(kBootstrap1);
146  uart_write_imm(kBootstrap2);
147 }
148 
149 /**
150  * Performs once-per-boot initialization of ROM modules and peripherals.
151  */
153 static rom_error_t rom_init(void) {
154  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomInit, 1);
155  sec_mmio_init();
156  uint32_t reset_reasons = rstmgr_reason_get();
157  reset_reason_check =
158  reset_reasons ^
159  (otp_read32(
160  OTP_CTRL_PARAM_OWNER_SW_CFG_ROM_RESET_REASON_CHECK_VALUE_OFFSET) &
161  0xFFFF);
162  if (reset_reasons != (1U << RSTMGR_RESET_INFO_LOW_POWER_EXIT_BIT)) {
163  // The above compares all bits, rather than just the one indication "low
164  // power exit", because if there is any other reset reason, besides
165  // LOW_POWER_EXIT, it means that the chip did full reset while coming out of
166  // low power. In that case, the state of AON IP blocks would have been
167  // reset, and the ROM should not treat this as "waking from low power".
168  waking_from_low_power = kHardenedBoolFalse;
169 
170  // Initialize pinmux configuration so we can use the UART, (except if waking
171  // up from low power, as the pinmux will in such case have retained its
172  // previous configuration.)
173  pinmux_init();
174  } else {
175  waking_from_low_power = kHardenedBoolTrue;
176  }
177 
178  // Configure UART0 as stdout.
179  uart_init(kUartNCOValue);
180 
181  // Set static_critical region format version.
182  static_critical_version = kStaticCriticalVersion2;
183 
184  // There are no conditional checks before writing to this CSR because it is
185  // expected that if relevant Ibex countermeasures are disabled, this will
186  // result in a nop.
187  CSR_WRITE(CSR_REG_SECURESEED, rnd_uint32());
188 
189  // Write the OTP value to bits 0 to 5 of the cpuctrl CSR.
190  uint32_t cpuctrl_csr;
191  CSR_READ(CSR_REG_CPUCTRL, &cpuctrl_csr);
192  cpuctrl_csr = bitfield_field32_write(
193  cpuctrl_csr, (bitfield_field32_t){.mask = 0x3f, .index = 0},
194  otp_read32(OTP_CTRL_PARAM_CREATOR_SW_CFG_CPUCTRL_OFFSET));
195  CSR_WRITE(CSR_REG_CPUCTRL, cpuctrl_csr);
196 
197  lc_state = lifecycle_state_get();
198 
199  // Update epmp config for debug rom according to lifecycle state.
200  rom_epmp_config_debug_rom(lc_state);
201 
202  if (launder32(waking_from_low_power) != kHardenedBoolTrue) {
203  HARDENED_CHECK_EQ(waking_from_low_power, kHardenedBoolFalse);
204  // Re-initialize the watchdog timer, if the RESET was caused by anything
205  // besides waking from low power (which would have left the watchdog in its
206  // previous configuration).
207  watchdog_init(lc_state);
208  SEC_MMIO_WRITE_INCREMENT(kWatchdogSecMmioInit);
209 
210  // Re-initialize sensor_ctrl.
211  HARDENED_RETURN_IF_ERROR(sensor_ctrl_configure(lc_state));
212  pwrmgr_cdc_sync(kSensorCtrlSyncCycles);
213  } else {
214  HARDENED_CHECK_EQ(waking_from_low_power, kHardenedBoolTrue);
215  }
216 
217  // Initialize the shutdown policy.
218  HARDENED_RETURN_IF_ERROR(shutdown_init(lc_state));
219 
220  flash_ctrl_init();
221  SEC_MMIO_WRITE_INCREMENT(kFlashCtrlSecMmioInit);
222  flash_ecc_exc_handler_en = otp_read32(
223  OTP_CTRL_PARAM_OWNER_SW_CFG_ROM_FLASH_ECC_EXC_HANDLER_EN_OFFSET);
224 
225  // Initialize in-memory copy of the ePMP register configuration.
226  rom_epmp_state_init(lc_state);
227 
228  // Check that AST is in the expected state.
229  HARDENED_RETURN_IF_ERROR(ast_check(lc_state));
230 
231  // Initialize the retention RAM based on the reset reason and the OTP value.
232  // Note: Retention RAM is always reset on PoR regardless of the OTP value.
233  uint32_t reset_mask =
234  (1 << kRstmgrReasonPowerOn) |
235  otp_read32(OTP_CTRL_PARAM_CREATOR_SW_CFG_RET_RAM_RESET_MASK_OFFSET);
236  if ((reset_reasons & reset_mask) != 0) {
237  retention_sram_init();
238  // The high nybble controls the retram readback enable.
239  retention_sram_readback_enable(
240  otp_read32(OTP_CTRL_PARAM_OWNER_SW_CFG_ROM_SRAM_READBACK_EN_OFFSET) >>
241  4);
242  retention_sram_get()->creator.last_shutdown_reason = kErrorOk;
243  }
244 
245  // Initialize boot_log
246  boot_log_t *boot_log = &retention_sram_get()->creator.boot_log;
247  memset(boot_log, 0, sizeof(*boot_log));
248  boot_log->identifier = kBootLogIdentifier;
249  boot_log->chip_version = kChipInfo.scm_revision;
251  reset_reasons & reset_mask ? kHardenedBoolTrue : kHardenedBoolFalse;
252 
253  // Always store the retention RAM version so the ROM_EXT can depend on its
254  // accuracy even after scrambling.
255  retention_sram_get()->version = kRetentionSramVersion4;
256 
257  // Store the reset reason in retention RAM.
258  retention_sram_get()->creator.reset_reasons = reset_reasons;
259 
260  // Print a nice message.
261  if (waking_from_low_power != kHardenedBoolTrue) {
262  rom_banner();
263  }
264  // This function is a NOP unless ROM is built for an fpga.
266 
267  // Double check the reset reason value against the OTP-defined value.
268  reset_reason_check = launder32(reset_reason_check) ^ rstmgr_reason_get();
269  uint32_t check_val =
270  otp_read32(
271  OTP_CTRL_PARAM_OWNER_SW_CFG_ROM_RESET_REASON_CHECK_VALUE_OFFSET) >>
272  16;
273  if (launder32(check_val) != kHardenedBoolFalse) {
274  // Double-check the reset reason.
275  if (launder32(check_val) == reset_reason_check) {
276  HARDENED_CHECK_EQ(check_val, reset_reason_check);
277  // Reset reasons equal, do nothing.
278  } else {
279  return kErrorRomResetReasonFault;
280  }
281  } else {
282  // Configured to not double-check the reset reason.
284  }
285 
286  // Clear the register if configured to do so.
287  if (otp_read32(
288  OTP_CTRL_PARAM_OWNER_SW_CFG_ROM_PRESERVE_RESET_REASON_EN_OFFSET) !=
290  rstmgr_reason_clear(reset_reasons);
291  }
292 
293  sec_mmio_check_values(rnd_uint32());
294  sec_mmio_check_counters(/*expected_check_count=*/1);
295 
296  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomInit, 2);
297  return kErrorOk;
298 }
299 
300 /**
301  * Verifies a ROM_EXT.
302  *
303  * This function performs bounds checks on the fields of the manifest, checks
304  * its `identifier` and `security_version` fields, and verifies its signature.
305  *
306  * @param Manifest of the ROM_EXT to be verified.
307  * @param[out] flash_exec Value to write to the flash_ctrl EXEC register.
308  * @return Result of the operation.
309  */
311 static rom_error_t rom_verify(const manifest_t *manifest,
312  uint32_t *flash_exec) {
313  // Check security version and manifest constraints.
314  //
315  // The poisoning work (`anti_rollback`) invalidates signatures if the
316  // security version of the manifest is smaller than the minimum required
317  // security version.
318  const uint32_t extra_word = UINT32_MAX;
319  const uint32_t *anti_rollback = NULL;
320  size_t anti_rollback_len = 0;
321  if (launder32(manifest->security_version) <
323  anti_rollback = &extra_word;
324  anti_rollback_len = sizeof(extra_word);
325  }
326  *flash_exec = 0;
327  HARDENED_RETURN_IF_ERROR(boot_policy_manifest_check(manifest, &boot_data));
328 
329  // Load OTBN boot services app.
330  //
331  // This will be reused by later boot stages.
332  HARDENED_RETURN_IF_ERROR(otbn_boot_app_load());
333  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomVerify, 1);
334 
335  // Load secure boot keys from OTP into RAM.
336  HARDENED_RETURN_IF_ERROR(sigverify_otp_keys_init(&sigverify_ctx));
337  // ECDSA key.
338  const ecdsa_p256_public_key_t *ecdsa_key = NULL;
339  HARDENED_RETURN_IF_ERROR(sigverify_ecdsa_p256_key_get(
340  &sigverify_ctx,
341  sigverify_ecdsa_p256_key_id_get(&manifest->ecdsa_public_key), lc_state,
342  &ecdsa_key));
343  // SPX+ key.
344  const sigverify_spx_key_t *spx_key = NULL;
345  sigverify_spx_config_id_t spx_config = 0;
346  const sigverify_spx_signature_t *spx_signature = NULL;
347  uint32_t sigverify_spx_en = sigverify_spx_verify_enabled(lc_state);
348  if (launder32(sigverify_spx_en) != kSigverifySpxDisabledOtp) {
349  const manifest_ext_spx_key_t *ext_spx_key;
350  HARDENED_RETURN_IF_ERROR(manifest_ext_get_spx_key(manifest, &ext_spx_key));
351  HARDENED_RETURN_IF_ERROR(sigverify_spx_key_get(
352  &sigverify_ctx, sigverify_spx_key_id_get(&ext_spx_key->key), lc_state,
353  &spx_key, &spx_config));
354  const manifest_ext_spx_signature_t *ext_spx_signature;
355  HARDENED_RETURN_IF_ERROR(
356  manifest_ext_get_spx_signature(manifest, &ext_spx_signature));
357  spx_signature = &ext_spx_signature->signature;
358  } else {
359  HARDENED_CHECK_EQ(sigverify_spx_en, kSigverifySpxDisabledOtp);
360  }
361 
362  // Measure ROM_EXT and portions of manifest via SHA256 digest.
363  // Initialize ROM_EXT measurement in .static_critical with garbage.
364  memset(boot_measurements.rom_ext.data, (int)rnd_uint32(),
365  sizeof(boot_measurements.rom_ext.data));
366  // Add anti-rollback poisoning word to measurement.
367  hmac_sha256_init();
368  hmac_sha256_update(anti_rollback, anti_rollback_len);
369  HARDENED_CHECK_GE(manifest->security_version,
371  // Add manifest usage constraints to the measurement.
372  manifest_usage_constraints_t usage_constraints_from_hw;
373  sigverify_usage_constraints_get(manifest->usage_constraints.selector_bits,
374  &usage_constraints_from_hw);
375  hmac_sha256_update(&usage_constraints_from_hw,
376  sizeof(usage_constraints_from_hw));
377  // Add remaining part of manifest / ROM_EXT image to the measurement.
378  manifest_digest_region_t digest_region = manifest_digest_region_get(manifest);
379  // Add remaining part of manifest / ROM_EXT image to the measurement.
380  hmac_sha256_update(digest_region.start, digest_region.length);
381  hmac_sha256_process();
382  hmac_digest_t act_digest;
383  hmac_sha256_final(&act_digest);
384  // Copy the ROM_EXT measurement to the .static_critical section.
385  static_assert(sizeof(boot_measurements.rom_ext) == sizeof(act_digest),
386  "Unexpected ROM_EXT digest size.");
387  memcpy(&boot_measurements.rom_ext, &act_digest,
388  sizeof(boot_measurements.rom_ext));
389 
390  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomVerify, 2);
391 
392  /**
393  * Verify the ECDSA/SPX+ signatures of ROM_EXT.
394  *
395  * We swap the order of signature verifications randomly.
396  */
397  *flash_exec = 0;
398  if (rnd_uint32() < 0x80000000) {
399  HARDENED_RETURN_IF_ERROR(sigverify_ecdsa_p256_verify(
400  &manifest->ecdsa_signature, ecdsa_key, &act_digest, flash_exec));
401 
402  return sigverify_spx_verify(
403  spx_signature, spx_key, spx_config, lc_state,
404  &usage_constraints_from_hw, sizeof(usage_constraints_from_hw),
405  anti_rollback, anti_rollback_len, digest_region.start,
406  digest_region.length, &act_digest, flash_exec);
407  } else {
408  HARDENED_RETURN_IF_ERROR(sigverify_spx_verify(
409  spx_signature, spx_key, spx_config, lc_state,
410  &usage_constraints_from_hw, sizeof(usage_constraints_from_hw),
411  anti_rollback, anti_rollback_len, digest_region.start,
412  digest_region.length, &act_digest, flash_exec));
413 
414  return sigverify_ecdsa_p256_verify(&manifest->ecdsa_signature, ecdsa_key,
415  &act_digest, flash_exec);
416  }
417 }
418 
419 /* These symbols are defined in
420  * `opentitan/sw/device/silicon_creator/rom/rom.ld`, and describes the
421  * location of the flash header.
422  */
423 extern char _rom_ext_virtual_start_address[];
424 extern char _rom_ext_virtual_size[];
425 /**
426  * Compute the virtual address corresponding to the physical address `lma_addr`.
427  *
428  * @param manifest Pointer to the current manifest.
429  * @param lma_addr Load address or physical address.
430  * @return the computed virtual address.
431  */
433 static inline uintptr_t rom_ext_vma_get(const manifest_t *manifest,
434  uintptr_t lma_addr) {
435  return (lma_addr - (uintptr_t)manifest +
436  (uintptr_t)_rom_ext_virtual_start_address);
437 }
438 
439 /**
440  * Performs consistency checks before booting a ROM_EXT.
441  *
442  * All of the checks in this function are expected to pass and any failures
443  * result in shutdown.
444  */
445 static void rom_pre_boot_check(void) {
446  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomPreBootCheck, 1);
447 
448  // Check the alert_handler configuration.
449  SHUTDOWN_IF_ERROR(alert_config_check(lc_state));
450  SHUTDOWN_IF_ERROR(rnd_health_config_check(lc_state));
451  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomPreBootCheck, 2);
452 
453  // Check cached life cycle state against the value reported by hardware.
454  lifecycle_state_t lc_state_check = lifecycle_state_get();
455  if (launder32(lc_state_check) != lc_state) {
456  HARDENED_TRAP();
457  }
458  HARDENED_CHECK_EQ(lc_state_check, lc_state);
459  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomPreBootCheck, 3);
460 
461  // Check cached boot data.
462  rom_error_t boot_data_ok = boot_data_check(&boot_data);
463  if (launder32(boot_data_ok) != kErrorOk) {
464  HARDENED_TRAP();
465  }
466  HARDENED_CHECK_EQ(boot_data_ok, kErrorOk);
467  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomPreBootCheck, 4);
468 
469  // Check the ePMP state
470  SHUTDOWN_IF_ERROR(epmp_state_check());
471  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomPreBootCheck, 5);
472 
473  // Check the cpuctrl CSR.
474  uint32_t cpuctrl_csr;
475  uint32_t cpuctrl_otp =
476  otp_read32(OTP_CTRL_PARAM_CREATOR_SW_CFG_CPUCTRL_OFFSET);
477  CSR_READ(CSR_REG_CPUCTRL, &cpuctrl_csr);
478  // We only mask the 8th bit (`ic_scr_key_valid`) to include exception flags
479  // (bits 6 and 7) in the check.
480  cpuctrl_csr = bitfield_bit32_write(cpuctrl_csr, 8, false);
481  if (launder32(cpuctrl_csr) != cpuctrl_otp) {
482  HARDENED_TRAP();
483  }
484  HARDENED_CHECK_EQ(cpuctrl_csr, cpuctrl_otp);
485  // Check rstmgr alert and cpu info collection configuration.
486  SHUTDOWN_IF_ERROR(
487  rstmgr_info_en_check(retention_sram_get()->creator.reset_reasons));
488  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomPreBootCheck, 6);
489 
490  sec_mmio_check_counters(/*expected_check_count=*/3);
491  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomPreBootCheck, 7);
492 }
493 
494 /**
495  * Measures the combination of software configuration OTP digests and the digest
496  * of the secure boot keys.
497  *
498  * @param measurement Pointer to the measurement of the partitions.
499  * @return rom_error_t Result of the operation.
500  */
501 static rom_error_t rom_measure_otp_partitions(
502  keymgr_binding_value_t *measurement) {
503  memset(measurement, (int)rnd_uint32(), sizeof(keymgr_binding_value_t));
504  // These is no need to harden these data copies as any poisoning of the OTP
505  // measurements will result in the derivation of a different UDS identity
506  // which will not be endorsed. Hence we save the cycles of using sec_mmio.
507  hmac_sha256_init();
508  static_assert(
509  (OTP_CTRL_CREATOR_SW_CFG_DIGEST_CREATOR_SW_CFG_DIGEST_FIELD_WIDTH *
510  OTP_CTRL_CREATOR_SW_CFG_DIGEST_MULTIREG_COUNT / 8) == sizeof(uint64_t),
511  "CreatorSwCfg OTP partition digest no longer 64 bits.");
512  static_assert(
513  (OTP_CTRL_OWNER_SW_CFG_DIGEST_OWNER_SW_CFG_DIGEST_FIELD_WIDTH *
514  OTP_CTRL_OWNER_SW_CFG_DIGEST_MULTIREG_COUNT / 8) == sizeof(uint64_t),
515  "OwnerSwCfg OTP partition digest no longer 64 bits.");
516  hmac_sha256_update(
517  (unsigned char *)(TOP_EARLGREY_OTP_CTRL_CORE_BASE_ADDR +
518  OTP_CTRL_SW_CFG_WINDOW_REG_OFFSET +
519  OTP_CTRL_CREATOR_SW_CFG_DIGEST_0_REG_OFFSET),
520  sizeof(uint64_t));
521  hmac_sha256_update(
522  (unsigned char *)(TOP_EARLGREY_OTP_CTRL_CORE_BASE_ADDR +
523  OTP_CTRL_SW_CFG_WINDOW_REG_OFFSET +
524  OTP_CTRL_OWNER_SW_CFG_DIGEST_0_REG_OFFSET),
525  sizeof(uint64_t));
526  hmac_sha256_update(sigverify_ctx.keys.integrity_measurement.digest,
527  kHmacDigestNumBytes);
528  hmac_sha256_process();
529  hmac_digest_t otp_measurement;
530  hmac_sha256_final(&otp_measurement);
531  memcpy(measurement->data, otp_measurement.digest, kHmacDigestNumBytes);
532  return kErrorOk;
533 }
534 
535 /**
536  * Boots a ROM_EXT.
537  *
538  * Note: This function should not return under normal conditions. Any returns
539  * from this function must result in shutdown.
540  *
541  * @param manifest Manifest of the ROM_EXT to boot.
542  * @param flash_exec Value to write to the flash_ctrl EXEC register.
543  * @return rom_error_t Result of the operation.
544  */
546 static rom_error_t rom_boot(const manifest_t *manifest, uint32_t flash_exec) {
547  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomBoot, 1);
548  HARDENED_RETURN_IF_ERROR(sc_keymgr_state_check(kScKeymgrStateReset));
549 
550  boot_log_t *boot_log = &retention_sram_get()->creator.boot_log;
552  manifest == boot_policy_manifest_a_get() ? kBootSlotA : kBootSlotB;
553  boot_log_digest_update(boot_log);
554 
555  keymgr_binding_value_t otp_measurement;
556  const keymgr_binding_value_t *attestation_measurement =
558  uint32_t use_otp_measurement =
559  otp_read32(OTP_CTRL_PARAM_OWNER_SW_CFG_ROM_KEYMGR_OTP_MEAS_EN_OFFSET);
560  if (launder32(use_otp_measurement) == kHardenedBoolTrue) {
561  HARDENED_CHECK_EQ(use_otp_measurement, kHardenedBoolTrue);
562  rom_measure_otp_partitions(&otp_measurement);
563  attestation_measurement = &otp_measurement;
564  } else {
565  HARDENED_CHECK_NE(use_otp_measurement, kHardenedBoolTrue);
566  }
567  sc_keymgr_sw_binding_set(&manifest->binding_value, attestation_measurement);
568  sc_keymgr_creator_max_ver_set(manifest->max_key_version);
569  SEC_MMIO_WRITE_INCREMENT(kScKeymgrSecMmioSwBindingSet +
570  kScKeymgrSecMmioCreatorMaxVerSet);
571 
572  sec_mmio_check_counters(/*expected_check_count=*/2);
573 
574  // Configure address translation, compute the epmp regions and the entry
575  // point for the virtual address in case the address translation is enabled.
576  // Otherwise, compute the epmp regions and the entry point for the load
577  // address.
578  epmp_region_t text_region = manifest_code_region_get(manifest);
579  uintptr_t entry_point = manifest_entry_point_get(manifest);
580  switch (launder32(manifest->address_translation)) {
581  case kHardenedBoolTrue:
583  ibex_addr_remap_0_set((uintptr_t)_rom_ext_virtual_start_address,
584  (uintptr_t)manifest, (size_t)_rom_ext_virtual_size);
585  SEC_MMIO_WRITE_INCREMENT(kAddressTranslationSecMmioConfigure);
586 
587  // Unlock read-only for the whole rom_ext virtual memory.
588  HARDENED_RETURN_IF_ERROR(epmp_state_check());
589  rom_epmp_unlock_rom_ext_r(
590  (epmp_region_t){.start = (uintptr_t)_rom_ext_virtual_start_address,
591  .end = (uintptr_t)_rom_ext_virtual_start_address +
592  (uintptr_t)_rom_ext_virtual_size});
593 
594  // Move the ROM_EXT execution section from the load address to the virtual
595  // address.
596  text_region.start = rom_ext_vma_get(manifest, text_region.start);
597  text_region.end = rom_ext_vma_get(manifest, text_region.end);
598  entry_point = rom_ext_vma_get(manifest, entry_point);
599  break;
600  case kHardenedBoolFalse:
602  break;
603  default:
604  HARDENED_TRAP();
605  }
606 
607  // Unlock execution of ROM_EXT executable code (text) sections.
608  HARDENED_RETURN_IF_ERROR(epmp_state_check());
609  rom_epmp_unlock_rom_ext_rx(text_region);
610 
611  CFI_FUNC_COUNTER_PREPCALL(rom_counters, kCfiRomBoot, 2, kCfiRomPreBootCheck);
612  rom_pre_boot_check();
613  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomBoot, 4);
614  CFI_FUNC_COUNTER_CHECK(rom_counters, kCfiRomPreBootCheck, 8);
615 
616  // Enable execution of code from flash if signature is verified.
617  flash_ctrl_exec_set(flash_exec);
618  SEC_MMIO_WRITE_INCREMENT(kFlashCtrlSecMmioExecSet);
619 
620  sec_mmio_check_values(rnd_uint32());
621  sec_mmio_check_counters(/*expected_check_count=*/5);
622 
623  // Jump to ROM_EXT entry point.
624  enum {
625  /**
626  * Expected value of the `kCfiRomTryBoot` counter when jumping to the first
627  * ROM_EXT image.
628  */
629  kCfiRomTryBootManifest0Val = 3 * kCfiIncrement + kCfiRomTryBootVal0,
630  /**
631  * Expected value of the `kCfiRomTryBoot` counter when jumping to the second
632  * ROM_EXT image.
633  */
634  kCfiRomTryBootManifest1Val = 10 * kCfiIncrement + kCfiRomTryBootVal0,
635  };
636  const manifest_t *manifest_check = NULL;
637  switch (launder32(rom_counters[kCfiRomTryBoot])) {
638  case kCfiRomTryBootManifest0Val:
639  HARDENED_CHECK_EQ(rom_counters[kCfiRomTryBoot],
640  kCfiRomTryBootManifest0Val);
641  manifest_check = boot_policy_manifests_get().ordered[0];
642  break;
643  case kCfiRomTryBootManifest1Val:
644  HARDENED_CHECK_EQ(rom_counters[kCfiRomTryBoot],
645  kCfiRomTryBootManifest1Val);
646  manifest_check = boot_policy_manifests_get().ordered[1];
647  break;
648  default:
649  HARDENED_TRAP();
650  }
651  HARDENED_CHECK_EQ(manifest, manifest_check);
652 
653 #if OT_BUILD_FOR_STATIC_ANALYZER
654  assert(manifest_check != NULL);
655 #endif
656 
657  if (launder32(manifest_check->address_translation) == kHardenedBoolTrue) {
658  HARDENED_CHECK_EQ(manifest_check->address_translation, kHardenedBoolTrue);
659  HARDENED_CHECK_EQ(rom_ext_vma_get(manifest_check,
660  manifest_entry_point_get(manifest_check)),
661  entry_point);
662  } else {
663  HARDENED_CHECK_EQ(manifest_check->address_translation, kHardenedBoolFalse);
664  HARDENED_CHECK_EQ(manifest_entry_point_get(manifest_check), entry_point);
665  }
666  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomBoot, 5);
667 
668  // In a normal build, this function inlines to nothing.
669  stack_utilization_print();
670 
671  // (Potentially) Execute the immutable ROM_EXT section.
672  uint32_t rom_ext_immutable_section_enabled =
673  otp_read32(OTP_CTRL_PARAM_CREATOR_SW_CFG_IMMUTABLE_ROM_EXT_EN_OFFSET);
674  if (launder32(rom_ext_immutable_section_enabled) == kHardenedBoolTrue) {
675  HARDENED_CHECK_EQ(rom_ext_immutable_section_enabled, kHardenedBoolTrue);
676  // Get offset and length of immutable ROM_EXT code partition.
677  uintptr_t immutable_rom_ext_start_offset = (uintptr_t)otp_read32(
678  OTP_CTRL_PARAM_CREATOR_SW_CFG_IMMUTABLE_ROM_EXT_START_OFFSET_OFFSET);
679  size_t immutable_rom_ext_length = (size_t)otp_read32(
680  OTP_CTRL_PARAM_CREATOR_SW_CFG_IMMUTABLE_ROM_EXT_LENGTH_OFFSET);
681  uintptr_t immutable_rom_ext_entry_point =
682  (uintptr_t)manifest + immutable_rom_ext_start_offset;
683  // If address translation is enabled, adjust the entry_point.
684  if (launder32(manifest->address_translation) == kHardenedBoolTrue) {
686  immutable_rom_ext_entry_point =
687  rom_ext_vma_get(manifest, immutable_rom_ext_entry_point);
688  } else {
689  HARDENED_CHECK_NE(manifest->address_translation, kHardenedBoolTrue);
690  }
691 
692  // Compute a hash of the code section.
693  // Include the start offset and the length of the section in the hash.
694  hmac_sha256_init();
695  hmac_sha256_update(&immutable_rom_ext_start_offset,
696  /*len=*/sizeof(uintptr_t));
697  hmac_sha256_update(&immutable_rom_ext_length, /*len=*/sizeof(size_t));
698  hmac_sha256_update((const void *)immutable_rom_ext_entry_point,
699  immutable_rom_ext_length);
700  hmac_sha256_process();
701  hmac_digest_t actual_immutable_section_digest;
702  hmac_sha256_final(&actual_immutable_section_digest);
703 
704  // Validate the hash matches that in OTP, and if so execute the code.
705  // Otherwise, trigger shutdown via hardened check fail.
706  hmac_digest_t immutable_rom_ext_hash;
707  otp_read(OTP_CTRL_PARAM_CREATOR_SW_CFG_IMMUTABLE_ROM_EXT_SHA256_HASH_OFFSET,
708  immutable_rom_ext_hash.digest, kHmacDigestNumWords);
709  for (size_t i = 0; i < kHmacDigestNumWords; ++i) {
710  HARDENED_CHECK_EQ(immutable_rom_ext_hash.digest[i],
711  actual_immutable_section_digest.digest[i]);
712  }
713  ((rom_ext_entry_point *)immutable_rom_ext_entry_point)();
714  } else {
715  HARDENED_CHECK_NE(rom_ext_immutable_section_enabled, kHardenedBoolTrue);
716  }
717 
718  // Jump to ROM_EXT.
719  ((rom_ext_entry_point *)entry_point)();
720  return kErrorRomBootFailed;
721 }
722 
723 /**
724  * Attempts to boot ROM_EXTs in the order given by the boot policy module.
725  *
726  * @return Result of the last attempt.
727  */
729 static rom_error_t rom_try_boot(void) {
730  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomTryBoot, 1);
731 
732  // Read boot data from flash
733  HARDENED_RETURN_IF_ERROR(boot_data_read(lc_state, &boot_data));
734 
735  boot_policy_manifests_t manifests = boot_policy_manifests_get();
736  uint32_t flash_exec = 0;
737 
738  CFI_FUNC_COUNTER_PREPCALL(rom_counters, kCfiRomTryBoot, 2, kCfiRomVerify);
739  rom_error_t error = rom_verify(manifests.ordered[0], &flash_exec);
740  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomTryBoot, 4);
741 
742  if (launder32(error) == kErrorOk) {
743  HARDENED_CHECK_EQ(error, kErrorOk);
744  CFI_FUNC_COUNTER_CHECK(rom_counters, kCfiRomVerify, 3);
745  CFI_FUNC_COUNTER_INIT(rom_counters, kCfiRomTryBoot);
746  CFI_FUNC_COUNTER_PREPCALL(rom_counters, kCfiRomTryBoot, 1, kCfiRomBoot);
747  HARDENED_RETURN_IF_ERROR(rom_boot(manifests.ordered[0], flash_exec));
748  return kErrorRomBootFailed;
749  }
750 
751  CFI_FUNC_COUNTER_PREPCALL(rom_counters, kCfiRomTryBoot, 5, kCfiRomVerify);
752  HARDENED_RETURN_IF_ERROR(rom_verify(manifests.ordered[1], &flash_exec));
753  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomTryBoot, 7);
754  CFI_FUNC_COUNTER_CHECK(rom_counters, kCfiRomVerify, 3);
755 
756  CFI_FUNC_COUNTER_PREPCALL(rom_counters, kCfiRomTryBoot, 8, kCfiRomBoot);
757  HARDENED_RETURN_IF_ERROR(rom_boot(manifests.ordered[1], flash_exec));
758  return kErrorRomBootFailed;
759 }
760 
761 /*
762  * The bootstrap request is the `kRomStateBootstrapCheck` and
763  * `kRomStateBootstrap` ROM states argument. It must be undefined before
764  * entering the `kRomStateBootstrapCheck` state as only the
765  * `kRomStateBootstrapCheck` run callback or hooks should set it to either
766  * `kHardenedBoolFalse` or `kHardenedBoolTrue`.
767  */
768 static hardened_bool_t bootstrap_request = 0;
769 
770 enum {
771  kRomStateCnt = 4,
772 };
773 
774 /**
775  * Table of ROM states.
776  *
777  * Encoding generated with:
778  * $ ./util/design/sparse-fsm-encode.py -d 6 -m 4 -n 16 \
779  * -s 519644925 --language=c
780  */
781 // clang-format off
782 #define ROM_STATES(X) \
783  X(kRomStateInit, 0x5616, rom_state_init, NULL) \
784  X(kRomStateBootstrapCheck, 0x0a92, rom_state_bootstrap_check, &bootstrap_request) \
785  X(kRomStateBootstrap, 0xd0a0, rom_state_bootstrap, &bootstrap_request) \
786  X(kRomStateBootRomExt, 0xed14, rom_state_boot_rom_ext, NULL)
787 // clang-format on
788 
789 ROM_STATE_INIT_TABLE(rom_states, kRomStateCnt, ROM_STATES);
790 
791 static OT_WARN_UNUSED_RESULT rom_error_t rom_state_init(void *arg,
792  uint32_t *next_state) {
793  CFI_FUNC_COUNTER_INIT(rom_counters, kCfiRomMain);
794 
795  CFI_FUNC_COUNTER_PREPCALL(rom_counters, kCfiRomMain, 1, kCfiRomInit);
796  HARDENED_RETURN_IF_ERROR(rom_init());
797  CFI_FUNC_COUNTER_INCREMENT(rom_counters, kCfiRomMain, 3);
798 
799  *next_state = kRomStateBootstrapCheck;
800 
801  return kErrorOk;
802 }
803 
804 static OT_WARN_UNUSED_RESULT rom_error_t
805 rom_state_bootstrap_check(void *arg, uint32_t *next_state) {
806  if (launder32(waking_from_low_power) != kHardenedBoolTrue) {
807  HARDENED_CHECK_EQ(waking_from_low_power, kHardenedBoolFalse);
808 
809  hardened_bool_t *bootstrap_req = (hardened_bool_t *)arg;
810 
811  if (launder32(*bootstrap_req) == 0) {
812  // The pre_ hook has not set the bootstrap request flag, it has to be
813  // checked and set to True or False
814  HARDENED_CHECK_EQ(*bootstrap_req, 0);
815  *bootstrap_req = bootstrap_requested();
816  }
817 
818  // The bootstrap request flag must now be True or False.
819  if (launder32(*bootstrap_req) == kHardenedBoolTrue) {
820  HARDENED_CHECK_EQ(*bootstrap_req, kHardenedBoolTrue);
821  *next_state = kRomStateBootstrap;
822  return kErrorOk;
823  }
824  }
825 
826  // We are not bootstrapping, aiming for ROM ext.
827  *next_state = kRomStateBootRomExt;
828  return kErrorOk;
829 }
830 
831 static OT_WARN_UNUSED_RESULT rom_error_t
832 rom_state_bootstrap(void *arg, uint32_t *next_state) {
833  hardened_bool_t *bootstrap_req = (hardened_bool_t *)arg;
834 
835  if (launder32(*bootstrap_req) == kHardenedBoolTrue) {
836  HARDENED_CHECK_EQ(*bootstrap_req, kHardenedBoolTrue);
837  rom_bootstrap_message();
838  watchdog_disable();
839  // `bootstrap` will not return unless there is an error.
840  HARDENED_RETURN_IF_ERROR(bootstrap());
841  }
842 
843  return kErrorRomBootFailed;
844 }
845 
846 static OT_WARN_UNUSED_RESULT rom_error_t
847 rom_state_boot_rom_ext(void *arg, uint32_t *next_state) {
848  // `rom_try_boot` will not return unless there is an error.
849  CFI_FUNC_COUNTER_PREPCALL(rom_counters, kCfiRomMain, 4, kCfiRomTryBoot);
850  return rom_try_boot();
851 }
852 
853 void rom_main(void) {
854  CFI_FUNC_COUNTER_INIT(rom_counters, kCfiRomMain);
855  shutdown_finalize(rom_state_fsm_walk(rom_states, kRomStateCnt, kRomStateInit,
856  rom_states_cfi));
857 }