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