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