2 * TPM utility functions
4 * Copyright (c) 2010 - 2015 IBM Corporation
6 * Stefan Berger <stefanb@us.ibm.com>
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, see <http://www.gnu.org/licenses/>
22 #include "qemu/osdep.h"
27 * A basic test of a TPM device. We expect a well formatted response header
28 * (error response is fine) within one second.
30 static int tpm_util_test(int fd
,
31 unsigned char *request
,
35 struct tpm_resp_hdr
*resp
;
42 unsigned char buf
[1024];
44 n
= write(fd
, request
, requestlen
);
48 if (n
!= requestlen
) {
55 /* wait for a second */
56 n
= select(fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
61 n
= read(fd
, &buf
, sizeof(buf
));
62 if (n
< sizeof(struct tpm_resp_hdr
)) {
66 resp
= (struct tpm_resp_hdr
*)buf
;
67 /* check the header */
68 if (be32_to_cpu(resp
->len
) != n
) {
72 *return_tag
= be16_to_cpu(resp
->tag
);
78 * Probe for the TPM device in the back
79 * Returns 0 on success with the version of the probed TPM set, 1 on failure.
81 int tpm_util_test_tpmdev(int tpm_fd
, TPMVersion
*tpm_version
)
84 * Sending a TPM1.2 command to a TPM2 should return a TPM1.2
85 * header (tag = 0xc4) and error code (TPM_BADTAG = 0x1e)
87 * Sending a TPM2 command to a TPM 2 will give a TPM 2 tag in the
89 * Sending a TPM2 command to a TPM 1.2 will give a TPM 1.2 tag
90 * in the header and an error code.
92 const struct tpm_req_hdr test_req
= {
93 .tag
= cpu_to_be16(TPM_TAG_RQU_COMMAND
),
94 .len
= cpu_to_be32(sizeof(test_req
)),
95 .ordinal
= cpu_to_be32(TPM_ORD_GetTicks
),
98 const struct tpm_req_hdr test_req_tpm2
= {
99 .tag
= cpu_to_be16(TPM2_ST_NO_SESSIONS
),
100 .len
= cpu_to_be32(sizeof(test_req_tpm2
)),
101 .ordinal
= cpu_to_be32(TPM2_CC_ReadClock
),
106 /* Send TPM 2 command */
107 ret
= tpm_util_test(tpm_fd
, (unsigned char *)&test_req_tpm2
,
108 sizeof(test_req_tpm2
), &return_tag
);
109 /* TPM 2 would respond with a tag of TPM2_ST_NO_SESSIONS */
110 if (!ret
&& return_tag
== TPM2_ST_NO_SESSIONS
) {
111 *tpm_version
= TPM_VERSION_2_0
;
115 /* Send TPM 1.2 command */
116 ret
= tpm_util_test(tpm_fd
, (unsigned char *)&test_req
,
117 sizeof(test_req
), &return_tag
);
118 if (!ret
&& return_tag
== TPM_TAG_RSP_COMMAND
) {
119 *tpm_version
= TPM_VERSION_1_2
;
120 /* this is a TPM 1.2 */
124 *tpm_version
= TPM_VERSION_UNSPEC
;