1 /********************************************************************************/
3 /* LibTPM interface functions */
4 /* Written by Stefan Berger */
5 /* IBM Thomas J. Watson Research Center */
6 /* $Id: tpm_library.c 4615 2011-08-30 15:35:24Z stefanb $ */
8 /* (c) Copyright IBM Corporation 2010. */
10 /* All rights reserved. */
12 /* Redistribution and use in source and binary forms, with or without */
13 /* modification, are permitted provided that the following conditions are */
16 /* Redistributions of source code must retain the above copyright notice, */
17 /* this list of conditions and the following disclaimer. */
19 /* Redistributions in binary form must reproduce the above copyright */
20 /* notice, this list of conditions and the following disclaimer in the */
21 /* documentation and/or other materials provided with the distribution. */
23 /* Neither the names of the IBM Corporation nor the names of its */
24 /* contributors may be used to endorse or promote products derived from */
25 /* this software without specific prior written permission. */
27 /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */
28 /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
29 /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR */
30 /* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT */
31 /* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, */
32 /* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */
33 /* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */
34 /* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY */
35 /* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
36 /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */
37 /* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
38 /********************************************************************************/
51 #ifdef USE_FREEBL_CRYPTO_LIBRARY
52 # include <plbase64.h>
55 #ifdef USE_OPENSSL_CRYPTO_LIBRARY
56 # include <openssl/bio.h>
57 # include <openssl/evp.h>
60 #include "tpm12/tpm_debug.h"
61 #include "tpm_error.h"
62 #include "tpm_library.h"
63 #include "tpm_library_intern.h"
64 #include "tpm_memory.h"
65 #include "tpm_nvfilename.h"
67 static const struct tags_and_indices
{
70 } tags_and_indices
[] = {
71 [TPMLIB_BLOB_TYPE_INITSTATE
] =
73 .starttag
= TPMLIB_INITSTATE_START_TAG
,
74 .endtag
= TPMLIB_INITSTATE_END_TAG
,
78 static const struct tpm_interface
*const tpm_iface
[] = {
86 static int debug_fd
= -1;
87 static unsigned debug_level
= 0;
88 static char *debug_prefix
= NULL
;
90 static struct sized_buffer cached_blobs
[TPMLIB_STATE_SAVE_STATE
+ 1];
92 static int tpmvers_choice
= 0; /* default is TPM1.2 */
93 static TPM_BOOL tpmvers_locked
= FALSE
;
95 uint32_t TPMLIB_GetVersion(void)
97 return TPM_LIBRARY_VERSION
;
100 TPM_RESULT
TPMLIB_ChooseTPMVersion(TPMLIB_TPMVersion ver
)
102 TPM_RESULT ret
= TPM_SUCCESS
;
104 /* TPMLIB_Terminate will reset previous choice */
109 case TPMLIB_TPM_VERSION_1_2
:
110 if (tpmvers_choice
!= 0)
111 ClearAllCachedState();
113 tpmvers_choice
= 0; // entry 0 in tpm_iface
115 case TPMLIB_TPM_VERSION_2
:
117 if (tpmvers_choice
!= 1)
118 ClearAllCachedState();
120 tpmvers_choice
= 1; // entry 1 in tpm_iface
130 TPM_RESULT
TPMLIB_MainInit(void)
132 tpmvers_locked
= TRUE
;
134 return tpm_iface
[tpmvers_choice
]->MainInit();
137 void TPMLIB_Terminate(void)
139 tpm_iface
[tpmvers_choice
]->Terminate();
141 tpmvers_locked
= FALSE
;
145 * Send a command to the TPM. The command buffer must hold a well formatted
146 * TPM command and the command_size indicate the size of the command.
147 * The respbuffer parameter may be provided by the user and grow if
148 * the respbufsize size indicator is determined to be too small for the
149 * response. In that case a new buffer will be allocated and the size of that
150 * buffer returned in the respbufsize parameter. resp_size describes the
151 * size of the actual response within the respbuffer.
153 TPM_RESULT
TPMLIB_Process(unsigned char **respbuffer
, uint32_t *resp_size
,
154 uint32_t *respbufsize
,
155 unsigned char *command
, uint32_t command_size
)
157 return tpm_iface
[tpmvers_choice
]->Process(respbuffer
,
158 resp_size
, respbufsize
,
159 command
, command_size
);
163 * Get the volatile state from the TPM. This function will return the
164 * buffer and the length of the buffer to the caller in case everything
167 TPM_RESULT
TPMLIB_VolatileAll_Store(unsigned char **buffer
,
170 return tpm_iface
[tpmvers_choice
]->VolatileAllStore(buffer
, buflen
);
174 * Have the TPM cancel an ongoing command
176 TPM_RESULT
TPMLIB_CancelCommand(void)
178 return tpm_iface
[tpmvers_choice
]->CancelCommand();
182 * Get a property of the TPM. The functions currently only
183 * return compile-time #defines but this may change in future
184 * versions where we may return parameters with which the TPM
185 * was created (rather than compiled).
187 TPM_RESULT
TPMLIB_GetTPMProperty(enum TPMLIB_TPMProperty prop
,
191 case TPMPROP_TPM_BUFFER_MAX
:
192 *result
= TPM_BUFFER_MAX
;
196 return tpm_iface
[tpmvers_choice
]->GetTPMProperty(prop
, result
);
202 char *TPMLIB_GetInfo(enum TPMLIB_InfoFlags flags
)
204 return tpm_iface
[tpmvers_choice
]->GetInfo(flags
);
207 TPM_RESULT
TPMLIB_SetState(enum TPMLIB_StateType st
,
208 const unsigned char *buffer
, uint32_t buflen
)
210 return tpm_iface
[0]->SetState(st
, buffer
, buflen
);
213 TPM_RESULT
TPMLIB_GetState(enum TPMLIB_StateType st
,
214 unsigned char **buffer
, uint32_t *buflen
)
216 return tpm_iface
[0]->GetState(st
, buffer
, buflen
);
219 TPM_RESULT
TPM_IO_Hash_Start(void)
221 return tpm_iface
[tpmvers_choice
]->HashStart();
224 TPM_RESULT
TPM_IO_Hash_Data(const unsigned char *data
, uint32_t data_length
)
226 return tpm_iface
[tpmvers_choice
]->HashData(data
, data_length
);
229 TPM_RESULT
TPM_IO_Hash_End(void)
231 return tpm_iface
[tpmvers_choice
]->HashEnd();
234 TPM_RESULT
TPM_IO_TpmEstablished_Get(TPM_BOOL
*tpmEstablished
)
236 return tpm_iface
[tpmvers_choice
]->TpmEstablishedGet(tpmEstablished
);
239 TPM_RESULT
TPM_IO_TpmEstablished_Reset(void)
241 return tpm_iface
[tpmvers_choice
]->TpmEstablishedReset();
244 uint32_t TPMLIB_SetBufferSize(uint32_t wanted_size
,
248 return tpm_iface
[tpmvers_choice
]->SetBufferSize(wanted_size
,
253 TPM_RESULT
TPMLIB_ValidateState(enum TPMLIB_StateType st
,
256 return tpm_iface
[tpmvers_choice
]->ValidateState(st
, flags
);
259 static struct libtpms_callbacks libtpms_cbs
;
261 struct libtpms_callbacks
*TPMLIB_GetCallbacks(void)
266 TPM_RESULT
TPMLIB_RegisterCallbacks(struct libtpms_callbacks
*callbacks
)
268 int max_size
= sizeof(struct libtpms_callbacks
);
270 /* restrict the size of the structure to what we know currently
271 future versions may know more callbacks */
272 if (callbacks
->sizeOfStruct
< max_size
)
273 max_size
= callbacks
->sizeOfStruct
;
275 /* clear the internal callback structure and copy the user provided
277 memset(&libtpms_cbs
, 0x0, sizeof(libtpms_cbs
));
278 memcpy(&libtpms_cbs
, callbacks
, max_size
);
283 static int is_base64ltr(char c
)
285 return ((c
>= 'A' && c
<= 'Z') ||
286 (c
>= 'a' && c
<= 'z') ||
287 (c
>= '0' && c
<= '9') ||
293 #ifdef USE_OPENSSL_CRYPTO_LIBRARY
294 static unsigned char *TPMLIB_OpenSSL_Base64Decode(char *input
,
295 unsigned int outputlen
)
298 unsigned char *res
= NULL
;
301 b64
= BIO_new(BIO_f_base64());
306 bmem
= BIO_new_mem_buf(input
, strlen(input
));
311 bmem
= BIO_push(b64
, bmem
);
312 BIO_set_flags(bmem
, BIO_FLAGS_BASE64_NO_NL
);
314 res
= malloc(outputlen
);
316 TPMLIB_LogError("Could not allocate %u bytes.\n", outputlen
);
320 n
= BIO_read(bmem
, res
, outputlen
);
335 * Base64 decode the string starting at 'start' and the last
336 * valid character may be a 'end'. The length of the decoded string
337 * is returned in *length.
339 static unsigned char *TPMLIB_Base64Decode(const char *start
, const char *end
,
342 unsigned char *ret
= NULL
;
343 char *input
= NULL
, *d
;
346 unsigned int numbase64chars
= 0;
351 while (end
> start
&& !is_base64ltr(*end
))
356 input
= malloc(end
- start
+ 1);
358 TPMLIB_LogError("Could not allocate %u bytes.\n",
359 (unsigned int)(end
- start
+ 1));
363 /* copy from source string skipping '\n' and '\r' and using
364 '=' to calculate the exact length */
370 if (is_base64ltr(c
)) {
383 *length
= (numbase64chars
/ 4) * 3;
384 switch (numbase64chars
% 4) {
387 *length
+= (numbase64chars
% 4) - 1;
392 fprintf(stderr
,"malformed base64\n");
397 #ifdef USE_FREEBL_CRYPTO_LIBRARY
398 ret
= (unsigned char *)PL_Base64Decode(input
, 0, NULL
);
401 #ifdef USE_OPENSSL_CRYPTO_LIBRARY
402 ret
= TPMLIB_OpenSSL_Base64Decode(input
, *length
);
411 static unsigned char *TPMLIB_GetPlaintext(const char *stream
,
412 const char *starttag
,
417 unsigned char *plaintext
= NULL
;
419 start
= strstr(stream
, starttag
);
421 start
+= strlen(starttag
);
422 while (isspace((int)*start
))
424 end
= strstr(start
, endtag
);
426 plaintext
= TPMLIB_Base64Decode(start
, --end
, length
);
432 TPM_RESULT
TPMLIB_DecodeBlob(const char *buffer
, enum TPMLIB_BlobType type
,
433 unsigned char **result
, size_t *result_len
)
435 TPM_RESULT res
= TPM_SUCCESS
;
437 *result
= TPMLIB_GetPlaintext(buffer
,
438 tags_and_indices
[type
].starttag
,
439 tags_and_indices
[type
].endtag
,
442 if (*result
== NULL
) {
449 void TPMLIB_SetDebugFD(int fd
)
454 void TPMLIB_SetDebugLevel(unsigned level
)
459 TPM_RESULT
TPMLIB_SetDebugPrefix(const char *prefix
)
464 debug_prefix
= strdup(prefix
);
474 int TPMLIB_LogPrintf(const char *format
, ...)
476 unsigned level
= debug_level
, i
;
481 if (!debug_fd
|| !debug_level
)
484 va_start(args
, format
);
485 n
= vsnprintf(buffer
, sizeof(buffer
), format
, args
);
488 if (n
< 0 || n
>= (int)sizeof(buffer
))
497 if (buffer
[i
] != ' ')
505 dprintf(debug_fd
, "%s", debug_prefix
);
506 dprintf(debug_fd
, "%s", buffer
);
512 * TPMLIB_LogPrintfA: Printf to the logfd without indentation check
514 * @indent: how many spaces to indent; indent of ~0 forces logging
515 * with indent 0 even if not debug_level is set
516 * @format: format to use for formatting the following parameters
519 void TPMLIB_LogPrintfA(unsigned int indent
, const char *format
, ...)
525 if (indent
!= (unsigned int)~0) {
526 if (!debug_fd
|| !debug_level
)
531 fd
= (debug_fd
>= 0) ? debug_fd
: STDERR_FILENO
;
535 if (indent
> sizeof(spaces
) - 1)
536 indent
= sizeof(spaces
) - 1;
537 memset(spaces
, ' ', indent
);
539 dprintf(fd
, "%s", spaces
);
542 va_start(args
, format
);
543 vdprintf(fd
, format
, args
);
547 void ClearCachedState(enum TPMLIB_StateType st
)
549 free(cached_blobs
[st
].buffer
);
550 cached_blobs
[st
].buffer
= NULL
;
551 cached_blobs
[st
].buflen
= 0;
554 void ClearAllCachedState(void)
556 ClearCachedState(TPMLIB_STATE_VOLATILE
);
557 ClearCachedState(TPMLIB_STATE_PERMANENT
);
558 ClearCachedState(TPMLIB_STATE_SAVE_STATE
);
562 * Set buffer for cached state; we allow setting an empty cached state
563 * by the caller passing a NULL pointer for the buffer.
565 void SetCachedState(enum TPMLIB_StateType st
,
566 unsigned char *buffer
, uint32_t buflen
)
568 free(cached_blobs
[st
].buffer
);
569 cached_blobs
[st
].buffer
= buffer
;
570 cached_blobs
[st
].buflen
= buffer
? buflen
: BUFLEN_EMPTY_BUFFER
;
573 void GetCachedState(enum TPMLIB_StateType st
,
574 unsigned char **buffer
, uint32_t *buflen
,
575 bool *is_empty_buffer
)
577 /* caller owns blob now */
578 *buffer
= cached_blobs
[st
].buffer
;
579 *buflen
= cached_blobs
[st
].buflen
;
580 *is_empty_buffer
= (*buflen
== BUFLEN_EMPTY_BUFFER
);
581 cached_blobs
[st
].buffer
= NULL
;
582 cached_blobs
[st
].buflen
= 0;
585 bool HasCachedState(enum TPMLIB_StateType st
)
587 return (cached_blobs
[st
].buffer
!= NULL
|| cached_blobs
[st
].buflen
!= 0);
590 TPM_RESULT
CopyCachedState(enum TPMLIB_StateType st
,
591 unsigned char **buffer
, uint32_t *buflen
,
592 bool *is_empty_buffer
)
594 TPM_RESULT ret
= TPM_SUCCESS
;
596 /* buflen may indicate an empty buffer */
597 *buflen
= cached_blobs
[st
].buflen
;
598 *is_empty_buffer
= (*buflen
== BUFLEN_EMPTY_BUFFER
);
600 if (cached_blobs
[st
].buffer
) {
601 *buffer
= malloc(*buflen
);
603 TPMLIB_LogError("Could not allocate %u bytes.\n", *buflen
);
606 memcpy(*buffer
, cached_blobs
[st
].buffer
, *buflen
);
615 const char *TPMLIB_StateTypeToName(enum TPMLIB_StateType st
)
618 case TPMLIB_STATE_PERMANENT
:
619 return TPM_PERMANENT_ALL_NAME
;
620 case TPMLIB_STATE_VOLATILE
:
621 return TPM_VOLATILESTATE_NAME
;
622 case TPMLIB_STATE_SAVE_STATE
:
623 return TPM_SAVESTATE_NAME
;
628 enum TPMLIB_StateType
TPMLIB_NameToStateType(const char *name
)
632 if (!strcmp(name
, TPM_PERMANENT_ALL_NAME
))
633 return TPMLIB_STATE_PERMANENT
;
634 if (!strcmp(name
, TPM_VOLATILESTATE_NAME
))
635 return TPMLIB_STATE_VOLATILE
;
636 if (!strcmp(name
, TPM_SAVESTATE_NAME
))
637 return TPMLIB_STATE_SAVE_STATE
;