xref: /aosp_15_r20/external/tpm2-tss/src/tss2-esys/api/Esys_SequenceComplete.c (revision 758e9fba6fc9adbf15340f70c73baee7b168b1c9)
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 /** Store command parameters inside the ESYS_CONTEXT for use during _Finish */
store_input_parameters(ESYS_CONTEXT * esysContext,ESYS_TR sequenceHandle)23 static void store_input_parameters (
24     ESYS_CONTEXT *esysContext,
25     ESYS_TR sequenceHandle)
26 {
27     esysContext->in.SequenceComplete.sequenceHandle = sequenceHandle;
28 }
29 
30 /** One-Call function for TPM2_SequenceComplete
31  *
32  * This function invokes the TPM2_SequenceComplete command in a one-call
33  * variant. This means the function will block until the TPM response is
34  * available. All input parameters are const. The memory for non-simple output
35  * parameters is allocated by the function implementation.
36  *
37  * @param[in,out] esysContext The ESYS_CONTEXT.
38  * @param[in]  sequenceHandle Authorization for the sequence.
39  * @param[in]  shandle1 Session handle for authorization of sequenceHandle
40  * @param[in]  shandle2 Second session handle.
41  * @param[in]  shandle3 Third session handle.
42  * @param[in]  buffer Data to be added to the hash/HMAC.
43  * @param[in]  hierarchy Hierarchy of the ticket for a hash.
44  * @param[out] result The returned HMAC or digest in a sized buffer.
45  *             (callee-allocated)
46  * @param[out] validation TPM2_Ticket indicating that the sequence of octets used to
47  *             compute outDigest did not start with TPM2_GENERATED_VALUE.
48  *             (callee-allocated)
49  * @retval TSS2_RC_SUCCESS if the function call was a success.
50  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
51  *         pointers or required output handle references are NULL.
52  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
53  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
54  *         internal operations or return parameters.
55  * @retval TSS2_ESYS_RC_BAD_SEQUENCE: if the context has an asynchronous
56  *         operation already pending.
57  * @retval TSS2_ESYS_RC_INSUFFICIENT_RESPONSE: if the TPM's response does not
58  *          at least contain the tag, response length, and response code.
59  * @retval TSS2_ESYS_RC_MALFORMED_RESPONSE: if the TPM's response is corrupted.
60  * @retval TSS2_ESYS_RC_RSP_AUTH_FAILED: if the response HMAC from the TPM
61            did not verify.
62  * @retval TSS2_ESYS_RC_MULTIPLE_DECRYPT_SESSIONS: if more than one session has
63  *         the 'decrypt' attribute bit set.
64  * @retval TSS2_ESYS_RC_MULTIPLE_ENCRYPT_SESSIONS: if more than one session has
65  *         the 'encrypt' attribute bit set.
66  * @retval TSS2_ESYS_RC_BAD_TR: if any of the ESYS_TR objects are unknown
67  *         to the ESYS_CONTEXT or are of the wrong type or if required
68  *         ESYS_TR objects are ESYS_TR_NONE.
69  * @retval TSS2_RCs produced by lower layers of the software stack may be
70  *         returned to the caller unaltered unless handled internally.
71  */
72 TSS2_RC
Esys_SequenceComplete(ESYS_CONTEXT * esysContext,ESYS_TR sequenceHandle,ESYS_TR shandle1,ESYS_TR shandle2,ESYS_TR shandle3,const TPM2B_MAX_BUFFER * buffer,TPMI_RH_HIERARCHY hierarchy,TPM2B_DIGEST ** result,TPMT_TK_HASHCHECK ** validation)73 Esys_SequenceComplete(
74     ESYS_CONTEXT *esysContext,
75     ESYS_TR sequenceHandle,
76     ESYS_TR shandle1,
77     ESYS_TR shandle2,
78     ESYS_TR shandle3,
79     const TPM2B_MAX_BUFFER *buffer,
80     TPMI_RH_HIERARCHY hierarchy,
81     TPM2B_DIGEST **result,
82     TPMT_TK_HASHCHECK **validation)
83 {
84     TSS2_RC r;
85 
86     r = Esys_SequenceComplete_Async(esysContext, sequenceHandle, shandle1,
87                                     shandle2, shandle3, buffer, hierarchy);
88     return_if_error(r, "Error in async function");
89 
90     /* Set the timeout to indefinite for now, since we want _Finish to block */
91     int32_t timeouttmp = esysContext->timeout;
92     esysContext->timeout = -1;
93     /*
94      * Now we call the finish function, until return code is not equal to
95      * from TSS2_BASE_RC_TRY_AGAIN.
96      * Note that the finish function may return TSS2_RC_TRY_AGAIN, even if we
97      * have set the timeout to -1. This occurs for example if the TPM requests
98      * a retransmission of the command via TPM2_RC_YIELDED.
99      */
100     do {
101         r = Esys_SequenceComplete_Finish(esysContext, result, validation);
102         /* This is just debug information about the reattempt to finish the
103            command */
104         if ((r & ~TSS2_RC_LAYER_MASK) == TSS2_BASE_RC_TRY_AGAIN)
105             LOG_DEBUG("A layer below returned TRY_AGAIN: %" PRIx32
106                       " => resubmitting command", r);
107     } while ((r & ~TSS2_RC_LAYER_MASK) == TSS2_BASE_RC_TRY_AGAIN);
108 
109     /* Restore the timeout value to the original value */
110     esysContext->timeout = timeouttmp;
111     return_if_error(r, "Esys Finish");
112 
113     return TSS2_RC_SUCCESS;
114 }
115 
116 /** Asynchronous function for TPM2_SequenceComplete
117  *
118  * This function invokes the TPM2_SequenceComplete command in a asynchronous
119  * variant. This means the function will return as soon as the command has been
120  * sent downwards the stack to the TPM. All input parameters are const.
121  * In order to retrieve the TPM's response call Esys_SequenceComplete_Finish.
122  *
123  * @param[in,out] esysContext The ESYS_CONTEXT.
124  * @param[in]  sequenceHandle Authorization for the sequence.
125  * @param[in]  shandle1 Session handle for authorization of sequenceHandle
126  * @param[in]  shandle2 Second session handle.
127  * @param[in]  shandle3 Third session handle.
128  * @param[in]  buffer Data to be added to the hash/HMAC.
129  * @param[in]  hierarchy Hierarchy of the ticket for a hash.
130  * @retval ESYS_RC_SUCCESS if the function call was a success.
131  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
132  *         pointers or required output handle references are NULL.
133  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
134  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
135  *         internal operations or return parameters.
136  * @retval TSS2_RCs produced by lower layers of the software stack may be
137            returned to the caller unaltered unless handled internally.
138  * @retval TSS2_ESYS_RC_MULTIPLE_DECRYPT_SESSIONS: if more than one session has
139  *         the 'decrypt' attribute bit set.
140  * @retval TSS2_ESYS_RC_MULTIPLE_ENCRYPT_SESSIONS: if more than one session has
141  *         the 'encrypt' attribute bit set.
142  * @retval TSS2_ESYS_RC_BAD_TR: if any of the ESYS_TR objects are unknown
143  *         to the ESYS_CONTEXT or are of the wrong type or if required
144  *         ESYS_TR objects are ESYS_TR_NONE.
145  */
146 TSS2_RC
Esys_SequenceComplete_Async(ESYS_CONTEXT * esysContext,ESYS_TR sequenceHandle,ESYS_TR shandle1,ESYS_TR shandle2,ESYS_TR shandle3,const TPM2B_MAX_BUFFER * buffer,TPMI_RH_HIERARCHY hierarchy)147 Esys_SequenceComplete_Async(
148     ESYS_CONTEXT *esysContext,
149     ESYS_TR sequenceHandle,
150     ESYS_TR shandle1,
151     ESYS_TR shandle2,
152     ESYS_TR shandle3,
153     const TPM2B_MAX_BUFFER *buffer,
154     TPMI_RH_HIERARCHY hierarchy)
155 {
156     TSS2_RC r;
157     LOG_TRACE("context=%p, sequenceHandle=%"PRIx32 ", buffer=%p,"
158               "hierarchy=%"PRIx32 "",
159               esysContext, sequenceHandle, buffer, hierarchy);
160     TSS2L_SYS_AUTH_COMMAND auths;
161     RSRC_NODE_T *sequenceHandleNode;
162 
163     /* Check context, sequence correctness and set state to error for now */
164     if (esysContext == NULL) {
165         LOG_ERROR("esyscontext is NULL.");
166         return TSS2_ESYS_RC_BAD_REFERENCE;
167     }
168     r = iesys_check_sequence_async(esysContext);
169     if (r != TSS2_RC_SUCCESS)
170         return r;
171     esysContext->state = _ESYS_STATE_INTERNALERROR;
172 
173     /* Check input parameters */
174     r = check_session_feasibility(shandle1, shandle2, shandle3, 1);
175     return_state_if_error(r, _ESYS_STATE_INIT, "Check session usage");
176     store_input_parameters(esysContext, sequenceHandle);
177 
178     /* Retrieve the metadata objects for provided handles */
179     r = esys_GetResourceObject(esysContext, sequenceHandle, &sequenceHandleNode);
180     return_state_if_error(r, _ESYS_STATE_INIT, "sequenceHandle unknown.");
181 
182     /* Initial invocation of SAPI to prepare the command buffer with parameters */
183     r = Tss2_Sys_SequenceComplete_Prepare(esysContext->sys,
184                                           (sequenceHandleNode == NULL)
185                                            ? TPM2_RH_NULL
186                                            : sequenceHandleNode->rsrc.handle,
187                                           buffer, hierarchy);
188     return_state_if_error(r, _ESYS_STATE_INIT, "SAPI Prepare returned error.");
189 
190     /* Calculate the cpHash Values */
191     r = init_session_tab(esysContext, shandle1, shandle2, shandle3);
192     return_state_if_error(r, _ESYS_STATE_INIT, "Initialize session resources");
193     if (sequenceHandleNode != NULL)
194         iesys_compute_session_value(esysContext->session_tab[0],
195                 &sequenceHandleNode->rsrc.name, &sequenceHandleNode->auth);
196     else
197         iesys_compute_session_value(esysContext->session_tab[0], NULL, NULL);
198 
199     iesys_compute_session_value(esysContext->session_tab[1], NULL, NULL);
200     iesys_compute_session_value(esysContext->session_tab[2], NULL, NULL);
201 
202     /* Generate the auth values and set them in the SAPI command buffer */
203     r = iesys_gen_auths(esysContext, sequenceHandleNode, NULL, NULL, &auths);
204     return_state_if_error(r, _ESYS_STATE_INIT,
205                           "Error in computation of auth values");
206 
207     esysContext->authsCount = auths.count;
208     if (auths.count > 0) {
209         r = Tss2_Sys_SetCmdAuths(esysContext->sys, &auths);
210         return_state_if_error(r, _ESYS_STATE_INIT, "SAPI error on SetCmdAuths");
211     }
212 
213     /* Trigger execution and finish the async invocation */
214     r = Tss2_Sys_ExecuteAsync(esysContext->sys);
215     return_state_if_error(r, _ESYS_STATE_INTERNALERROR,
216                           "Finish (Execute Async)");
217 
218     esysContext->state = _ESYS_STATE_SENT;
219 
220     return r;
221 }
222 
223 /** Asynchronous finish function for TPM2_SequenceComplete
224  *
225  * This function returns the results of a TPM2_SequenceComplete command
226  * invoked via Esys_SequenceComplete_Finish. All non-simple output parameters
227  * are allocated by the function's implementation. NULL can be passed for every
228  * output parameter if the value is not required.
229  *
230  * @param[in,out] esysContext The ESYS_CONTEXT.
231  * @param[out] result The returned HMAC or digest in a sized buffer.
232  *             (callee-allocated)
233  * @param[out] validation TPM2_Ticket indicating that the sequence of octets used to
234  *             compute outDigest did not start with TPM2_GENERATED_VALUE.
235  *             (callee-allocated)
236  * @retval TSS2_RC_SUCCESS on success
237  * @retval ESYS_RC_SUCCESS if the function call was a success.
238  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
239  *         pointers or required output handle references are NULL.
240  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
241  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
242  *         internal operations or return parameters.
243  * @retval TSS2_ESYS_RC_BAD_SEQUENCE: if the context has an asynchronous
244  *         operation already pending.
245  * @retval TSS2_ESYS_RC_TRY_AGAIN: if the timeout counter expires before the
246  *         TPM response is received.
247  * @retval TSS2_ESYS_RC_INSUFFICIENT_RESPONSE: if the TPM's response does not
248  *         at least contain the tag, response length, and response code.
249  * @retval TSS2_ESYS_RC_RSP_AUTH_FAILED: if the response HMAC from the TPM did
250  *         not verify.
251  * @retval TSS2_ESYS_RC_MALFORMED_RESPONSE: if the TPM's response is corrupted.
252  * @retval TSS2_RCs produced by lower layers of the software stack may be
253  *         returned to the caller unaltered unless handled internally.
254  */
255 TSS2_RC
Esys_SequenceComplete_Finish(ESYS_CONTEXT * esysContext,TPM2B_DIGEST ** result,TPMT_TK_HASHCHECK ** validation)256 Esys_SequenceComplete_Finish(
257     ESYS_CONTEXT *esysContext,
258     TPM2B_DIGEST **result,
259     TPMT_TK_HASHCHECK **validation)
260 {
261     TSS2_RC r;
262     LOG_TRACE("context=%p, result=%p, validation=%p",
263               esysContext, result, validation);
264 
265     if (esysContext == NULL) {
266         LOG_ERROR("esyscontext is NULL.");
267         return TSS2_ESYS_RC_BAD_REFERENCE;
268     }
269 
270     /* Check for correct sequence and set sequence to irregular for now */
271     if (esysContext->state != _ESYS_STATE_SENT &&
272         esysContext->state != _ESYS_STATE_RESUBMISSION) {
273         LOG_ERROR("Esys called in bad sequence.");
274         return TSS2_ESYS_RC_BAD_SEQUENCE;
275     }
276     esysContext->state = _ESYS_STATE_INTERNALERROR;
277 
278     /* Allocate memory for response parameters */
279     if (result != NULL) {
280         *result = calloc(sizeof(TPM2B_DIGEST), 1);
281         if (*result == NULL) {
282             return_error(TSS2_ESYS_RC_MEMORY, "Out of memory");
283         }
284     }
285     if (validation != NULL) {
286         *validation = calloc(sizeof(TPMT_TK_HASHCHECK), 1);
287         if (*validation == NULL) {
288             goto_error(r, TSS2_ESYS_RC_MEMORY, "Out of memory", error_cleanup);
289         }
290     }
291 
292     /*Receive the TPM response and handle resubmissions if necessary. */
293     r = Tss2_Sys_ExecuteFinish(esysContext->sys, esysContext->timeout);
294     if ((r & ~TSS2_RC_LAYER_MASK) == TSS2_BASE_RC_TRY_AGAIN) {
295         LOG_DEBUG("A layer below returned TRY_AGAIN: %" PRIx32, r);
296         esysContext->state = _ESYS_STATE_SENT;
297         goto error_cleanup;
298     }
299     /* This block handle the resubmission of TPM commands given a certain set of
300      * TPM response codes. */
301     if (r == TPM2_RC_RETRY || r == TPM2_RC_TESTING || r == TPM2_RC_YIELDED) {
302         LOG_DEBUG("TPM returned RETRY, TESTING or YIELDED, which triggers a "
303             "resubmission: %" PRIx32, r);
304         if (esysContext->submissionCount++ >= _ESYS_MAX_SUBMISSIONS) {
305             LOG_WARNING("Maximum number of (re)submissions has been reached.");
306             esysContext->state = _ESYS_STATE_INIT;
307             goto error_cleanup;
308         }
309         esysContext->state = _ESYS_STATE_RESUBMISSION;
310         r = Tss2_Sys_ExecuteAsync(esysContext->sys);
311         if (r != TSS2_RC_SUCCESS) {
312             LOG_WARNING("Error attempting to resubmit");
313             /* We do not set esysContext->state here but inherit the most recent
314              * state of the _async function. */
315             goto error_cleanup;
316         }
317         r = TSS2_ESYS_RC_TRY_AGAIN;
318         LOG_DEBUG("Resubmission initiated and returning RC_TRY_AGAIN.");
319         goto error_cleanup;
320     }
321     /* The following is the "regular error" handling. */
322     if (iesys_tpm_error(r)) {
323         LOG_WARNING("Received TPM Error");
324         esysContext->state = _ESYS_STATE_INIT;
325         goto error_cleanup;
326     } else if (r != TSS2_RC_SUCCESS) {
327         LOG_ERROR("Received a non-TPM Error");
328         esysContext->state = _ESYS_STATE_INTERNALERROR;
329         goto error_cleanup;
330     }
331 
332     /*
333      * Now the verification of the response (hmac check) and if necessary the
334      * parameter decryption have to be done.
335      */
336     r = iesys_check_response(esysContext);
337     goto_state_if_error(r, _ESYS_STATE_INTERNALERROR, "Error: check response",
338                         error_cleanup);
339 
340     /*
341      * After the verification of the response we call the complete function
342      * to deliver the result.
343      */
344     r = Tss2_Sys_SequenceComplete_Complete(esysContext->sys,
345                                            (result != NULL) ? *result : NULL,
346                                            (validation != NULL) ? *validation
347                                             : NULL);
348     goto_state_if_error(r, _ESYS_STATE_INTERNALERROR,
349                         "Received error from SAPI unmarshaling" ,
350                         error_cleanup);
351 
352     /* The ESYS_TR sequence object has to be invalidated */
353     r = Esys_TR_Close(esysContext,
354                       &esysContext->in.SequenceComplete.sequenceHandle);
355     goto_if_error(r, "invalidate object", error_cleanup);
356 
357     esysContext->state = _ESYS_STATE_INIT;
358 
359     return TSS2_RC_SUCCESS;
360 
361 error_cleanup:
362     if (result != NULL)
363         SAFE_FREE(*result);
364     if (validation != NULL)
365         SAFE_FREE(*validation);
366 
367     return r;
368 }
369