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