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_Rewrap
23  *
24  * This function invokes the TPM2_Rewrap 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]  oldParent Parent of object.
31  * @param[in]  newParent New parent of the object.
32  * @param[in]  shandle1 Session handle for authorization of oldParent
33  * @param[in]  shandle2 Second session handle.
34  * @param[in]  shandle3 Third session handle.
35  * @param[in]  inDuplicate An object encrypted using symmetric key derived from
36  *             inSymSeed.
37  * @param[in]  name The Name of the object being rewrapped.
38  * @param[in]  inSymSeed The seed for the symmetric key and HMAC key.
39  * @param[out] outDuplicate An object encrypted using symmetric key derived
40  *             from outSymSeed.
41  *             (callee-allocated)
42  * @param[out] outSymSeed Seed for a symmetric key protected by newParent
43  *             asymmetric key.
44  *             (callee-allocated)
45  * @retval TSS2_RC_SUCCESS if the function call was a success.
46  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
47  *         pointers or required output handle references are NULL.
48  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
49  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
50  *         internal operations or return parameters.
51  * @retval TSS2_ESYS_RC_BAD_SEQUENCE: if the context has an asynchronous
52  *         operation already pending.
53  * @retval TSS2_ESYS_RC_INSUFFICIENT_RESPONSE: if the TPM's response does not
54  *          at least contain the tag, response length, and response code.
55  * @retval TSS2_ESYS_RC_MALFORMED_RESPONSE: if the TPM's response is corrupted.
56  * @retval TSS2_ESYS_RC_RSP_AUTH_FAILED: if the response HMAC from the TPM
57            did not verify.
58  * @retval TSS2_ESYS_RC_MULTIPLE_DECRYPT_SESSIONS: if more than one session has
59  *         the 'decrypt' attribute bit set.
60  * @retval TSS2_ESYS_RC_MULTIPLE_ENCRYPT_SESSIONS: if more than one session has
61  *         the 'encrypt' attribute bit set.
62  * @retval TSS2_ESYS_RC_BAD_TR: if any of the ESYS_TR objects are unknown
63  *         to the ESYS_CONTEXT or are of the wrong type or if required
64  *         ESYS_TR objects are ESYS_TR_NONE.
65  * @retval TSS2_RCs produced by lower layers of the software stack may be
66  *         returned to the caller unaltered unless handled internally.
67  */
68 TSS2_RC
Esys_Rewrap(ESYS_CONTEXT * esysContext,ESYS_TR oldParent,ESYS_TR newParent,ESYS_TR shandle1,ESYS_TR shandle2,ESYS_TR shandle3,const TPM2B_PRIVATE * inDuplicate,const TPM2B_NAME * name,const TPM2B_ENCRYPTED_SECRET * inSymSeed,TPM2B_PRIVATE ** outDuplicate,TPM2B_ENCRYPTED_SECRET ** outSymSeed)69 Esys_Rewrap(
70     ESYS_CONTEXT *esysContext,
71     ESYS_TR oldParent,
72     ESYS_TR newParent,
73     ESYS_TR shandle1,
74     ESYS_TR shandle2,
75     ESYS_TR shandle3,
76     const TPM2B_PRIVATE *inDuplicate,
77     const TPM2B_NAME *name,
78     const TPM2B_ENCRYPTED_SECRET *inSymSeed,
79     TPM2B_PRIVATE **outDuplicate,
80     TPM2B_ENCRYPTED_SECRET **outSymSeed)
81 {
82     TSS2_RC r;
83 
84     r = Esys_Rewrap_Async(esysContext, oldParent, newParent, shandle1, shandle2,
85                           shandle3, inDuplicate, name, inSymSeed);
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_Rewrap_Finish(esysContext, outDuplicate, outSymSeed);
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_Rewrap
115  *
116  * This function invokes the TPM2_Rewrap 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_Rewrap_Finish.
120  *
121  * @param[in,out] esysContext The ESYS_CONTEXT.
122  * @param[in]  oldParent Parent of object.
123  * @param[in]  newParent New parent of the object.
124  * @param[in]  shandle1 Session handle for authorization of oldParent
125  * @param[in]  shandle2 Second session handle.
126  * @param[in]  shandle3 Third session handle.
127  * @param[in]  inDuplicate An object encrypted using symmetric key derived from
128  *             inSymSeed.
129  * @param[in]  name The Name of the object being rewrapped.
130  * @param[in]  inSymSeed The seed for the symmetric key and HMAC key.
131  * @retval ESYS_RC_SUCCESS if the function call was a success.
132  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
133  *         pointers or required output handle references are NULL.
134  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
135  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
136  *         internal operations or return parameters.
137  * @retval TSS2_RCs produced by lower layers of the software stack may be
138            returned to the caller unaltered unless handled internally.
139  * @retval TSS2_ESYS_RC_MULTIPLE_DECRYPT_SESSIONS: if more than one session has
140  *         the 'decrypt' attribute bit set.
141  * @retval TSS2_ESYS_RC_MULTIPLE_ENCRYPT_SESSIONS: if more than one session has
142  *         the 'encrypt' attribute bit set.
143  * @retval TSS2_ESYS_RC_BAD_TR: if any of the ESYS_TR objects are unknown
144  *         to the ESYS_CONTEXT or are of the wrong type or if required
145  *         ESYS_TR objects are ESYS_TR_NONE.
146  */
147 TSS2_RC
Esys_Rewrap_Async(ESYS_CONTEXT * esysContext,ESYS_TR oldParent,ESYS_TR newParent,ESYS_TR shandle1,ESYS_TR shandle2,ESYS_TR shandle3,const TPM2B_PRIVATE * inDuplicate,const TPM2B_NAME * name,const TPM2B_ENCRYPTED_SECRET * inSymSeed)148 Esys_Rewrap_Async(
149     ESYS_CONTEXT *esysContext,
150     ESYS_TR oldParent,
151     ESYS_TR newParent,
152     ESYS_TR shandle1,
153     ESYS_TR shandle2,
154     ESYS_TR shandle3,
155     const TPM2B_PRIVATE *inDuplicate,
156     const TPM2B_NAME *name,
157     const TPM2B_ENCRYPTED_SECRET *inSymSeed)
158 {
159     TSS2_RC r;
160     LOG_TRACE("context=%p, oldParent=%"PRIx32 ", newParent=%"PRIx32 ","
161               "inDuplicate=%p, name=%p, inSymSeed=%p",
162               esysContext, oldParent, newParent, inDuplicate, name,
163               inSymSeed);
164     TSS2L_SYS_AUTH_COMMAND auths;
165     RSRC_NODE_T *oldParentNode;
166     RSRC_NODE_T *newParentNode;
167 
168     /* Check context, sequence correctness and set state to error for now */
169     if (esysContext == NULL) {
170         LOG_ERROR("esyscontext is NULL.");
171         return TSS2_ESYS_RC_BAD_REFERENCE;
172     }
173     r = iesys_check_sequence_async(esysContext);
174     if (r != TSS2_RC_SUCCESS)
175         return r;
176     esysContext->state = _ESYS_STATE_INTERNALERROR;
177 
178     /* Check input parameters */
179     r = check_session_feasibility(shandle1, shandle2, shandle3, 1);
180     return_state_if_error(r, _ESYS_STATE_INIT, "Check session usage");
181 
182     /* Retrieve the metadata objects for provided handles */
183     r = esys_GetResourceObject(esysContext, oldParent, &oldParentNode);
184     return_state_if_error(r, _ESYS_STATE_INIT, "oldParent unknown.");
185     r = esys_GetResourceObject(esysContext, newParent, &newParentNode);
186     return_state_if_error(r, _ESYS_STATE_INIT, "newParent unknown.");
187 
188     /* Initial invocation of SAPI to prepare the command buffer with parameters */
189     r = Tss2_Sys_Rewrap_Prepare(esysContext->sys,
190                                 (oldParentNode == NULL) ? TPM2_RH_NULL
191                                  : oldParentNode->rsrc.handle,
192                                 (newParentNode == NULL) ? TPM2_RH_NULL
193                                  : newParentNode->rsrc.handle, inDuplicate, name,
194                                 inSymSeed);
195     return_state_if_error(r, _ESYS_STATE_INIT, "SAPI Prepare returned error.");
196 
197     /* Calculate the cpHash Values */
198     r = init_session_tab(esysContext, shandle1, shandle2, shandle3);
199     return_state_if_error(r, _ESYS_STATE_INIT, "Initialize session resources");
200     if (oldParentNode != NULL)
201         iesys_compute_session_value(esysContext->session_tab[0],
202                 &oldParentNode->rsrc.name, &oldParentNode->auth);
203     else
204         iesys_compute_session_value(esysContext->session_tab[0], NULL, NULL);
205 
206     iesys_compute_session_value(esysContext->session_tab[1], NULL, NULL);
207     iesys_compute_session_value(esysContext->session_tab[2], NULL, NULL);
208 
209     /* Generate the auth values and set them in the SAPI command buffer */
210     r = iesys_gen_auths(esysContext, oldParentNode, newParentNode, NULL, &auths);
211     return_state_if_error(r, _ESYS_STATE_INIT,
212                           "Error in computation of auth values");
213 
214     esysContext->authsCount = auths.count;
215     if (auths.count > 0) {
216         r = Tss2_Sys_SetCmdAuths(esysContext->sys, &auths);
217         return_state_if_error(r, _ESYS_STATE_INIT, "SAPI error on SetCmdAuths");
218     }
219 
220     /* Trigger execution and finish the async invocation */
221     r = Tss2_Sys_ExecuteAsync(esysContext->sys);
222     return_state_if_error(r, _ESYS_STATE_INTERNALERROR,
223                           "Finish (Execute Async)");
224 
225     esysContext->state = _ESYS_STATE_SENT;
226 
227     return r;
228 }
229 
230 /** Asynchronous finish function for TPM2_Rewrap
231  *
232  * This function returns the results of a TPM2_Rewrap command
233  * invoked via Esys_Rewrap_Finish. All non-simple output parameters
234  * are allocated by the function's implementation. NULL can be passed for every
235  * output parameter if the value is not required.
236  *
237  * @param[in,out] esysContext The ESYS_CONTEXT.
238  * @param[out] outDuplicate An object encrypted using symmetric key derived
239  *             from outSymSeed.
240  *             (callee-allocated)
241  * @param[out] outSymSeed Seed for a symmetric key protected by newParent
242  *             asymmetric key.
243  *             (callee-allocated)
244  * @retval TSS2_RC_SUCCESS on success
245  * @retval ESYS_RC_SUCCESS if the function call was a success.
246  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
247  *         pointers or required output handle references are NULL.
248  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
249  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
250  *         internal operations or return parameters.
251  * @retval TSS2_ESYS_RC_BAD_SEQUENCE: if the context has an asynchronous
252  *         operation already pending.
253  * @retval TSS2_ESYS_RC_TRY_AGAIN: if the timeout counter expires before the
254  *         TPM response is received.
255  * @retval TSS2_ESYS_RC_INSUFFICIENT_RESPONSE: if the TPM's response does not
256  *         at least contain the tag, response length, and response code.
257  * @retval TSS2_ESYS_RC_RSP_AUTH_FAILED: if the response HMAC from the TPM did
258  *         not verify.
259  * @retval TSS2_ESYS_RC_MALFORMED_RESPONSE: if the TPM's response is corrupted.
260  * @retval TSS2_RCs produced by lower layers of the software stack may be
261  *         returned to the caller unaltered unless handled internally.
262  */
263 TSS2_RC
Esys_Rewrap_Finish(ESYS_CONTEXT * esysContext,TPM2B_PRIVATE ** outDuplicate,TPM2B_ENCRYPTED_SECRET ** outSymSeed)264 Esys_Rewrap_Finish(
265     ESYS_CONTEXT *esysContext,
266     TPM2B_PRIVATE **outDuplicate,
267     TPM2B_ENCRYPTED_SECRET **outSymSeed)
268 {
269     TSS2_RC r;
270     LOG_TRACE("context=%p, outDuplicate=%p, outSymSeed=%p",
271               esysContext, outDuplicate, outSymSeed);
272 
273     if (esysContext == NULL) {
274         LOG_ERROR("esyscontext is NULL.");
275         return TSS2_ESYS_RC_BAD_REFERENCE;
276     }
277 
278     /* Check for correct sequence and set sequence to irregular for now */
279     if (esysContext->state != _ESYS_STATE_SENT &&
280         esysContext->state != _ESYS_STATE_RESUBMISSION) {
281         LOG_ERROR("Esys called in bad sequence.");
282         return TSS2_ESYS_RC_BAD_SEQUENCE;
283     }
284     esysContext->state = _ESYS_STATE_INTERNALERROR;
285 
286     /* Allocate memory for response parameters */
287     if (outDuplicate != NULL) {
288         *outDuplicate = calloc(sizeof(TPM2B_PRIVATE), 1);
289         if (*outDuplicate == NULL) {
290             return_error(TSS2_ESYS_RC_MEMORY, "Out of memory");
291         }
292     }
293     if (outSymSeed != NULL) {
294         *outSymSeed = calloc(sizeof(TPM2B_ENCRYPTED_SECRET), 1);
295         if (*outSymSeed == NULL) {
296             goto_error(r, TSS2_ESYS_RC_MEMORY, "Out of memory", error_cleanup);
297         }
298     }
299 
300     /*Receive the TPM response and handle resubmissions if necessary. */
301     r = Tss2_Sys_ExecuteFinish(esysContext->sys, esysContext->timeout);
302     if ((r & ~TSS2_RC_LAYER_MASK) == TSS2_BASE_RC_TRY_AGAIN) {
303         LOG_DEBUG("A layer below returned TRY_AGAIN: %" PRIx32, r);
304         esysContext->state = _ESYS_STATE_SENT;
305         goto error_cleanup;
306     }
307     /* This block handle the resubmission of TPM commands given a certain set of
308      * TPM response codes. */
309     if (r == TPM2_RC_RETRY || r == TPM2_RC_TESTING || r == TPM2_RC_YIELDED) {
310         LOG_DEBUG("TPM returned RETRY, TESTING or YIELDED, which triggers a "
311             "resubmission: %" PRIx32, r);
312         if (esysContext->submissionCount++ >= _ESYS_MAX_SUBMISSIONS) {
313             LOG_WARNING("Maximum number of (re)submissions has been reached.");
314             esysContext->state = _ESYS_STATE_INIT;
315             goto error_cleanup;
316         }
317         esysContext->state = _ESYS_STATE_RESUBMISSION;
318         r = Tss2_Sys_ExecuteAsync(esysContext->sys);
319         if (r != TSS2_RC_SUCCESS) {
320             LOG_WARNING("Error attempting to resubmit");
321             /* We do not set esysContext->state here but inherit the most recent
322              * state of the _async function. */
323             goto error_cleanup;
324         }
325         r = TSS2_ESYS_RC_TRY_AGAIN;
326         LOG_DEBUG("Resubmission initiated and returning RC_TRY_AGAIN.");
327         goto error_cleanup;
328     }
329     /* The following is the "regular error" handling. */
330     if (iesys_tpm_error(r)) {
331         LOG_WARNING("Received TPM Error");
332         esysContext->state = _ESYS_STATE_INIT;
333         goto error_cleanup;
334     } else if (r != TSS2_RC_SUCCESS) {
335         LOG_ERROR("Received a non-TPM Error");
336         esysContext->state = _ESYS_STATE_INTERNALERROR;
337         goto error_cleanup;
338     }
339 
340     /*
341      * Now the verification of the response (hmac check) and if necessary the
342      * parameter decryption have to be done.
343      */
344     r = iesys_check_response(esysContext);
345     goto_state_if_error(r, _ESYS_STATE_INTERNALERROR, "Error: check response",
346                         error_cleanup);
347 
348     /*
349      * After the verification of the response we call the complete function
350      * to deliver the result.
351      */
352     r = Tss2_Sys_Rewrap_Complete(esysContext->sys,
353                                  (outDuplicate != NULL) ? *outDuplicate : NULL,
354                                  (outSymSeed != NULL) ? *outSymSeed : NULL);
355     goto_state_if_error(r, _ESYS_STATE_INTERNALERROR,
356                         "Received error from SAPI unmarshaling" ,
357                         error_cleanup);
358 
359     esysContext->state = _ESYS_STATE_INIT;
360 
361     return TSS2_RC_SUCCESS;
362 
363 error_cleanup:
364     if (outDuplicate != NULL)
365         SAFE_FREE(*outDuplicate);
366     if (outSymSeed != NULL)
367         SAFE_FREE(*outSymSeed);
368 
369     return r;
370 }
371