1 /* SPDX-License-Identifier: GPL-2.0-only */
2
3 #include <security/vboot/antirollback.h>
4 #include <program_loading.h>
5 #include <vb2_api.h>
6 #include <security/tpm/tss.h>
7 #include <security/vboot/misc.h>
8 #include <security/vboot/mrc_cache_hash_tpm.h>
9 #include <console/console.h>
10 #include <string.h>
11
mrc_cache_update_hash(uint32_t index,const uint8_t * data,size_t size)12 void mrc_cache_update_hash(uint32_t index, const uint8_t *data, size_t size)
13 {
14 struct vb2_hash hash;
15 tpm_result_t rc = TPM_SUCCESS;
16
17 /* Initialize TPM driver. */
18 rc = tlcl_lib_init();
19 if (rc != TPM_SUCCESS) {
20 printk(BIOS_ERR, "MRC: TPM driver initialization failed with error %#x.\n", rc);
21 return;
22 }
23
24 /* Calculate hash of data generated by MRC. */
25 if (vb2_hash_calculate(vboot_hwcrypto_allowed(), data, size,
26 VB2_HASH_SHA256, &hash)) {
27 printk(BIOS_ERR, "MRC: SHA-256 calculation failed for data. "
28 "Not updating TPM hash space.\n");
29 /*
30 * Since data is being updated in mrc cache, the hash
31 * currently stored in TPM hash space is no longer
32 * valid. If we are not able to calculate hash of the
33 * data being updated, reset all the bits in TPM hash
34 * space to zero to invalidate it.
35 */
36 memset(hash.raw, 0, VB2_SHA256_DIGEST_SIZE);
37 }
38
39 /* Write hash of data to TPM space. */
40 rc = antirollback_write_space_mrc_hash(index, hash.sha256, sizeof(hash.sha256));
41 if (rc != TPM_SUCCESS) {
42 printk(BIOS_ERR, "MRC: Could not save hash to TPM with error %#x.\n", rc);
43 return;
44 }
45
46 printk(BIOS_INFO, "MRC: TPM MRC hash idx %#x updated successfully.\n", index);
47 }
48
mrc_cache_verify_hash(uint32_t index,const uint8_t * data,size_t size)49 int mrc_cache_verify_hash(uint32_t index, const uint8_t *data, size_t size)
50 {
51 struct vb2_hash tpm_hash = { .algo = VB2_HASH_SHA256 };
52 tpm_result_t rc = TPM_SUCCESS;
53
54 /* Initialize TPM driver. */
55 rc = tlcl_lib_init();
56 if (rc != TPM_SUCCESS) {
57 printk(BIOS_ERR, "MRC: TPM driver initialization failed with error %#x.\n", rc);
58 return 0;
59 }
60
61 /* Read hash of MRC data saved in TPM. */
62 rc = antirollback_read_space_mrc_hash(index, tpm_hash.sha256, sizeof(tpm_hash.sha256));
63 if (rc != TPM_SUCCESS) {
64 printk(BIOS_ERR, "MRC: Could not read hash from TPM with error %#x.\n", rc);
65 return 0;
66 }
67
68 /* Calculate hash of data read from MRC_CACHE and compare. */
69 if (vb2_hash_verify(vboot_hwcrypto_allowed(), data, size, &tpm_hash)) {
70 printk(BIOS_ERR, "MRC: Hash comparison failed.\n");
71 return 0;
72 }
73
74 printk(BIOS_INFO, "MRC: Hash idx %#x comparison successful.\n", index);
75
76 return 1;
77 }
78