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