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