tpm: add TPM2_Clear command support
[platform/kernel/u-boot.git] / lib / tpm-v2.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (c) 2018 Bootlin
4  * Author: Miquel Raynal <miquel.raynal@bootlin.com>
5  */
6
7 #include <common.h>
8 #include <dm.h>
9 #include <tpm-common.h>
10 #include <tpm-v2.h>
11 #include "tpm-utils.h"
12
13 u32 tpm2_startup(enum tpm2_startup_types mode)
14 {
15         const u8 command_v2[12] = {
16                 tpm_u16(TPM2_ST_NO_SESSIONS),
17                 tpm_u32(12),
18                 tpm_u32(TPM2_CC_STARTUP),
19                 tpm_u16(mode),
20         };
21         int ret;
22
23         /*
24          * Note TPM2_Startup command will return RC_SUCCESS the first time,
25          * but will return RC_INITIALIZE otherwise.
26          */
27         ret = tpm_sendrecv_command(command_v2, NULL, NULL);
28         if (ret && ret != TPM2_RC_INITIALIZE)
29                 return ret;
30
31         return 0;
32 }
33
34 u32 tpm2_self_test(enum tpm2_yes_no full_test)
35 {
36         const u8 command_v2[12] = {
37                 tpm_u16(TPM2_ST_NO_SESSIONS),
38                 tpm_u32(11),
39                 tpm_u32(TPM2_CC_SELF_TEST),
40                 full_test,
41         };
42
43         return tpm_sendrecv_command(command_v2, NULL, NULL);
44 }
45
46 u32 tpm2_clear(u32 handle, const char *pw, const ssize_t pw_sz)
47 {
48         u8 command_v2[COMMAND_BUFFER_SIZE] = {
49                 tpm_u16(TPM2_ST_SESSIONS),      /* TAG */
50                 tpm_u32(27 + pw_sz),            /* Length */
51                 tpm_u32(TPM2_CC_CLEAR),         /* Command code */
52
53                 /* HANDLE */
54                 tpm_u32(handle),                /* TPM resource handle */
55
56                 /* AUTH_SESSION */
57                 tpm_u32(9 + pw_sz),             /* Authorization size */
58                 tpm_u32(TPM2_RS_PW),            /* Session handle */
59                 tpm_u16(0),                     /* Size of <nonce> */
60                                                 /* <nonce> (if any) */
61                 0,                              /* Attributes: Cont/Excl/Rst */
62                 tpm_u16(pw_sz),                 /* Size of <hmac/password> */
63                 /* STRING(pw)                      <hmac/password> (if any) */
64         };
65         unsigned int offset = 27;
66         int ret;
67
68         /*
69          * Fill the command structure starting from the first buffer:
70          *     - the password (if any)
71          */
72         ret = pack_byte_string(command_v2, sizeof(command_v2), "s",
73                                offset, pw, pw_sz);
74         offset += pw_sz;
75         if (ret)
76                 return TPM_LIB_ERROR;
77
78         return tpm_sendrecv_command(command_v2, NULL, NULL);
79 }