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