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