1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*******************************************************************************
3  * Copyright 2017-2018, Fraunhofer SIT sponsored by Infineon Technologies AG
4  * All rights reserved.
5  ******************************************************************************/
6 
7 #ifdef HAVE_CONFIG_H
8 #include <config.h>
9 #endif
10 
11 #include "tss2_mu.h"
12 #include "tss2_sys.h"
13 #include "tss2_esys.h"
14 
15 #include "esys_types.h"
16 #include "esys_iutil.h"
17 #include "esys_mu.h"
18 #define LOGMODULE esys
19 #include "util/log.h"
20 #include "util/aux_util.h"
21 
22 /** One-Call function for TPM2_PCR_SetAuthPolicy
23  *
24  * This function invokes the TPM2_PCR_SetAuthPolicy command in a one-call
25  * variant. This means the function will block until the TPM response is
26  * available. All input parameters are const. The memory for non-simple output
27  * parameters is allocated by the function implementation.
28  *
29  * @param[in,out] esysContext The ESYS_CONTEXT.
30  * @param[in]  authHandle TPM2_RH_PLATFORM+{PP}.
31  * @param[in]  shandle1 Session handle for authorization of authHandle
32  * @param[in]  shandle2 Second session handle.
33  * @param[in]  shandle3 Third session handle.
34  * @param[in]  authPolicy The desired authPolicy.
35  * @param[in]  hashAlg The hash algorithm of the policy.
36  * @param[in]  pcrNum The PCR for which the policy is to be set.
37  * @retval TSS2_RC_SUCCESS if the function call was a success.
38  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
39  *         pointers or required output handle references are NULL.
40  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
41  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
42  *         internal operations or return parameters.
43  * @retval TSS2_ESYS_RC_BAD_SEQUENCE: if the context has an asynchronous
44  *         operation already pending.
45  * @retval TSS2_ESYS_RC_INSUFFICIENT_RESPONSE: if the TPM's response does not
46  *          at least contain the tag, response length, and response code.
47  * @retval TSS2_ESYS_RC_MALFORMED_RESPONSE: if the TPM's response is corrupted.
48  * @retval TSS2_ESYS_RC_RSP_AUTH_FAILED: if the response HMAC from the TPM
49            did not verify.
50  * @retval TSS2_ESYS_RC_MULTIPLE_DECRYPT_SESSIONS: if more than one session has
51  *         the 'decrypt' attribute bit set.
52  * @retval TSS2_ESYS_RC_MULTIPLE_ENCRYPT_SESSIONS: if more than one session has
53  *         the 'encrypt' attribute bit set.
54  * @retval TSS2_ESYS_RC_BAD_TR: if any of the ESYS_TR objects are unknown
55  *         to the ESYS_CONTEXT or are of the wrong type or if required
56  *         ESYS_TR objects are ESYS_TR_NONE.
57  * @retval TSS2_ESYS_RC_NO_ENCRYPT_PARAM: if one of the sessions has the
58  *         'encrypt' attribute set and the command does not support encryption
59  *          of the first response parameter.
60  * @retval TSS2_RCs produced by lower layers of the software stack may be
61  *         returned to the caller unaltered unless handled internally.
62  */
63 TSS2_RC
Esys_PCR_SetAuthPolicy(ESYS_CONTEXT * esysContext,ESYS_TR authHandle,ESYS_TR shandle1,ESYS_TR shandle2,ESYS_TR shandle3,const TPM2B_DIGEST * authPolicy,TPMI_ALG_HASH hashAlg,TPMI_DH_PCR pcrNum)64 Esys_PCR_SetAuthPolicy(
65     ESYS_CONTEXT *esysContext,
66     ESYS_TR authHandle,
67     ESYS_TR shandle1,
68     ESYS_TR shandle2,
69     ESYS_TR shandle3,
70     const TPM2B_DIGEST *authPolicy,
71     TPMI_ALG_HASH hashAlg,
72     TPMI_DH_PCR pcrNum)
73 {
74     TSS2_RC r;
75 
76     r = Esys_PCR_SetAuthPolicy_Async(esysContext, authHandle, shandle1, shandle2,
77                                      shandle3, authPolicy, hashAlg, pcrNum);
78     return_if_error(r, "Error in async function");
79 
80     /* Set the timeout to indefinite for now, since we want _Finish to block */
81     int32_t timeouttmp = esysContext->timeout;
82     esysContext->timeout = -1;
83     /*
84      * Now we call the finish function, until return code is not equal to
85      * from TSS2_BASE_RC_TRY_AGAIN.
86      * Note that the finish function may return TSS2_RC_TRY_AGAIN, even if we
87      * have set the timeout to -1. This occurs for example if the TPM requests
88      * a retransmission of the command via TPM2_RC_YIELDED.
89      */
90     do {
91         r = Esys_PCR_SetAuthPolicy_Finish(esysContext);
92         /* This is just debug information about the reattempt to finish the
93            command */
94         if ((r & ~TSS2_RC_LAYER_MASK) == TSS2_BASE_RC_TRY_AGAIN)
95             LOG_DEBUG("A layer below returned TRY_AGAIN: %" PRIx32
96                       " => resubmitting command", r);
97     } while ((r & ~TSS2_RC_LAYER_MASK) == TSS2_BASE_RC_TRY_AGAIN);
98 
99     /* Restore the timeout value to the original value */
100     esysContext->timeout = timeouttmp;
101     return_if_error(r, "Esys Finish");
102 
103     return TSS2_RC_SUCCESS;
104 }
105 
106 /** Asynchronous function for TPM2_PCR_SetAuthPolicy
107  *
108  * This function invokes the TPM2_PCR_SetAuthPolicy command in a asynchronous
109  * variant. This means the function will return as soon as the command has been
110  * sent downwards the stack to the TPM. All input parameters are const.
111  * In order to retrieve the TPM's response call Esys_PCR_SetAuthPolicy_Finish.
112  *
113  * @param[in,out] esysContext The ESYS_CONTEXT.
114  * @param[in]  authHandle TPM2_RH_PLATFORM+{PP}.
115  * @param[in]  shandle1 Session handle for authorization of authHandle
116  * @param[in]  shandle2 Second session handle.
117  * @param[in]  shandle3 Third session handle.
118  * @param[in]  authPolicy The desired authPolicy.
119  * @param[in]  hashAlg The hash algorithm of the policy.
120  * @param[in]  pcrNum The PCR for which the policy is to be set.
121  * @retval ESYS_RC_SUCCESS if the function call was a success.
122  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
123  *         pointers or required output handle references are NULL.
124  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
125  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
126  *         internal operations or return parameters.
127  * @retval TSS2_RCs produced by lower layers of the software stack may be
128            returned to the caller unaltered unless handled internally.
129  * @retval TSS2_ESYS_RC_MULTIPLE_DECRYPT_SESSIONS: if more than one session has
130  *         the 'decrypt' attribute bit set.
131  * @retval TSS2_ESYS_RC_MULTIPLE_ENCRYPT_SESSIONS: if more than one session has
132  *         the 'encrypt' attribute bit set.
133  * @retval TSS2_ESYS_RC_BAD_TR: if any of the ESYS_TR objects are unknown
134  *         to the ESYS_CONTEXT or are of the wrong type or if required
135  *         ESYS_TR objects are ESYS_TR_NONE.
136  * @retval TSS2_ESYS_RC_NO_ENCRYPT_PARAM: if one of the sessions has the
137  *         'encrypt' attribute set and the command does not support encryption
138  *          of the first response parameter.
139  */
140 TSS2_RC
Esys_PCR_SetAuthPolicy_Async(ESYS_CONTEXT * esysContext,ESYS_TR authHandle,ESYS_TR shandle1,ESYS_TR shandle2,ESYS_TR shandle3,const TPM2B_DIGEST * authPolicy,TPMI_ALG_HASH hashAlg,TPMI_DH_PCR pcrNum)141 Esys_PCR_SetAuthPolicy_Async(
142     ESYS_CONTEXT *esysContext,
143     ESYS_TR authHandle,
144     ESYS_TR shandle1,
145     ESYS_TR shandle2,
146     ESYS_TR shandle3,
147     const TPM2B_DIGEST *authPolicy,
148     TPMI_ALG_HASH hashAlg,
149     TPMI_DH_PCR pcrNum)
150 {
151     TSS2_RC r;
152     LOG_TRACE("context=%p, authHandle=%"PRIx32 ", authPolicy=%p,"
153               "hashAlg=%04"PRIx16", pcrNum=%"PRIx32 "",
154               esysContext, authHandle, authPolicy, hashAlg, pcrNum);
155     TSS2L_SYS_AUTH_COMMAND auths;
156     RSRC_NODE_T *authHandleNode;
157 
158     /* Check context, sequence correctness and set state to error for now */
159     if (esysContext == NULL) {
160         LOG_ERROR("esyscontext is NULL.");
161         return TSS2_ESYS_RC_BAD_REFERENCE;
162     }
163     r = iesys_check_sequence_async(esysContext);
164     if (r != TSS2_RC_SUCCESS)
165         return r;
166     esysContext->state = _ESYS_STATE_INTERNALERROR;
167 
168     /* Check input parameters */
169     r = check_session_feasibility(shandle1, shandle2, shandle3, 1);
170     return_state_if_error(r, _ESYS_STATE_INIT, "Check session usage");
171 
172     /* Retrieve the metadata objects for provided handles */
173     r = esys_GetResourceObject(esysContext, authHandle, &authHandleNode);
174     return_state_if_error(r, _ESYS_STATE_INIT, "authHandle unknown.");
175 
176     /* Initial invocation of SAPI to prepare the command buffer with parameters */
177     r = Tss2_Sys_PCR_SetAuthPolicy_Prepare(esysContext->sys,
178                                            (authHandleNode == NULL)
179                                             ? TPM2_RH_NULL
180                                             : authHandleNode->rsrc.handle,
181                                            authPolicy, hashAlg, pcrNum);
182     return_state_if_error(r, _ESYS_STATE_INIT, "SAPI Prepare returned error.");
183 
184     /* Calculate the cpHash Values */
185     r = init_session_tab(esysContext, shandle1, shandle2, shandle3);
186     return_state_if_error(r, _ESYS_STATE_INIT, "Initialize session resources");
187     if (authHandleNode != NULL)
188         iesys_compute_session_value(esysContext->session_tab[0],
189                 &authHandleNode->rsrc.name, &authHandleNode->auth);
190     else
191         iesys_compute_session_value(esysContext->session_tab[0], NULL, NULL);
192 
193     iesys_compute_session_value(esysContext->session_tab[1], NULL, NULL);
194     iesys_compute_session_value(esysContext->session_tab[2], NULL, NULL);
195 
196     /* Generate the auth values and set them in the SAPI command buffer */
197     r = iesys_gen_auths(esysContext, authHandleNode, NULL, NULL, &auths);
198     return_state_if_error(r, _ESYS_STATE_INIT,
199                           "Error in computation of auth values");
200 
201     esysContext->authsCount = auths.count;
202     if (auths.count > 0) {
203         r = Tss2_Sys_SetCmdAuths(esysContext->sys, &auths);
204         return_state_if_error(r, _ESYS_STATE_INIT, "SAPI error on SetCmdAuths");
205     }
206 
207     /* Trigger execution and finish the async invocation */
208     r = Tss2_Sys_ExecuteAsync(esysContext->sys);
209     return_state_if_error(r, _ESYS_STATE_INTERNALERROR,
210                           "Finish (Execute Async)");
211 
212     esysContext->state = _ESYS_STATE_SENT;
213 
214     return r;
215 }
216 
217 /** Asynchronous finish function for TPM2_PCR_SetAuthPolicy
218  *
219  * This function returns the results of a TPM2_PCR_SetAuthPolicy command
220  * invoked via Esys_PCR_SetAuthPolicy_Finish. All non-simple output parameters
221  * are allocated by the function's implementation. NULL can be passed for every
222  * output parameter if the value is not required.
223  *
224  * @param[in,out] esysContext The ESYS_CONTEXT.
225  * @retval TSS2_RC_SUCCESS on success
226  * @retval ESYS_RC_SUCCESS if the function call was a success.
227  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
228  *         pointers or required output handle references are NULL.
229  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
230  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
231  *         internal operations or return parameters.
232  * @retval TSS2_ESYS_RC_BAD_SEQUENCE: if the context has an asynchronous
233  *         operation already pending.
234  * @retval TSS2_ESYS_RC_TRY_AGAIN: if the timeout counter expires before the
235  *         TPM response is received.
236  * @retval TSS2_ESYS_RC_INSUFFICIENT_RESPONSE: if the TPM's response does not
237  *         at least contain the tag, response length, and response code.
238  * @retval TSS2_ESYS_RC_RSP_AUTH_FAILED: if the response HMAC from the TPM did
239  *         not verify.
240  * @retval TSS2_ESYS_RC_MALFORMED_RESPONSE: if the TPM's response is corrupted.
241  * @retval TSS2_RCs produced by lower layers of the software stack may be
242  *         returned to the caller unaltered unless handled internally.
243  */
244 TSS2_RC
Esys_PCR_SetAuthPolicy_Finish(ESYS_CONTEXT * esysContext)245 Esys_PCR_SetAuthPolicy_Finish(
246     ESYS_CONTEXT *esysContext)
247 {
248     TSS2_RC r;
249     LOG_TRACE("context=%p",
250               esysContext);
251 
252     if (esysContext == NULL) {
253         LOG_ERROR("esyscontext is NULL.");
254         return TSS2_ESYS_RC_BAD_REFERENCE;
255     }
256 
257     /* Check for correct sequence and set sequence to irregular for now */
258     if (esysContext->state != _ESYS_STATE_SENT &&
259         esysContext->state != _ESYS_STATE_RESUBMISSION) {
260         LOG_ERROR("Esys called in bad sequence.");
261         return TSS2_ESYS_RC_BAD_SEQUENCE;
262     }
263     esysContext->state = _ESYS_STATE_INTERNALERROR;
264 
265     /*Receive the TPM response and handle resubmissions if necessary. */
266     r = Tss2_Sys_ExecuteFinish(esysContext->sys, esysContext->timeout);
267     if ((r & ~TSS2_RC_LAYER_MASK) == TSS2_BASE_RC_TRY_AGAIN) {
268         LOG_DEBUG("A layer below returned TRY_AGAIN: %" PRIx32, r);
269         esysContext->state = _ESYS_STATE_SENT;
270         return r;
271     }
272     /* This block handle the resubmission of TPM commands given a certain set of
273      * TPM response codes. */
274     if (r == TPM2_RC_RETRY || r == TPM2_RC_TESTING || r == TPM2_RC_YIELDED) {
275         LOG_DEBUG("TPM returned RETRY, TESTING or YIELDED, which triggers a "
276             "resubmission: %" PRIx32, r);
277         if (esysContext->submissionCount++ >= _ESYS_MAX_SUBMISSIONS) {
278             LOG_WARNING("Maximum number of (re)submissions has been reached.");
279             esysContext->state = _ESYS_STATE_INIT;
280             return r;
281         }
282         esysContext->state = _ESYS_STATE_RESUBMISSION;
283         r = Tss2_Sys_ExecuteAsync(esysContext->sys);
284         if (r != TSS2_RC_SUCCESS) {
285             LOG_WARNING("Error attempting to resubmit");
286             /* We do not set esysContext->state here but inherit the most recent
287              * state of the _async function. */
288             return r;
289         }
290         r = TSS2_ESYS_RC_TRY_AGAIN;
291         LOG_DEBUG("Resubmission initiated and returning RC_TRY_AGAIN.");
292         return r;
293     }
294     /* The following is the "regular error" handling. */
295     if (iesys_tpm_error(r)) {
296         LOG_WARNING("Received TPM Error");
297         esysContext->state = _ESYS_STATE_INIT;
298         return r;
299     } else if (r != TSS2_RC_SUCCESS) {
300         LOG_ERROR("Received a non-TPM Error");
301         esysContext->state = _ESYS_STATE_INTERNALERROR;
302         return r;
303     }
304 
305     /*
306      * Now the verification of the response (hmac check) and if necessary the
307      * parameter decryption have to be done.
308      */
309     r = iesys_check_response(esysContext);
310     return_state_if_error(r, _ESYS_STATE_INTERNALERROR,
311                           "Error: check response");
312 
313     /*
314      * After the verification of the response we call the complete function
315      * to deliver the result.
316      */
317     r = Tss2_Sys_PCR_SetAuthPolicy_Complete(esysContext->sys);
318     return_state_if_error(r, _ESYS_STATE_INTERNALERROR,
319                           "Received error from SAPI unmarshaling" );
320 
321     esysContext->state = _ESYS_STATE_INIT;
322 
323     return TSS2_RC_SUCCESS;
324 }
325