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_EC_Ephemeral
23  *
24  * This function invokes the TPM2_EC_Ephemeral 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]  shandle1 First session handle.
31  * @param[in]  shandle2 Second session handle.
32  * @param[in]  shandle3 Third session handle.
33  * @param[in]  curveID The curve for the computed ephemeral point .
34  * @param[out] Q Ephemeral public key Q := [r]G.
35  *             (callee-allocated)
36  * @param[out] counter Least-significant 16 bits of commitCount.
37  *             (callee-allocated)
38  * @retval TSS2_RC_SUCCESS if the function call was a success.
39  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
40  *         pointers or required output handle references are NULL.
41  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
42  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
43  *         internal operations or return parameters.
44  * @retval TSS2_ESYS_RC_BAD_SEQUENCE: if the context has an asynchronous
45  *         operation already pending.
46  * @retval TSS2_ESYS_RC_INSUFFICIENT_RESPONSE: if the TPM's response does not
47  *          at least contain the tag, response length, and response code.
48  * @retval TSS2_ESYS_RC_MALFORMED_RESPONSE: if the TPM's response is corrupted.
49  * @retval TSS2_ESYS_RC_RSP_AUTH_FAILED: if the response HMAC from the TPM
50            did not verify.
51  * @retval TSS2_ESYS_RC_MULTIPLE_DECRYPT_SESSIONS: if more than one session has
52  *         the 'decrypt' attribute bit set.
53  * @retval TSS2_ESYS_RC_MULTIPLE_ENCRYPT_SESSIONS: if more than one session has
54  *         the 'encrypt' attribute bit set.
55  * @retval TSS2_ESYS_RC_NO_DECRYPT_PARAM: if one of the sessions has the
56  *         'decrypt' attribute set and the command does not support encryption
57  *         of the first command parameter.
58  * @retval TSS2_RCs produced by lower layers of the software stack may be
59  *         returned to the caller unaltered unless handled internally.
60  */
61 TSS2_RC
Esys_EC_Ephemeral(ESYS_CONTEXT * esysContext,ESYS_TR shandle1,ESYS_TR shandle2,ESYS_TR shandle3,TPMI_ECC_CURVE curveID,TPM2B_ECC_POINT ** Q,UINT16 * counter)62 Esys_EC_Ephemeral(
63     ESYS_CONTEXT *esysContext,
64     ESYS_TR shandle1,
65     ESYS_TR shandle2,
66     ESYS_TR shandle3,
67     TPMI_ECC_CURVE curveID,
68     TPM2B_ECC_POINT **Q,
69     UINT16 *counter)
70 {
71     TSS2_RC r;
72 
73     r = Esys_EC_Ephemeral_Async(esysContext, shandle1, shandle2, shandle3,
74                                 curveID);
75     return_if_error(r, "Error in async function");
76 
77     /* Set the timeout to indefinite for now, since we want _Finish to block */
78     int32_t timeouttmp = esysContext->timeout;
79     esysContext->timeout = -1;
80     /*
81      * Now we call the finish function, until return code is not equal to
82      * from TSS2_BASE_RC_TRY_AGAIN.
83      * Note that the finish function may return TSS2_RC_TRY_AGAIN, even if we
84      * have set the timeout to -1. This occurs for example if the TPM requests
85      * a retransmission of the command via TPM2_RC_YIELDED.
86      */
87     do {
88         r = Esys_EC_Ephemeral_Finish(esysContext, Q, counter);
89         /* This is just debug information about the reattempt to finish the
90            command */
91         if (base_rc(r) == TSS2_BASE_RC_TRY_AGAIN)
92             LOG_DEBUG("A layer below returned TRY_AGAIN: %" PRIx32
93                       " => resubmitting command", r);
94     } while (base_rc(r) == TSS2_BASE_RC_TRY_AGAIN);
95 
96     /* Restore the timeout value to the original value */
97     esysContext->timeout = timeouttmp;
98     return_if_error(r, "Esys Finish");
99 
100     return TSS2_RC_SUCCESS;
101 }
102 
103 /** Asynchronous function for TPM2_EC_Ephemeral
104  *
105  * This function invokes the TPM2_EC_Ephemeral command in a asynchronous
106  * variant. This means the function will return as soon as the command has been
107  * sent downwards the stack to the TPM. All input parameters are const.
108  * In order to retrieve the TPM's response call Esys_EC_Ephemeral_Finish.
109  *
110  * @param[in,out] esysContext The ESYS_CONTEXT.
111  * @param[in]  shandle1 First session handle.
112  * @param[in]  shandle2 Second session handle.
113  * @param[in]  shandle3 Third session handle.
114  * @param[in]  curveID The curve for the computed ephemeral point .
115  * @retval ESYS_RC_SUCCESS if the function call was a success.
116  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
117  *         pointers or required output handle references are NULL.
118  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
119  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
120  *         internal operations or return parameters.
121  * @retval TSS2_RCs produced by lower layers of the software stack may be
122            returned to the caller unaltered unless handled internally.
123  * @retval TSS2_ESYS_RC_MULTIPLE_DECRYPT_SESSIONS: if more than one session has
124  *         the 'decrypt' attribute bit set.
125  * @retval TSS2_ESYS_RC_MULTIPLE_ENCRYPT_SESSIONS: if more than one session has
126  *         the 'encrypt' attribute bit set.
127  * @retval TSS2_ESYS_RC_NO_DECRYPT_PARAM: if one of the sessions has the
128  *         'decrypt' attribute set and the command does not support encryption
129  *         of the first command parameter.
130  */
131 TSS2_RC
Esys_EC_Ephemeral_Async(ESYS_CONTEXT * esysContext,ESYS_TR shandle1,ESYS_TR shandle2,ESYS_TR shandle3,TPMI_ECC_CURVE curveID)132 Esys_EC_Ephemeral_Async(
133     ESYS_CONTEXT *esysContext,
134     ESYS_TR shandle1,
135     ESYS_TR shandle2,
136     ESYS_TR shandle3,
137     TPMI_ECC_CURVE curveID)
138 {
139     TSS2_RC r;
140     LOG_TRACE("context=%p, curveID=%04"PRIx16"",
141               esysContext, curveID);
142     TSS2L_SYS_AUTH_COMMAND auths;
143 
144     /* Check context, sequence correctness and set state to error for now */
145     if (esysContext == NULL) {
146         LOG_ERROR("esyscontext is NULL.");
147         return TSS2_ESYS_RC_BAD_REFERENCE;
148     }
149     r = iesys_check_sequence_async(esysContext);
150     if (r != TSS2_RC_SUCCESS)
151         return r;
152     esysContext->state = _ESYS_STATE_INTERNALERROR;
153 
154     /* Check input parameters */
155     r = check_session_feasibility(shandle1, shandle2, shandle3, 0);
156     return_state_if_error(r, _ESYS_STATE_INIT, "Check session usage");
157 
158     /* Initial invocation of SAPI to prepare the command buffer with parameters */
159     r = Tss2_Sys_EC_Ephemeral_Prepare(esysContext->sys, curveID);
160     return_state_if_error(r, _ESYS_STATE_INIT, "SAPI Prepare returned error.");
161 
162     /* Calculate the cpHash Values */
163     r = init_session_tab(esysContext, shandle1, shandle2, shandle3);
164     return_state_if_error(r, _ESYS_STATE_INIT, "Initialize session resources");
165     iesys_compute_session_value(esysContext->session_tab[0], NULL, NULL);
166     iesys_compute_session_value(esysContext->session_tab[1], NULL, NULL);
167     iesys_compute_session_value(esysContext->session_tab[2], NULL, NULL);
168 
169     /* Generate the auth values and set them in the SAPI command buffer */
170     r = iesys_gen_auths(esysContext, NULL, NULL, NULL, &auths);
171     return_state_if_error(r, _ESYS_STATE_INIT,
172                           "Error in computation of auth values");
173 
174     esysContext->authsCount = auths.count;
175     if (auths.count > 0) {
176         r = Tss2_Sys_SetCmdAuths(esysContext->sys, &auths);
177         return_state_if_error(r, _ESYS_STATE_INIT, "SAPI error on SetCmdAuths");
178     }
179 
180     /* Trigger execution and finish the async invocation */
181     r = Tss2_Sys_ExecuteAsync(esysContext->sys);
182     return_state_if_error(r, _ESYS_STATE_INTERNALERROR,
183                           "Finish (Execute Async)");
184 
185     esysContext->state = _ESYS_STATE_SENT;
186 
187     return r;
188 }
189 
190 /** Asynchronous finish function for TPM2_EC_Ephemeral
191  *
192  * This function returns the results of a TPM2_EC_Ephemeral command
193  * invoked via Esys_EC_Ephemeral_Finish. All non-simple output parameters
194  * are allocated by the function's implementation. NULL can be passed for every
195  * output parameter if the value is not required.
196  *
197  * @param[in,out] esysContext The ESYS_CONTEXT.
198  * @param[out] Q Ephemeral public key Q := [r]G.
199  *             (callee-allocated)
200  * @param[out] counter Least-significant 16 bits of commitCount.
201  *             (callee-allocated)
202  * @retval TSS2_RC_SUCCESS on success
203  * @retval ESYS_RC_SUCCESS if the function call was a success.
204  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
205  *         pointers or required output handle references are NULL.
206  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
207  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
208  *         internal operations or return parameters.
209  * @retval TSS2_ESYS_RC_BAD_SEQUENCE: if the context has an asynchronous
210  *         operation already pending.
211  * @retval TSS2_ESYS_RC_TRY_AGAIN: if the timeout counter expires before the
212  *         TPM response is received.
213  * @retval TSS2_ESYS_RC_INSUFFICIENT_RESPONSE: if the TPM's response does not
214  *         at least contain the tag, response length, and response code.
215  * @retval TSS2_ESYS_RC_RSP_AUTH_FAILED: if the response HMAC from the TPM did
216  *         not verify.
217  * @retval TSS2_ESYS_RC_MALFORMED_RESPONSE: if the TPM's response is corrupted.
218  * @retval TSS2_RCs produced by lower layers of the software stack may be
219  *         returned to the caller unaltered unless handled internally.
220  */
221 TSS2_RC
Esys_EC_Ephemeral_Finish(ESYS_CONTEXT * esysContext,TPM2B_ECC_POINT ** Q,UINT16 * counter)222 Esys_EC_Ephemeral_Finish(
223     ESYS_CONTEXT *esysContext,
224     TPM2B_ECC_POINT **Q,
225     UINT16 *counter)
226 {
227     TSS2_RC r;
228     LOG_TRACE("context=%p, Q=%p, counter=%p",
229               esysContext, Q, counter);
230 
231     if (esysContext == NULL) {
232         LOG_ERROR("esyscontext is NULL.");
233         return TSS2_ESYS_RC_BAD_REFERENCE;
234     }
235 
236     /* Check for correct sequence and set sequence to irregular for now */
237     if (esysContext->state != _ESYS_STATE_SENT &&
238         esysContext->state != _ESYS_STATE_RESUBMISSION) {
239         LOG_ERROR("Esys called in bad sequence.");
240         return TSS2_ESYS_RC_BAD_SEQUENCE;
241     }
242     esysContext->state = _ESYS_STATE_INTERNALERROR;
243 
244     /* Allocate memory for response parameters */
245     if (Q != NULL) {
246         *Q = calloc(sizeof(TPM2B_ECC_POINT), 1);
247         if (*Q == NULL) {
248             return_error(TSS2_ESYS_RC_MEMORY, "Out of memory");
249         }
250     }
251 
252     /*Receive the TPM response and handle resubmissions if necessary. */
253     r = Tss2_Sys_ExecuteFinish(esysContext->sys, esysContext->timeout);
254     if (base_rc(r) == TSS2_BASE_RC_TRY_AGAIN) {
255         LOG_DEBUG("A layer below returned TRY_AGAIN: %" PRIx32, r);
256         esysContext->state = _ESYS_STATE_SENT;
257         goto error_cleanup;
258     }
259     /* This block handle the resubmission of TPM commands given a certain set of
260      * TPM response codes. */
261     if (r == TPM2_RC_RETRY || r == TPM2_RC_TESTING || r == TPM2_RC_YIELDED) {
262         LOG_DEBUG("TPM returned RETRY, TESTING or YIELDED, which triggers a "
263             "resubmission: %" PRIx32, r);
264         if (esysContext->submissionCount++ >= _ESYS_MAX_SUBMISSIONS) {
265             LOG_WARNING("Maximum number of (re)submissions has been reached.");
266             esysContext->state = _ESYS_STATE_INIT;
267             goto error_cleanup;
268         }
269         esysContext->state = _ESYS_STATE_RESUBMISSION;
270         r = Tss2_Sys_ExecuteAsync(esysContext->sys);
271         if (r != TSS2_RC_SUCCESS) {
272             LOG_WARNING("Error attempting to resubmit");
273             /* We do not set esysContext->state here but inherit the most recent
274              * state of the _async function. */
275             goto error_cleanup;
276         }
277         r = TSS2_ESYS_RC_TRY_AGAIN;
278         LOG_DEBUG("Resubmission initiated and returning RC_TRY_AGAIN.");
279         goto error_cleanup;
280     }
281     /* The following is the "regular error" handling. */
282     if (iesys_tpm_error(r)) {
283         LOG_WARNING("Received TPM Error");
284         esysContext->state = _ESYS_STATE_INIT;
285         goto error_cleanup;
286     } else if (r != TSS2_RC_SUCCESS) {
287         LOG_ERROR("Received a non-TPM Error");
288         esysContext->state = _ESYS_STATE_INTERNALERROR;
289         goto error_cleanup;
290     }
291 
292     /*
293      * Now the verification of the response (hmac check) and if necessary the
294      * parameter decryption have to be done.
295      */
296     r = iesys_check_response(esysContext);
297     goto_state_if_error(r, _ESYS_STATE_INTERNALERROR, "Error: check response",
298                         error_cleanup);
299 
300     /*
301      * After the verification of the response we call the complete function
302      * to deliver the result.
303      */
304     r = Tss2_Sys_EC_Ephemeral_Complete(esysContext->sys,
305                                        (Q != NULL) ? *Q : NULL, counter);
306     goto_state_if_error(r, _ESYS_STATE_INTERNALERROR,
307                         "Received error from SAPI unmarshaling" ,
308                         error_cleanup);
309 
310     esysContext->state = _ESYS_STATE_INIT;
311 
312     return TSS2_RC_SUCCESS;
313 
314 error_cleanup:
315     if (Q != NULL)
316         SAFE_FREE(*Q);
317 
318     return r;
319 }
320