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