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