1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22#include "qemu/osdep.h"
23#include "tpm_util.h"
24#include "tpm_int.h"
25#include "exec/memory.h"
26
27
28
29
30void tpm_util_write_fatal_error_response(uint8_t *out, uint32_t out_len)
31{
32 if (out_len >= sizeof(struct tpm_resp_hdr)) {
33 struct tpm_resp_hdr *resp = (struct tpm_resp_hdr *)out;
34
35 resp->tag = cpu_to_be16(TPM_TAG_RSP_COMMAND);
36 resp->len = cpu_to_be32(sizeof(struct tpm_resp_hdr));
37 resp->errcode = cpu_to_be32(TPM_FAIL);
38 }
39}
40
41bool tpm_util_is_selftest(const uint8_t *in, uint32_t in_len)
42{
43 struct tpm_req_hdr *hdr = (struct tpm_req_hdr *)in;
44
45 if (in_len >= sizeof(*hdr)) {
46 return (be32_to_cpu(hdr->ordinal) == TPM_ORD_ContinueSelfTest);
47 }
48
49 return false;
50}
51
52
53
54
55
56static int tpm_util_test(int fd,
57 unsigned char *request,
58 size_t requestlen,
59 uint16_t *return_tag)
60{
61 struct tpm_resp_hdr *resp;
62 fd_set readfds;
63 int n;
64 struct timeval tv = {
65 .tv_sec = 1,
66 .tv_usec = 0,
67 };
68 unsigned char buf[1024];
69
70 n = write(fd, request, requestlen);
71 if (n < 0) {
72 return -errno;
73 }
74 if (n != requestlen) {
75 return -EFAULT;
76 }
77
78 FD_ZERO(&readfds);
79 FD_SET(fd, &readfds);
80
81
82 n = select(fd + 1, &readfds, NULL, NULL, &tv);
83 if (n != 1) {
84 return -errno;
85 }
86
87 n = read(fd, &buf, sizeof(buf));
88 if (n < sizeof(struct tpm_resp_hdr)) {
89 return -EFAULT;
90 }
91
92 resp = (struct tpm_resp_hdr *)buf;
93
94 if (be32_to_cpu(resp->len) != n) {
95 return -EMSGSIZE;
96 }
97
98 *return_tag = be16_to_cpu(resp->tag);
99
100 return 0;
101}
102
103
104
105
106
107int tpm_util_test_tpmdev(int tpm_fd, TPMVersion *tpm_version)
108{
109
110
111
112
113
114
115
116
117
118 const struct tpm_req_hdr test_req = {
119 .tag = cpu_to_be16(TPM_TAG_RQU_COMMAND),
120 .len = cpu_to_be32(sizeof(test_req)),
121 .ordinal = cpu_to_be32(TPM_ORD_GetTicks),
122 };
123
124 const struct tpm_req_hdr test_req_tpm2 = {
125 .tag = cpu_to_be16(TPM2_ST_NO_SESSIONS),
126 .len = cpu_to_be32(sizeof(test_req_tpm2)),
127 .ordinal = cpu_to_be32(TPM2_CC_ReadClock),
128 };
129 uint16_t return_tag;
130 int ret;
131
132
133 ret = tpm_util_test(tpm_fd, (unsigned char *)&test_req_tpm2,
134 sizeof(test_req_tpm2), &return_tag);
135
136 if (!ret && return_tag == TPM2_ST_NO_SESSIONS) {
137 *tpm_version = TPM_VERSION_2_0;
138 return 0;
139 }
140
141
142 ret = tpm_util_test(tpm_fd, (unsigned char *)&test_req,
143 sizeof(test_req), &return_tag);
144 if (!ret && return_tag == TPM_TAG_RSP_COMMAND) {
145 *tpm_version = TPM_VERSION_1_2;
146
147 return 0;
148 }
149
150 *tpm_version = TPM_VERSION_UNSPEC;
151
152 return 1;
153}
154