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)23 static void store_input_parameters (
24     ESYS_CONTEXT *esysContext,
25     ESYS_TR nvIndex)
26 {
27     esysContext->in.NV.nvIndex = nvIndex;
28 }
29 
30 /** One-Call function for TPM2_NV_Extend
31  *
32  * This function invokes the TPM2_NV_Extend command in a one-call
33  * variant. This means the function will block until the TPM response is
34  * available. All input parameters are const. The memory for non-simple output
35  * parameters is allocated by the function implementation.
36  *
37  * @param[in,out] esysContext The ESYS_CONTEXT.
38  * @param[in]  authHandle Handle indicating the source of the authorization
39  *             value.
40  * @param[in]  nvIndex The NV Index to extend.
41  * @param[in]  shandle1 Session handle for authorization of authHandle
42  * @param[in]  shandle2 Second session handle.
43  * @param[in]  shandle3 Third session handle.
44  * @param[in]  data The data to extend.
45  * @retval TSS2_RC_SUCCESS if the function call was a success.
46  * @retval TSS2_ESYS_RC_BAD_REFERENCE if the esysContext or required input
47  *         pointers or required output handle references are NULL.
48  * @retval TSS2_ESYS_RC_BAD_CONTEXT: if esysContext corruption is detected.
49  * @retval TSS2_ESYS_RC_MEMORY: if the ESAPI cannot allocate enough memory for
50  *         internal operations or return parameters.
51  * @retval TSS2_ESYS_RC_BAD_SEQUENCE: if the context has an asynchronous
52  *         operation already pending.
53  * @retval TSS2_ESYS_RC_INSUFFICIENT_RESPONSE: if the TPM's response does not
54  *          at least contain the tag, response length, and response code.
55  * @retval TSS2_ESYS_RC_MALFORMED_RESPONSE: if the TPM's response is corrupted.
56  * @retval TSS2_ESYS_RC_RSP_AUTH_FAILED: if the response HMAC from the TPM
57            did not verify.
58  * @retval TSS2_ESYS_RC_MULTIPLE_DECRYPT_SESSIONS: if more than one session has
59  *         the 'decrypt' attribute bit set.
60  * @retval TSS2_ESYS_RC_MULTIPLE_ENCRYPT_SESSIONS: if more than one session has
61  *         the 'encrypt' attribute bit set.
62  * @retval TSS2_ESYS_RC_BAD_TR: if any of the ESYS_TR objects are unknown
63  *         to the ESYS_CONTEXT or are of the wrong type or if required
64  *         ESYS_TR objects are ESYS_TR_NONE.
65  * @retval TSS2_ESYS_RC_NO_ENCRYPT_PARAM: if one of the sessions has the
66  *         'encrypt' attribute set and the command does not support encryption
67  *          of the first response parameter.
68  * @retval TSS2_RCs produced by lower layers of the software stack may be
69  *         returned to the caller unaltered unless handled internally.
70  */
71 TSS2_RC
Esys_NV_Extend(ESYS_CONTEXT * esysContext,ESYS_TR authHandle,ESYS_TR nvIndex,ESYS_TR shandle1,ESYS_TR shandle2,ESYS_TR shandle3,const TPM2B_MAX_NV_BUFFER * data)72 Esys_NV_Extend(
73     ESYS_CONTEXT *esysContext,
74     ESYS_TR authHandle,
75     ESYS_TR nvIndex,
76     ESYS_TR shandle1,
77     ESYS_TR shandle2,
78     ESYS_TR shandle3,
79     const TPM2B_MAX_NV_BUFFER *data)
80 {
81     TSS2_RC r;
82 
83     r = Esys_NV_Extend_Async(esysContext, authHandle, nvIndex, shandle1,
84                              shandle2, shandle3, data);
85     return_if_error(r, "Error in async function");
86 
87     /* Set the timeout to indefinite for now, since we want _Finish to block */
88     int32_t timeouttmp = esysContext->timeout;
89     esysContext->timeout = -1;
90     /*
91      * Now we call the finish function, until return code is not equal to
92      * from TSS2_BASE_RC_TRY_AGAIN.
93      * Note that the finish function may return TSS2_RC_TRY_AGAIN, even if we
94      * have set the timeout to -1. This occurs for example if the TPM requests
95      * a retransmission of the command via TPM2_RC_YIELDED.
96      */
97     do {
98         r = Esys_NV_Extend_Finish(esysContext);
99         /* This is just debug information about the reattempt to finish the
100            command */
101         if (base_rc(r) == TSS2_BASE_RC_TRY_AGAIN)
102             LOG_DEBUG("A layer below returned TRY_AGAIN: %" PRIx32
103                       " => resubmitting command", r);
104     } while (base_rc(r) == TSS2_BASE_RC_TRY_AGAIN);
105 
106     /* Restore the timeout value to the original value */
107     esysContext->timeout = timeouttmp;
108     return_if_error(r, "Esys Finish");
109 
110     return TSS2_RC_SUCCESS;
111 }
112 
113 /** Asynchronous function for TPM2_NV_Extend
114  *
115  * This function invokes the TPM2_NV_Extend command in a asynchronous
116  * variant. This means the function will return as soon as the command has been
117  * sent downwards the stack to the TPM. All input parameters are const.
118  * In order to retrieve the TPM's response call Esys_NV_Extend_Finish.
119  *
120  * @param[in,out] esysContext The ESYS_CONTEXT.
121  * @param[in]  authHandle Handle indicating the source of the authorization
122  *             value.
123  * @param[in]  nvIndex The NV Index to extend.
124  * @param[in]  shandle1 Session handle for authorization of authHandle
125  * @param[in]  shandle2 Second session handle.
126  * @param[in]  shandle3 Third session handle.
127  * @param[in]  data The data to extend.
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_BAD_TR: if any of the ESYS_TR objects are unknown
141  *         to the ESYS_CONTEXT or are of the wrong type or if required
142  *         ESYS_TR objects are ESYS_TR_NONE.
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_NV_Extend_Async(ESYS_CONTEXT * esysContext,ESYS_TR authHandle,ESYS_TR nvIndex,ESYS_TR shandle1,ESYS_TR shandle2,ESYS_TR shandle3,const TPM2B_MAX_NV_BUFFER * data)148 Esys_NV_Extend_Async(
149     ESYS_CONTEXT *esysContext,
150     ESYS_TR authHandle,
151     ESYS_TR nvIndex,
152     ESYS_TR shandle1,
153     ESYS_TR shandle2,
154     ESYS_TR shandle3,
155     const TPM2B_MAX_NV_BUFFER *data)
156 {
157     TSS2_RC r;
158     LOG_TRACE("context=%p, authHandle=%"PRIx32 ", nvIndex=%"PRIx32 ","
159               "data=%p",
160               esysContext, authHandle, nvIndex, data);
161     TSS2L_SYS_AUTH_COMMAND auths;
162     RSRC_NODE_T *authHandleNode;
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);
179 
180     /* Retrieve the metadata objects for provided handles */
181     r = esys_GetResourceObject(esysContext, authHandle, &authHandleNode);
182     return_state_if_error(r, _ESYS_STATE_INIT, "authHandle unknown.");
183     r = esys_GetResourceObject(esysContext, nvIndex, &nvIndexNode);
184     return_state_if_error(r, _ESYS_STATE_INIT, "nvIndex unknown.");
185 
186     /* Initial invocation of SAPI to prepare the command buffer with parameters */
187     r = Tss2_Sys_NV_Extend_Prepare(esysContext->sys,
188                                    (authHandleNode == NULL) ? TPM2_RH_NULL
189                                     : authHandleNode->rsrc.handle,
190                                    (nvIndexNode == NULL) ? TPM2_RH_NULL
191                                     : nvIndexNode->rsrc.handle, data);
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, nvIndexNode, 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_NV_Extend
228  *
229  * This function returns the results of a TPM2_NV_Extend command
230  * invoked via Esys_NV_Extend_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_NV_Extend_Finish(ESYS_CONTEXT * esysContext)255 Esys_NV_Extend_Finish(
256     ESYS_CONTEXT *esysContext)
257 {
258     TSS2_RC r;
259     LOG_TRACE("context=%p",
260               esysContext);
261 
262     if (esysContext == NULL) {
263         LOG_ERROR("esyscontext is NULL.");
264         return TSS2_ESYS_RC_BAD_REFERENCE;
265     }
266 
267     /* Check for correct sequence and set sequence to irregular for now */
268     if (esysContext->state != _ESYS_STATE_SENT &&
269         esysContext->state != _ESYS_STATE_RESUBMISSION) {
270         LOG_ERROR("Esys called in bad sequence.");
271         return TSS2_ESYS_RC_BAD_SEQUENCE;
272     }
273     esysContext->state = _ESYS_STATE_INTERNALERROR;
274 
275     /*Receive the TPM response and handle resubmissions if necessary. */
276     r = Tss2_Sys_ExecuteFinish(esysContext->sys, esysContext->timeout);
277     if (base_rc(r) == TSS2_BASE_RC_TRY_AGAIN) {
278         LOG_DEBUG("A layer below returned TRY_AGAIN: %" PRIx32, r);
279         esysContext->state = _ESYS_STATE_SENT;
280         return r;
281     }
282     /* This block handle the resubmission of TPM commands given a certain set of
283      * TPM response codes. */
284     if (r == TPM2_RC_RETRY || r == TPM2_RC_TESTING || r == TPM2_RC_YIELDED) {
285         LOG_DEBUG("TPM returned RETRY, TESTING or YIELDED, which triggers a "
286             "resubmission: %" PRIx32, r);
287         if (esysContext->submissionCount++ >= _ESYS_MAX_SUBMISSIONS) {
288             LOG_WARNING("Maximum number of (re)submissions has been reached.");
289             esysContext->state = _ESYS_STATE_INIT;
290             return r;
291         }
292         esysContext->state = _ESYS_STATE_RESUBMISSION;
293         r = Tss2_Sys_ExecuteAsync(esysContext->sys);
294         if (r != TSS2_RC_SUCCESS) {
295             LOG_WARNING("Error attempting to resubmit");
296             /* We do not set esysContext->state here but inherit the most recent
297              * state of the _async function. */
298             return r;
299         }
300         r = TSS2_ESYS_RC_TRY_AGAIN;
301         LOG_DEBUG("Resubmission initiated and returning RC_TRY_AGAIN.");
302         return r;
303     }
304     /* The following is the "regular error" handling. */
305     if (iesys_tpm_error(r)) {
306         LOG_WARNING("Received TPM Error");
307         esysContext->state = _ESYS_STATE_INIT;
308         return r;
309     } else if (r != TSS2_RC_SUCCESS) {
310         LOG_ERROR("Received a non-TPM Error");
311         esysContext->state = _ESYS_STATE_INTERNALERROR;
312         return r;
313     }
314 
315     /*
316      * Now the verification of the response (hmac check) and if necessary the
317      * parameter decryption have to be done.
318      */
319     r = iesys_check_response(esysContext);
320     return_state_if_error(r, _ESYS_STATE_INTERNALERROR,
321                           "Error: check response");
322 
323     /*
324      * After the verification of the response we call the complete function
325      * to deliver the result.
326      */
327     r = Tss2_Sys_NV_Extend_Complete(esysContext->sys);
328     return_state_if_error(r, _ESYS_STATE_INTERNALERROR,
329                           "Received error from SAPI unmarshaling" );
330 
331     ESYS_TR nvIndex = esysContext->in.NV.nvIndex;
332     RSRC_NODE_T *nvIndexNode;
333     r = esys_GetResourceObject(esysContext, nvIndex, &nvIndexNode);
334     return_if_error(r, "get resource");
335 
336     /* Update name in meta data because of possibly changed attributes */
337     if (nvIndexNode != NULL) {
338         nvIndexNode->rsrc.misc.rsrc_nv_pub.nvPublic.attributes |= TPMA_NV_WRITTEN;
339         r = iesys_nv_get_name(&nvIndexNode->rsrc.misc.rsrc_nv_pub,
340                               &nvIndexNode->rsrc.name);
341         return_if_error(r, "Error get nvname")
342     }
343 
344     esysContext->state = _ESYS_STATE_INIT;
345 
346     return TSS2_RC_SUCCESS;
347 }
348