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/vbios_cache_hash_tpm.h>
9 #include <console/console.h>
10 #include <string.h>
11
vbios_cache_update_hash(const uint8_t * data,size_t size)12 void vbios_cache_update_hash(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, "VBIOS_CACHE: TPM driver initialization failed with error %#x.\n", rc);
21 return;
22 }
23
24 /* Calculate hash of vbios data. */
25 if (vb2_hash_calculate(vboot_hwcrypto_allowed(), data, size,
26 VB2_HASH_SHA256, &hash)) {
27 printk(BIOS_ERR, "VBIOS_CACHE: SHA-256 calculation failed for data; "
28 "clearing TPM hash space.\n");
29 /*
30 * Since data is being updated in vbios 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_vbios_hash(hash.sha256, sizeof(hash.sha256));
41 if (rc != TPM_SUCCESS) {
42 printk(BIOS_ERR, "VBIOS_CACHE: Could not save hash to TPM with error %#x.\n", rc);
43 return;
44 }
45
46 printk(BIOS_INFO, "VBIOS_CACHE: TPM NV idx %#x updated successfully.\n",
47 VBIOS_CACHE_NV_INDEX);
48 }
49
vbios_cache_verify_hash(const uint8_t * data,size_t size)50 enum cb_err vbios_cache_verify_hash(const uint8_t *data, size_t size)
51 {
52 struct vb2_hash tpm_hash = { .algo = VB2_HASH_SHA256 };
53 tpm_result_t rc = TPM_SUCCESS;
54
55 /* Initialize TPM driver. */
56 rc = tlcl_lib_init();
57 if (rc != TPM_SUCCESS) {
58 printk(BIOS_ERR, "VBIOS_CACHE: TPM driver initialization failed with error %#x.\n", rc);
59 return CB_ERR;
60 }
61
62 /* Read hash of VBIOS data saved in TPM. */
63 rc = antirollback_read_space_vbios_hash(tpm_hash.sha256, sizeof(tpm_hash.sha256));
64 if (rc != TPM_SUCCESS) {
65 printk(BIOS_ERR, "VBIOS_CACHE: Could not read hash from TPM with error %#x.\n", rc);
66 return CB_ERR;
67 }
68
69 /* Calculate hash of data read from VBIOS FMAP CACHE and compare. */
70 if (vb2_hash_verify(vboot_hwcrypto_allowed(), data, size, &tpm_hash)) {
71 printk(BIOS_ERR, "VBIOS_CACHE: Hash comparison failed.\n");
72 return CB_ERR;
73 }
74
75 printk(BIOS_INFO, "VBIOS_CACHE: Hash idx %#x comparison successful.\n",
76 VBIOS_CACHE_NV_INDEX);
77
78 return CB_SUCCESS;
79 }
80