xref: /aosp_15_r20/external/tpm2-tss/src/tss2-esys/api/Esys_ECDH_ZGen.c (revision 758e9fba6fc9adbf15340f70c73baee7b168b1c9)
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_ECDH_ZGen
23  *
24  * This function invokes the TPM2_ECDH_ZGen 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]  keyHandle Handle of a loaded ECC key.
31  * @param[in]  shandle1 Session handle for authorization of keyHandle
32  * @param[in]  shandle2 Second session handle.
33  * @param[in]  shandle3 Third session handle.
34  * @param[in]  inPoint A public key.
35  * @param[out] outPoint X and Y coordinates of the product of the
36  *             multiplication Z = (xZ , yZ) := [hdS]QB.
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_BAD_TR: if any of the ESYS_TR objects are unknown
56  *         to the ESYS_CONTEXT or are of the wrong type or if required
57  *         ESYS_TR objects are ESYS_TR_NONE.
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_ECDH_ZGen(ESYS_CONTEXT * esysContext,ESYS_TR keyHandle,ESYS_TR shandle1,ESYS_TR shandle2,ESYS_TR shandle3,const TPM2B_ECC_POINT * inPoint,TPM2B_ECC_POINT ** outPoint)62 Esys_ECDH_ZGen(
63     ESYS_CONTEXT *esysContext,
64     ESYS_TR keyHandle,
65     ESYS_TR shandle1,
66     ESYS_TR shandle2,
67     ESYS_TR shandle3,
68     const TPM2B_ECC_POINT *inPoint,
69     TPM2B_ECC_POINT **outPoint)
70 {
71     TSS2_RC r;
72 
73     r = Esys_ECDH_ZGen_Async(esysContext, keyHandle, shandle1, shandle2,
74                              shandle3, inPoint);
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_ECDH_ZGen_Finish(esysContext, outPoint);
89         /* This is just debug information about the reattempt to finish the
90            command */
91         if ((r & ~TSS2_RC_LAYER_MASK) == TSS2_BASE_RC_TRY_AGAIN)
92             LOG_DEBUG("A layer below returned TRY_AGAIN: %" PRIx32
93                       " => resubmitting command", r);
94     } while ((r & ~TSS2_RC_LAYER_MASK) == 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_ECDH_ZGen
104  *
105  * This function invokes the TPM2_ECDH_ZGen 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_ECDH_ZGen_Finish.
109  *
110  * @param[in,out] esysContext The ESYS_CONTEXT.
111  * @param[in]  keyHandle Handle of a loaded ECC key.
112  * @param[in]  shandle1 Session handle for authorization of keyHandle
113  * @param[in]  shandle2 Second session handle.
114  * @param[in]  shandle3 Third session handle.
115  * @param[in]  inPoint A public key.
116  * @retval ESYS_RC_SUCCESS if the function call was a success.
117  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
118  *         pointers or required output handle references are NULL.
119  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
120  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
121  *         internal operations or return parameters.
122  * @retval TSS2_RCs produced by lower layers of the software stack may be
123            returned to the caller unaltered unless handled internally.
124  * @retval TSS2_ESYS_RC_MULTIPLE_DECRYPT_SESSIONS: if more than one session has
125  *         the 'decrypt' attribute bit set.
126  * @retval TSS2_ESYS_RC_MULTIPLE_ENCRYPT_SESSIONS: if more than one session has
127  *         the 'encrypt' attribute bit set.
128  * @retval TSS2_ESYS_RC_BAD_TR: if any of the ESYS_TR objects are unknown
129  *         to the ESYS_CONTEXT or are of the wrong type or if required
130  *         ESYS_TR objects are ESYS_TR_NONE.
131  */
132 TSS2_RC
Esys_ECDH_ZGen_Async(ESYS_CONTEXT * esysContext,ESYS_TR keyHandle,ESYS_TR shandle1,ESYS_TR shandle2,ESYS_TR shandle3,const TPM2B_ECC_POINT * inPoint)133 Esys_ECDH_ZGen_Async(
134     ESYS_CONTEXT *esysContext,
135     ESYS_TR keyHandle,
136     ESYS_TR shandle1,
137     ESYS_TR shandle2,
138     ESYS_TR shandle3,
139     const TPM2B_ECC_POINT *inPoint)
140 {
141     TSS2_RC r;
142     LOG_TRACE("context=%p, keyHandle=%"PRIx32 ", inPoint=%p",
143               esysContext, keyHandle, inPoint);
144     TSS2L_SYS_AUTH_COMMAND auths;
145     RSRC_NODE_T *keyHandleNode;
146 
147     /* Check context, sequence correctness and set state to error for now */
148     if (esysContext == NULL) {
149         LOG_ERROR("esyscontext is NULL.");
150         return TSS2_ESYS_RC_BAD_REFERENCE;
151     }
152     r = iesys_check_sequence_async(esysContext);
153     if (r != TSS2_RC_SUCCESS)
154         return r;
155     esysContext->state = _ESYS_STATE_INTERNALERROR;
156 
157     /* Check input parameters */
158     r = check_session_feasibility(shandle1, shandle2, shandle3, 1);
159     return_state_if_error(r, _ESYS_STATE_INIT, "Check session usage");
160 
161     /* Retrieve the metadata objects for provided handles */
162     r = esys_GetResourceObject(esysContext, keyHandle, &keyHandleNode);
163     return_state_if_error(r, _ESYS_STATE_INIT, "keyHandle unknown.");
164 
165     /* Initial invocation of SAPI to prepare the command buffer with parameters */
166     r = Tss2_Sys_ECDH_ZGen_Prepare(esysContext->sys,
167                                    (keyHandleNode == NULL) ? TPM2_RH_NULL
168                                     : keyHandleNode->rsrc.handle, inPoint);
169     return_state_if_error(r, _ESYS_STATE_INIT, "SAPI Prepare returned error.");
170 
171     /* Calculate the cpHash Values */
172     r = init_session_tab(esysContext, shandle1, shandle2, shandle3);
173     return_state_if_error(r, _ESYS_STATE_INIT, "Initialize session resources");
174     if (keyHandleNode != NULL)
175         iesys_compute_session_value(esysContext->session_tab[0],
176                 &keyHandleNode->rsrc.name, &keyHandleNode->auth);
177     else
178         iesys_compute_session_value(esysContext->session_tab[0], NULL, NULL);
179 
180     iesys_compute_session_value(esysContext->session_tab[1], NULL, NULL);
181     iesys_compute_session_value(esysContext->session_tab[2], NULL, NULL);
182 
183     /* Generate the auth values and set them in the SAPI command buffer */
184     r = iesys_gen_auths(esysContext, keyHandleNode, NULL, NULL, &auths);
185     return_state_if_error(r, _ESYS_STATE_INIT,
186                           "Error in computation of auth values");
187 
188     esysContext->authsCount = auths.count;
189     if (auths.count > 0) {
190         r = Tss2_Sys_SetCmdAuths(esysContext->sys, &auths);
191         return_state_if_error(r, _ESYS_STATE_INIT, "SAPI error on SetCmdAuths");
192     }
193 
194     /* Trigger execution and finish the async invocation */
195     r = Tss2_Sys_ExecuteAsync(esysContext->sys);
196     return_state_if_error(r, _ESYS_STATE_INTERNALERROR,
197                           "Finish (Execute Async)");
198 
199     esysContext->state = _ESYS_STATE_SENT;
200 
201     return r;
202 }
203 
204 /** Asynchronous finish function for TPM2_ECDH_ZGen
205  *
206  * This function returns the results of a TPM2_ECDH_ZGen command
207  * invoked via Esys_ECDH_ZGen_Finish. All non-simple output parameters
208  * are allocated by the function's implementation. NULL can be passed for every
209  * output parameter if the value is not required.
210  *
211  * @param[in,out] esysContext The ESYS_CONTEXT.
212  * @param[out] outPoint X and Y coordinates of the product of the
213  *             multiplication Z = (xZ , yZ) := [hdS]QB.
214  *             (callee-allocated)
215  * @retval TSS2_RC_SUCCESS on success
216  * @retval ESYS_RC_SUCCESS if the function call was a success.
217  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
218  *         pointers or required output handle references are NULL.
219  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
220  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
221  *         internal operations or return parameters.
222  * @retval TSS2_ESYS_RC_BAD_SEQUENCE: if the context has an asynchronous
223  *         operation already pending.
224  * @retval TSS2_ESYS_RC_TRY_AGAIN: if the timeout counter expires before the
225  *         TPM response is received.
226  * @retval TSS2_ESYS_RC_INSUFFICIENT_RESPONSE: if the TPM's response does not
227  *         at least contain the tag, response length, and response code.
228  * @retval TSS2_ESYS_RC_RSP_AUTH_FAILED: if the response HMAC from the TPM did
229  *         not verify.
230  * @retval TSS2_ESYS_RC_MALFORMED_RESPONSE: if the TPM's response is corrupted.
231  * @retval TSS2_RCs produced by lower layers of the software stack may be
232  *         returned to the caller unaltered unless handled internally.
233  */
234 TSS2_RC
Esys_ECDH_ZGen_Finish(ESYS_CONTEXT * esysContext,TPM2B_ECC_POINT ** outPoint)235 Esys_ECDH_ZGen_Finish(
236     ESYS_CONTEXT *esysContext,
237     TPM2B_ECC_POINT **outPoint)
238 {
239     TSS2_RC r;
240     LOG_TRACE("context=%p, outPoint=%p",
241               esysContext, outPoint);
242 
243     if (esysContext == NULL) {
244         LOG_ERROR("esyscontext is NULL.");
245         return TSS2_ESYS_RC_BAD_REFERENCE;
246     }
247 
248     /* Check for correct sequence and set sequence to irregular for now */
249     if (esysContext->state != _ESYS_STATE_SENT &&
250         esysContext->state != _ESYS_STATE_RESUBMISSION) {
251         LOG_ERROR("Esys called in bad sequence.");
252         return TSS2_ESYS_RC_BAD_SEQUENCE;
253     }
254     esysContext->state = _ESYS_STATE_INTERNALERROR;
255 
256     /* Allocate memory for response parameters */
257     if (outPoint != NULL) {
258         *outPoint = calloc(sizeof(TPM2B_ECC_POINT), 1);
259         if (*outPoint == NULL) {
260             return_error(TSS2_ESYS_RC_MEMORY, "Out of memory");
261         }
262     }
263 
264     /*Receive the TPM response and handle resubmissions if necessary. */
265     r = Tss2_Sys_ExecuteFinish(esysContext->sys, esysContext->timeout);
266     if ((r & ~TSS2_RC_LAYER_MASK) == TSS2_BASE_RC_TRY_AGAIN) {
267         LOG_DEBUG("A layer below returned TRY_AGAIN: %" PRIx32, r);
268         esysContext->state = _ESYS_STATE_SENT;
269         goto error_cleanup;
270     }
271     /* This block handle the resubmission of TPM commands given a certain set of
272      * TPM response codes. */
273     if (r == TPM2_RC_RETRY || r == TPM2_RC_TESTING || r == TPM2_RC_YIELDED) {
274         LOG_DEBUG("TPM returned RETRY, TESTING or YIELDED, which triggers a "
275             "resubmission: %" PRIx32, r);
276         if (esysContext->submissionCount++ >= _ESYS_MAX_SUBMISSIONS) {
277             LOG_WARNING("Maximum number of (re)submissions has been reached.");
278             esysContext->state = _ESYS_STATE_INIT;
279             goto error_cleanup;
280         }
281         esysContext->state = _ESYS_STATE_RESUBMISSION;
282         r = Tss2_Sys_ExecuteAsync(esysContext->sys);
283         if (r != TSS2_RC_SUCCESS) {
284             LOG_WARNING("Error attempting to resubmit");
285             /* We do not set esysContext->state here but inherit the most recent
286              * state of the _async function. */
287             goto error_cleanup;
288         }
289         r = TSS2_ESYS_RC_TRY_AGAIN;
290         LOG_DEBUG("Resubmission initiated and returning RC_TRY_AGAIN.");
291         goto error_cleanup;
292     }
293     /* The following is the "regular error" handling. */
294     if (iesys_tpm_error(r)) {
295         LOG_WARNING("Received TPM Error");
296         esysContext->state = _ESYS_STATE_INIT;
297         goto error_cleanup;
298     } else if (r != TSS2_RC_SUCCESS) {
299         LOG_ERROR("Received a non-TPM Error");
300         esysContext->state = _ESYS_STATE_INTERNALERROR;
301         goto error_cleanup;
302     }
303 
304     /*
305      * Now the verification of the response (hmac check) and if necessary the
306      * parameter decryption have to be done.
307      */
308     r = iesys_check_response(esysContext);
309     goto_state_if_error(r, _ESYS_STATE_INTERNALERROR, "Error: check response",
310                         error_cleanup);
311 
312     /*
313      * After the verification of the response we call the complete function
314      * to deliver the result.
315      */
316     r = Tss2_Sys_ECDH_ZGen_Complete(esysContext->sys,
317                                     (outPoint != NULL) ? *outPoint : NULL);
318     goto_state_if_error(r, _ESYS_STATE_INTERNALERROR,
319                         "Received error from SAPI unmarshaling" ,
320                         error_cleanup);
321 
322     esysContext->state = _ESYS_STATE_INIT;
323 
324     return TSS2_RC_SUCCESS;
325 
326 error_cleanup:
327     if (outPoint != NULL)
328         SAFE_FREE(*outPoint);
329 
330     return r;
331 }
332