Software APIs
print_certs.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/lib/base/status.h"
9 #include "sw/device/silicon_creator/lib/drivers/flash_ctrl.h"
10 #include "sw/device/silicon_creator/manuf/base/perso_tlv_data.h"
11 
12 OTTF_DEFINE_TEST_CONFIG();
13 
14 const char kBase64[] =
15  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
16 
17 static void base64_encode(char *dest, const uint8_t *data, int32_t len) {
18  for (int32_t i = 0; len > 0; i += 3, len -= 3) {
19  // clang-format off
20  uint32_t val = (uint32_t)(data[i] << 16 |
21  (len > 1 ? data[i + 1] << 8 : 0) |
22  (len > 2 ? data[i + 2] : 0));
23  // clang-format on
24  *dest++ = kBase64[(val >> 18) & 0x3f];
25  *dest++ = kBase64[(val >> 12) & 0x3f];
26  *dest++ = len > 1 ? kBase64[(val >> 6) & 0x3f] : '=';
27  *dest++ = len > 2 ? kBase64[(val >> 0) & 0x3f] : '=';
28  }
29  *dest = '\0';
30 }
31 
32 static status_t print_cert(char *dest,
33  const flash_ctrl_info_page_t *info_page) {
34  uint8_t data[2048];
35  TRY(flash_ctrl_info_read_zeros_on_read_error(
36  info_page, 0, sizeof(data) / sizeof(uint32_t), data));
37 
38  uint32_t offset = 0;
39  size_t len = sizeof(data);
40  while (true) {
41  perso_tlv_cert_obj_t obj = {0};
42  rom_error_t err = perso_tlv_get_cert_obj(data + offset, len, &obj);
43  if (err != kErrorOk) {
44  break;
45  }
46  base64_encode(dest, obj.cert_body_p, (int32_t)obj.cert_body_size);
47  LOG_INFO("%s type=%d sz=%d", obj.name, obj.obj_type, obj.obj_size);
48  LOG_INFO("%s: %s", obj.name, dest);
49  offset += (obj.obj_size + 7) & ~7u;
50  len -= obj.obj_size;
51  }
52  return OK_STATUS();
53 }
54 
55 static status_t print_owner_block(char *dest,
56  const flash_ctrl_info_page_t *info_page) {
57  uint8_t data[2048];
58  TRY(flash_ctrl_info_read(info_page, 0, sizeof(data) / sizeof(uint32_t),
59  data));
60  base64_encode(dest, data, sizeof(data));
61  return OK_STATUS();
62 }
63 
64 static status_t print_certs(void) {
65  char buf[3072];
66  // Print certificates.
67  TRY(print_cert(buf, &kFlashCtrlInfoPageFactoryCerts));
68  TRY(print_cert(buf, &kFlashCtrlInfoPageDiceCerts));
69 
70  // Print owner information.
71  TRY(print_owner_block(buf, &kFlashCtrlInfoPageOwnerSlot0));
72  LOG_INFO("OWNER_PAGE_0: %s", buf);
73 
74  TRY(print_owner_block(buf, &kFlashCtrlInfoPageOwnerSlot1));
75  LOG_INFO("OWNER_PAGE_1: %s", buf);
76 
77  return OK_STATUS();
78 }
79 
80 bool test_main(void) {
81  status_t sts = print_certs();
82  if (status_err(sts)) {
83  LOG_ERROR("print_certs: %r", sts);
84  }
85  return status_ok(sts);
86 }