1 #include <mbedtls/sha256.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <stdint.h>
5 #include <stdio.h>
6 #include <ibmtss/TPM_Types.h>
7 #include <ibmtss/tssmarshal.h>
8 #include <netinet/in.h>
9 
10 #define TPM_TPM20
11 #include "../../tss2/ibmtpm20tss/utils/tssmarshal.c"
12 #include "../../tss2/ibmtpm20tss/utils/Unmarshal.c"
13 
14 #define zalloc(a) calloc(1,a)
15 // Silence linking complaints
16 int verbose;
17 
18 #define COPYRIGHT_YEAR "2020"
19 
20 
21 TPMS_NV_PUBLIC vars = {
22 	.nvIndex = 0x01c10190,
23 	.nameAlg = TPM_ALG_SHA256,
24 	.dataSize = 2048,
25 	.attributes.val = TPMA_NVA_PPWRITE		|
26 			  TPMA_NVA_ORDINARY             |
27 			  TPMA_NVA_WRITE_STCLEAR        |
28 			  TPMA_NVA_AUTHREAD             |
29 			  TPMA_NVA_NO_DA                |
30 			  TPMA_NVA_WRITTEN              |
31 			  TPMA_NVA_PLATFORMCREATE,
32 };
33 
34 TPMS_NV_PUBLIC control = {
35 	.nvIndex = 0x01c10191,
36 	.nameAlg = TPM_ALG_SHA256,
37 	.dataSize = 73,
38 	.attributes.val = TPMA_NVA_PPWRITE		|
39 			  TPMA_NVA_ORDINARY             |
40 			  TPMA_NVA_WRITE_STCLEAR        |
41 			  TPMA_NVA_AUTHREAD             |
42 			  TPMA_NVA_NO_DA                |
43 			  TPMA_NVA_WRITTEN              |
44 			  TPMA_NVA_PLATFORMCREATE,
45 };
46 
calc_hash(TPMS_NV_PUBLIC * public,char * name)47 int calc_hash(TPMS_NV_PUBLIC *public, char *name)
48 {
49 	uint16_t written = 0;
50 	uint32_t size = 4096;
51 	unsigned char *buffer = zalloc(size);
52 	unsigned char *buffer_tmp = buffer;
53 	char output[34];
54 	mbedtls_sha256_context cxt;
55 	int ret = 0;
56 	int i;
57 
58 	// Output hash includes the hash algorithm in the first two bytes
59 	*((uint16_t *) output) = htons(public->nameAlg);
60 
61 	// Serialize the NV Public struct
62 	ret = TSS_TPMS_NV_PUBLIC_Marshalu(public, &written, &buffer_tmp, &size);
63 	if (ret) return ret;
64 
65 	// Hash it
66 	mbedtls_sha256_init(&cxt);
67 	ret = mbedtls_sha256_starts_ret(&cxt, 0);
68 	if (ret) return ret;
69 
70 	ret = mbedtls_sha256_update_ret(&cxt, buffer, written);
71 	if (ret) return ret;
72 
73 	mbedtls_sha256_finish_ret(&cxt, output+2);
74 	mbedtls_sha256_free(&cxt);
75 
76 	free(buffer);
77 
78 	// Print it
79 	printf("\nconst uint8_t tpmnv_%s_name[] = {", name);
80 	for (i = 0; i < sizeof(output); i++) {
81 		if (!(i % 13))
82 			printf("\n\t");
83 		printf("0x%02x, ", output[i] & 0xff);
84 	}
85 	printf("\n};\n");
86 
87 	return 0;
88 }
89 
90 
main()91 int main()
92 {
93 	printf("// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later\n");
94 	printf("/* Copyright " COPYRIGHT_YEAR " IBM Corp. */\n");
95 
96 	printf("#ifndef _SECBOOT_TPM_PUBLIC_NAME_H_\n");
97 	printf("#define _SECBOOT_TPM_PUBLIC_NAME_H_\n");
98 
99 	calc_hash(&vars, "vars");
100 	calc_hash(&control, "control");
101 
102 	printf("\n");
103 	printf("#endif\n");
104 
105 	return 0;
106 }
107 
108