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