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