master
c 1,122 lines 33.4 KB
Raw
1 /*
2 * Emulator TPM driver
3 *
4 * Copyright (c) 2017 Intel Corporation
5 * Author: Amarnath Valluri <amarnath.valluri@intel.com>
6 *
7 * Copyright (c) 2010 - 2013, 2018 IBM Corporation
8 * Authors:
9 * Stefan Berger <stefanb@us.ibm.com>
10 *
11 * Copyright (C) 2011 IAIK, Graz University of Technology
12 * Author: Andreas Niederl
13 *
14 * This library is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Lesser General Public
16 * License as published by the Free Software Foundation; either
17 * version 2.1 of the License, or (at your option) any later version.
18 *
19 * This library is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * Lesser General Public License for more details.
23 *
24 * You should have received a copy of the GNU Lesser General Public
25 * License along with this library; if not, see <http://www.gnu.org/licenses/>
26 *
27 */
28
29 #include "qemu/osdep.h"
30 #include "qemu/error-report.h"
31 #include "qemu/module.h"
32 #include "qemu/sockets.h"
33 #include "qemu/lockable.h"
34 #include "io/channel-socket.h"
35 #include "system/runstate.h"
36 #include "system/tpm_backend.h"
37 #include "system/tpm_util.h"
38 #include "tpm_int.h"
39 #include "tpm_ioctl.h"
40 #include "migration/blocker.h"
41 #include "migration/vmstate.h"
42 #include "qapi/error.h"
43 #include "qapi/clone-visitor.h"
44 #include "qapi/qapi-visit-tpm.h"
45 #include "chardev/char-fe.h"
46 #include "trace.h"
47 #include "qom/object.h"
48
49 #define TYPE_TPM_EMULATOR "tpm-emulator"
50 OBJECT_DECLARE_SIMPLE_TYPE(TPMEmulator, TPM_EMULATOR)
51
52 #define TPM_EMULATOR_IMPLEMENTS_ALL_CAPS(S, cap) (((S)->caps & (cap)) == (cap))
53
54 /* data structures */
55
56 /* blobs from the TPM; part of VM state when migrating */
57 typedef struct TPMBlobBuffers {
58 uint32_t permanent_flags;
59 TPMSizedBuffer permanent;
60
61 uint32_t volatil_flags;
62 TPMSizedBuffer volatil;
63
64 uint32_t savestate_flags;
65 TPMSizedBuffer savestate;
66 } TPMBlobBuffers;
67
68 struct TPMEmulator {
69 TPMBackend parent;
70
71 TPMEmulatorOptions *options;
72 CharFrontend ctrl_chr;
73 QIOChannel *data_ioc;
74 TPMVersion tpm_version;
75 uint32_t caps; /* capabilities of the TPM */
76 uint8_t cur_locty_number; /* last set locality */
77 Error *migration_blocker;
78
79 QemuMutex mutex;
80
81 unsigned int established_flag:1;
82 unsigned int established_flag_cached:1;
83
84 TPMBlobBuffers state_blobs;
85
86 bool relock_storage;
87 VMChangeStateEntry *vmstate;
88 };
89
90 struct tpm_error {
91 uint32_t tpm_result;
92 const char *string;
93 };
94
95 static const struct tpm_error tpm_errors[] = {
96 /* TPM 1.2 error codes */
97 { TPM_BAD_PARAMETER , "a parameter is bad" },
98 { TPM_FAIL , "operation failed" },
99 { TPM_KEYNOTFOUND , "key could not be found" },
100 { TPM_BAD_PARAM_SIZE , "bad parameter size"},
101 { TPM_ENCRYPT_ERROR , "encryption error" },
102 { TPM_DECRYPT_ERROR , "decryption error" },
103 { TPM_BAD_KEY_PROPERTY, "bad key property" },
104 { TPM_BAD_MODE , "bad (encryption) mode" },
105 { TPM_BAD_VERSION , "bad version identifier" },
106 { TPM_BAD_LOCALITY , "bad locality" },
107 /* TPM 2 error codes */
108 { TPM_RC_FAILURE , "operation failed" },
109 { TPM_RC_LOCALITY , "bad locality" },
110 { TPM_RC_INSUFFICIENT, "insufficient amount of data" },
111 };
112
113 static const char *tpm_emulator_strerror(uint32_t tpm_result)
114 {
115 size_t i;
116
117 for (i = 0; i < ARRAY_SIZE(tpm_errors); i++) {
118 if (tpm_errors[i].tpm_result == tpm_result) {
119 return tpm_errors[i].string;
120 }
121 }
122 return "";
123 }
124
125 static int tpm_emulator_ctrlcmd(TPMEmulator *tpm, unsigned long cmd, void *msg,
126 size_t msg_len_in, size_t msg_len_out_err,
127 size_t msg_len_out_total)
128 {
129 CharFrontend *dev = &tpm->ctrl_chr;
130 uint32_t cmd_no = cpu_to_be32(cmd);
131 ssize_t n = sizeof(uint32_t) + msg_len_in;
132 ptm_res res;
133
134 WITH_QEMU_LOCK_GUARD(&tpm->mutex) {
135 g_autofree uint8_t *buf = g_malloc(n);
136
137 memcpy(buf, &cmd_no, sizeof(cmd_no));
138 memcpy(buf + sizeof(cmd_no), msg, msg_len_in);
139
140 n = qemu_chr_fe_write_all(dev, buf, n);
141 if (n <= 0) {
142 return -1;
143 }
144
145 if (msg_len_out_total > 0) {
146 assert(msg_len_out_total >= msg_len_out_err);
147
148 n = qemu_chr_fe_read_all(dev, (uint8_t *)msg, msg_len_out_err);
149 if (n <= 0) {
150 return -1;
151 }
152 if (msg_len_out_err == msg_len_out_total) {
153 return 0;
154 }
155 /* result error code is always in the first 4 bytes */
156 assert(sizeof(res) <= msg_len_out_err);
157 memcpy(&res, msg, sizeof(res));
158 if (res) {
159 return 0;
160 }
161
162 n = qemu_chr_fe_read_all(dev, (uint8_t *)msg + msg_len_out_err,
163 msg_len_out_total - msg_len_out_err);
164 if (n <= 0) {
165 return -1;
166 }
167 }
168 }
169
170 return 0;
171 }
172
173 static int tpm_emulator_unix_tx_bufs(TPMEmulator *tpm_emu,
174 const uint8_t *in, uint32_t in_len,
175 uint8_t *out, uint32_t out_len,
176 bool *selftest_done,
177 Error **errp)
178 {
179 bool is_selftest = false;
180 Error *local_err = NULL;
181 uint32_t to_read;
182 ssize_t ret;
183
184 if (selftest_done) {
185 *selftest_done = false;
186 is_selftest = tpm_util_is_selftest(in, in_len);
187 }
188
189 ret = qio_channel_write_all(tpm_emu->data_ioc, (char *)in, in_len, errp);
190 if (ret != 0) {
191 return -1;
192 }
193
194 ret = qio_channel_read_all(tpm_emu->data_ioc, (char *)out,
195 sizeof(struct tpm_resp_hdr), errp);
196 if (ret != 0) {
197 return -1;
198 }
199
200 /*
201 * Size of response from emulator must be <= out_len (= negotiated buffer
202 * size)
203 */
204 to_read = tpm_cmd_get_size(out);
205 if (to_read > out_len) {
206 if (qio_channel_shutdown(tpm_emu->data_ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
207 &local_err) < 0) {
208 error_report_err(local_err);
209 }
210 error_setg(errp, "tpm-emulator: Disconnected after receiving "
211 "unacceptable large response (%u > %u)",
212 to_read, out_len);
213 return -1;
214 }
215
216 ret = qio_channel_read_all(tpm_emu->data_ioc,
217 (char *)out + sizeof(struct tpm_resp_hdr),
218 to_read - sizeof(struct tpm_resp_hdr), errp);
219 if (ret != 0) {
220 return -1;
221 }
222
223 if (is_selftest) {
224 *selftest_done = tpm_cmd_get_errcode(out) == 0;
225 }
226
227 return 0;
228 }
229
230 static int tpm_emulator_set_locality(TPMEmulator *tpm_emu, uint8_t locty_number,
231 Error **errp)
232 {
233 ptm_loc loc;
234
235 if (tpm_emu->cur_locty_number == locty_number) {
236 return 0;
237 }
238
239 trace_tpm_emulator_set_locality(locty_number);
240
241 memset(&loc, 0, sizeof(loc));
242 loc.u.req.loc = locty_number;
243 if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_LOCALITY, &loc,
244 sizeof(loc), sizeof(loc.u.resp.tpm_result),
245 sizeof(loc)) < 0) {
246 error_setg(errp, "tpm-emulator: could not set locality");
247 return -1;
248 }
249
250 loc.u.resp.tpm_result = be32_to_cpu(loc.u.resp.tpm_result);
251 if (loc.u.resp.tpm_result != 0) {
252 error_setg(errp, "tpm-emulator: TPM result for set locality : 0x%x",
253 loc.u.resp.tpm_result);
254 return -1;
255 }
256
257 tpm_emu->cur_locty_number = locty_number;
258
259 return 0;
260 }
261
262 static void tpm_emulator_handle_request(TPMBackend *tb, TPMBackendCmd *cmd,
263 Error **errp)
264 {
265 TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
266
267 trace_tpm_emulator_handle_request();
268
269 if (tpm_emulator_set_locality(tpm_emu, cmd->locty, errp) < 0 ||
270 tpm_emulator_unix_tx_bufs(tpm_emu, cmd->in, cmd->in_len,
271 cmd->out, cmd->out_len,
272 &cmd->selftest_done, errp) < 0) {
273 tpm_util_write_fatal_error_response(cmd->out, cmd->out_len);
274 }
275 }
276
277 static int tpm_emulator_probe_caps(TPMEmulator *tpm_emu)
278 {
279 ptm_cap_n cap_n;
280
281 if (tpm_emulator_ctrlcmd(tpm_emu, CMD_GET_CAPABILITY, &cap_n, 0,
282 sizeof(cap_n.u.resp.tpm_result),
283 sizeof(cap_n)) < 0) {
284 error_report("tpm-emulator: probing failed");
285 return -1;
286 }
287
288 tpm_emu->caps = be32_to_cpu(cap_n.u.resp.caps);
289
290 trace_tpm_emulator_probe_caps(tpm_emu->caps);
291
292 return 0;
293 }
294
295 static int tpm_emulator_check_caps(TPMEmulator *tpm_emu)
296 {
297 uint32_t caps = 0;
298 const char *tpm = NULL;
299
300 /* check for min. required capabilities */
301 switch (tpm_emu->tpm_version) {
302 case TPM_VERSION_1_2:
303 caps = PTM_CAP_INIT | PTM_CAP_SHUTDOWN | PTM_CAP_GET_TPMESTABLISHED |
304 PTM_CAP_SET_LOCALITY | PTM_CAP_SET_DATAFD | PTM_CAP_STOP |
305 PTM_CAP_SET_BUFFERSIZE;
306 tpm = "1.2";
307 break;
308 case TPM_VERSION_2_0:
309 caps = PTM_CAP_INIT | PTM_CAP_SHUTDOWN | PTM_CAP_GET_TPMESTABLISHED |
310 PTM_CAP_SET_LOCALITY | PTM_CAP_RESET_TPMESTABLISHED |
311 PTM_CAP_SET_DATAFD | PTM_CAP_STOP | PTM_CAP_SET_BUFFERSIZE;
312 tpm = "2";
313 break;
314 case TPM_VERSION_UNSPEC:
315 error_report("tpm-emulator: TPM version has not been set");
316 return -1;
317 }
318
319 if (!TPM_EMULATOR_IMPLEMENTS_ALL_CAPS(tpm_emu, caps)) {
320 error_report("tpm-emulator: TPM does not implement minimum set of "
321 "required capabilities for TPM %s (0x%x)", tpm, (int)caps);
322 return -1;
323 }
324
325 return 0;
326 }
327
328 static int tpm_emulator_stop_tpm(TPMBackend *tb, Error **errp)
329 {
330 TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
331 ptm_res res;
332
333 if (tpm_emulator_ctrlcmd(tpm_emu, CMD_STOP, &res, 0,
334 sizeof(ptm_res), sizeof(res)) < 0) {
335 error_setg(errp, "tpm-emulator: Could not stop TPM");
336 return -1;
337 }
338
339 res = be32_to_cpu(res);
340 if (res) {
341 error_setg(errp, "tpm-emulator: TPM result for CMD_STOP: 0x%x %s", res,
342 tpm_emulator_strerror(res));
343 return -1;
344 }
345
346 return 0;
347 }
348
349 static int tpm_emulator_lock_storage(TPMEmulator *tpm_emu)
350 {
351 ptm_lockstorage pls;
352
353 if (!TPM_EMULATOR_IMPLEMENTS_ALL_CAPS(tpm_emu, PTM_CAP_LOCK_STORAGE)) {
354 trace_tpm_emulator_lock_storage_cmd_not_supt();
355 return 0;
356 }
357
358 /* give failing side 300 * 10ms time to release lock */
359 pls.u.req.retries = cpu_to_be32(300);
360 if (tpm_emulator_ctrlcmd(tpm_emu, CMD_LOCK_STORAGE, &pls, sizeof(pls.u.req),
361 sizeof(pls.u.resp.tpm_result),
362 sizeof(pls.u.resp)) < 0) {
363 error_report("tpm-emulator: Could not lock storage within 3 seconds");
364 return -1;
365 }
366
367 pls.u.resp.tpm_result = be32_to_cpu(pls.u.resp.tpm_result);
368 if (pls.u.resp.tpm_result != 0) {
369 error_report("tpm-emulator: TPM result for CMD_LOCK_STORAGE: 0x%x %s",
370 pls.u.resp.tpm_result,
371 tpm_emulator_strerror(pls.u.resp.tpm_result));
372 return -1;
373 }
374
375 return 0;
376 }
377
378 static int tpm_emulator_set_buffer_size(TPMBackend *tb,
379 size_t wanted_size,
380 size_t *actual_size,
381 Error **errp)
382 {
383 TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
384 ptm_setbuffersize psbs;
385 size_t tpm_buffersize;
386
387 if (tpm_emulator_stop_tpm(tb, errp) < 0) {
388 return -1;
389 }
390
391 psbs.u.req.buffersize = cpu_to_be32(wanted_size);
392
393 if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_BUFFERSIZE, &psbs,
394 sizeof(psbs.u.req), sizeof(psbs.u.resp.tpm_result),
395 sizeof(psbs.u.resp)) < 0) {
396 error_setg(errp, "tpm-emulator: Could not set buffer size");
397 return -1;
398 }
399
400 psbs.u.resp.tpm_result = be32_to_cpu(psbs.u.resp.tpm_result);
401 if (psbs.u.resp.tpm_result != 0) {
402 error_setg(errp,
403 "tpm-emulator: TPM result for set buffer size : 0x%x %s",
404 psbs.u.resp.tpm_result,
405 tpm_emulator_strerror(psbs.u.resp.tpm_result));
406 return -1;
407 }
408
409 tpm_buffersize = be32_to_cpu(psbs.u.resp.buffersize);
410 /* Reject different buffer size used by the TPM than what was requested. */
411 if (wanted_size != 0 && wanted_size != tpm_buffersize) {
412 error_setg(errp,
413 "tpm-emulator: TPM did not accept the requested buffer size "
414 "of %zu bytes but adjusted it to %zu bytes",
415 wanted_size, tpm_buffersize);
416 return -1;
417 }
418
419 if (actual_size) {
420 *actual_size = tpm_buffersize;
421 }
422
423 trace_tpm_emulator_set_buffer_size(
424 be32_to_cpu(psbs.u.resp.buffersize),
425 be32_to_cpu(psbs.u.resp.minsize),
426 be32_to_cpu(psbs.u.resp.maxsize));
427
428 return 0;
429 }
430
431 static int tpm_emulator_startup_tpm_resume(TPMBackend *tb, size_t buffersize,
432 bool is_resume, Error **errp)
433 {
434 TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
435 ptm_init init = {
436 .u.req.init_flags = 0,
437 };
438 ptm_res res;
439
440 trace_tpm_emulator_startup_tpm_resume(is_resume, buffersize);
441
442 if (buffersize != 0 &&
443 tpm_emulator_set_buffer_size(tb, buffersize, NULL, errp) < 0) {
444 goto err_exit;
445 }
446
447 if (is_resume) {
448 init.u.req.init_flags |= cpu_to_be32(PTM_INIT_FLAG_DELETE_VOLATILE);
449 }
450
451 if (tpm_emulator_ctrlcmd(tpm_emu, CMD_INIT, &init, sizeof(init),
452 sizeof(init.u.resp.tpm_result),
453 sizeof(init)) < 0) {
454 error_setg(errp, "tpm-emulator: could not send INIT");
455 goto err_exit;
456 }
457
458 res = be32_to_cpu(init.u.resp.tpm_result);
459 if (res) {
460 error_setg(errp, "tpm-emulator: TPM result for CMD_INIT: 0x%x %s", res,
461 tpm_emulator_strerror(res));
462 goto err_exit;
463 }
464 return 0;
465
466 err_exit:
467 return -1;
468 }
469
470 static int do_tpm_emulator_startup_tpm(TPMBackend *tb, size_t buffersize,
471 Error **errp)
472 {
473 /* TPM startup will be done from post_load hook */
474 if (runstate_check(RUN_STATE_INMIGRATE)) {
475 if (buffersize != 0) {
476 return tpm_emulator_set_buffer_size(tb, buffersize, NULL, errp);
477 }
478
479 return 0;
480 }
481
482 return tpm_emulator_startup_tpm_resume(tb, buffersize, false, errp);
483 }
484
485 static int tpm_emulator_startup_tpm(TPMBackend *tb, size_t buffersize)
486 {
487 Error *local_err = NULL;
488 int ret = do_tpm_emulator_startup_tpm(tb, buffersize, &local_err);
489
490 if (ret < 0) {
491 error_report_err(local_err);
492 }
493
494 return ret;
495 }
496
497 static bool tpm_emulator_get_tpm_established_flag(TPMBackend *tb)
498 {
499 TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
500 ptm_est est;
501
502 if (tpm_emu->established_flag_cached) {
503 return tpm_emu->established_flag;
504 }
505
506 if (tpm_emulator_ctrlcmd(tpm_emu, CMD_GET_TPMESTABLISHED, &est, 0,
507 sizeof(est) /* always returns resp.bit */,
508 sizeof(est)) < 0) {
509 error_report("tpm-emulator: Could not get the TPM established flag");
510 return false;
511 }
512 trace_tpm_emulator_get_tpm_established_flag(est.u.resp.bit);
513
514 tpm_emu->established_flag_cached = 1;
515 tpm_emu->established_flag = (est.u.resp.bit != 0);
516
517 return tpm_emu->established_flag;
518 }
519
520 static int tpm_emulator_reset_tpm_established_flag(TPMBackend *tb,
521 uint8_t locty)
522 {
523 TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
524 ptm_reset_est reset_est;
525 ptm_res res;
526
527 /* only a TPM 2.0 will support this */
528 if (tpm_emu->tpm_version != TPM_VERSION_2_0) {
529 return 0;
530 }
531
532 reset_est.u.req.loc = tpm_emu->cur_locty_number;
533 if (tpm_emulator_ctrlcmd(tpm_emu, CMD_RESET_TPMESTABLISHED,
534 &reset_est, sizeof(reset_est),
535 sizeof(reset_est.u.resp.tpm_result),
536 sizeof(reset_est)) < 0) {
537 error_report("tpm-emulator: Could not reset the establishment bit");
538 return -1;
539 }
540
541 res = be32_to_cpu(reset_est.u.resp.tpm_result);
542 if (res) {
543 error_report(
544 "tpm-emulator: TPM result for rest established flag: 0x%x %s",
545 res, tpm_emulator_strerror(res));
546 return -1;
547 }
548
549 tpm_emu->established_flag_cached = 0;
550
551 return 0;
552 }
553
554 static void tpm_emulator_cancel_cmd(TPMBackend *tb)
555 {
556 TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
557 ptm_res res;
558
559 if (!TPM_EMULATOR_IMPLEMENTS_ALL_CAPS(tpm_emu, PTM_CAP_CANCEL_TPM_CMD)) {
560 trace_tpm_emulator_cancel_cmd_not_supt();
561 return;
562 }
563
564 /* FIXME: make the function non-blocking, or it may block a VCPU */
565 if (tpm_emulator_ctrlcmd(tpm_emu, CMD_CANCEL_TPM_CMD, &res, 0,
566 sizeof(ptm_res), sizeof(res)) < 0) {
567 error_report("tpm-emulator: Could not cancel command");
568 } else if (res != 0) {
569 error_report("tpm-emulator: Failed to cancel TPM: 0x%x",
570 be32_to_cpu(res));
571 }
572 }
573
574 static TPMVersion tpm_emulator_get_tpm_version(TPMBackend *tb)
575 {
576 TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
577
578 return tpm_emu->tpm_version;
579 }
580
581 static size_t tpm_emulator_get_buffer_size(TPMBackend *tb)
582 {
583 size_t actual_size;
584 Error *local_err = NULL;
585
586 if (tpm_emulator_set_buffer_size(tb, 0, &actual_size, &local_err) < 0) {
587 error_report_err(local_err);
588 return 4096;
589 }
590
591 return actual_size;
592 }
593
594 static int tpm_emulator_block_migration(TPMEmulator *tpm_emu)
595 {
596 Error *err = NULL;
597 uint32_t caps = PTM_CAP_GET_STATEBLOB | PTM_CAP_SET_STATEBLOB |
598 PTM_CAP_STOP;
599
600 if (!TPM_EMULATOR_IMPLEMENTS_ALL_CAPS(tpm_emu, caps)) {
601 error_setg(&tpm_emu->migration_blocker,
602 "Migration disabled: TPM emulator does not support "
603 "migration");
604 if (migrate_add_blocker(&tpm_emu->migration_blocker, &err) < 0) {
605 error_report_err(err);
606 return -1;
607 }
608 }
609
610 return 0;
611 }
612
613 static int tpm_emulator_prepare_data_fd(TPMEmulator *tpm_emu)
614 {
615 ptm_res res;
616 Error *err = NULL;
617 int fds[2] = { -1, -1 };
618
619 if (qemu_socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
620 error_report("tpm-emulator: Failed to create socketpair");
621 return -1;
622 }
623
624 qemu_chr_fe_set_msgfds(&tpm_emu->ctrl_chr, fds + 1, 1);
625
626 if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_DATAFD, &res, 0,
627 sizeof(ptm_res), sizeof(res)) < 0 || res != 0) {
628 error_report("tpm-emulator: Failed to send CMD_SET_DATAFD");
629 goto err_exit;
630 }
631
632 tpm_emu->data_ioc = QIO_CHANNEL(qio_channel_socket_new_fd(fds[0], &err));
633 if (err) {
634 error_prepend(&err, "tpm-emulator: Failed to create io channel: ");
635 error_report_err(err);
636 goto err_exit;
637 }
638
639 close(fds[1]);
640
641 return 0;
642
643 err_exit:
644 close(fds[0]);
645 close(fds[1]);
646 return -1;
647 }
648
649 static int tpm_emulator_handle_device_opts(TPMEmulator *tpm_emu, QemuOpts *opts)
650 {
651 const char *value;
652 Error *err = NULL;
653 Chardev *dev;
654
655 value = qemu_opt_get(opts, "chardev");
656 if (!value) {
657 error_report("tpm-emulator: parameter 'chardev' is missing");
658 goto err;
659 }
660
661 dev = qemu_chr_find(value);
662 if (!dev) {
663 error_report("tpm-emulator: tpm chardev '%s' not found", value);
664 goto err;
665 }
666
667 if (!qemu_chr_fe_init(&tpm_emu->ctrl_chr, dev, &err)) {
668 error_prepend(&err, "tpm-emulator: No valid chardev found at '%s':",
669 value);
670 error_report_err(err);
671 goto err;
672 }
673
674 tpm_emu->options->chardev = g_strdup(value);
675
676 if (tpm_emulator_prepare_data_fd(tpm_emu) < 0) {
677 goto err;
678 }
679
680 /* FIXME: tpm_util_test_tpmdev() accepts only on socket fd, as it also used
681 * by passthrough driver, which not yet using GIOChannel.
682 */
683 if (tpm_util_test_tpmdev(QIO_CHANNEL_SOCKET(tpm_emu->data_ioc)->fd,
684 &tpm_emu->tpm_version)) {
685 error_report("'%s' is not emulating TPM device.",
686 tpm_emu->options->chardev);
687 goto err;
688 }
689
690 switch (tpm_emu->tpm_version) {
691 case TPM_VERSION_1_2:
692 trace_tpm_emulator_handle_device_opts_tpm12();
693 break;
694 case TPM_VERSION_2_0:
695 trace_tpm_emulator_handle_device_opts_tpm2();
696 break;
697 default:
698 trace_tpm_emulator_handle_device_opts_unspec();
699 }
700
701 if (tpm_emulator_probe_caps(tpm_emu) ||
702 tpm_emulator_check_caps(tpm_emu)) {
703 goto err;
704 }
705
706 return tpm_emulator_block_migration(tpm_emu);
707
708 err:
709 trace_tpm_emulator_handle_device_opts_startup_error();
710
711 return -1;
712 }
713
714 static TPMBackend *tpm_emulator_create(QemuOpts *opts)
715 {
716 TPMBackend *tb = TPM_BACKEND(object_new(TYPE_TPM_EMULATOR));
717
718 if (tpm_emulator_handle_device_opts(TPM_EMULATOR(tb), opts)) {
719 object_unref(OBJECT(tb));
720 return NULL;
721 }
722
723 return tb;
724 }
725
726 static TpmTypeOptions *tpm_emulator_get_tpm_options(TPMBackend *tb)
727 {
728 TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
729 TpmTypeOptions *options = g_new0(TpmTypeOptions, 1);
730
731 options->type = TPM_TYPE_EMULATOR;
732 options->u.emulator.data = QAPI_CLONE(TPMEmulatorOptions, tpm_emu->options);
733
734 return options;
735 }
736
737 static const QemuOptDesc tpm_emulator_cmdline_opts[] = {
738 TPM_STANDARD_CMDLINE_OPTS,
739 {
740 .name = "chardev",
741 .type = QEMU_OPT_STRING,
742 .help = "Character device to use for out-of-band control messages",
743 },
744 { /* end of list */ },
745 };
746
747 /*
748 * Transfer a TPM state blob from the TPM into a provided buffer.
749 *
750 * @tpm_emu: TPMEmulator
751 * @type: the type of blob to transfer
752 * @tsb: the TPMSizeBuffer to fill with the blob
753 * @flags: the flags to return to the caller
754 */
755 static int tpm_emulator_get_state_blob(TPMEmulator *tpm_emu,
756 uint8_t type,
757 TPMSizedBuffer *tsb,
758 uint32_t *flags)
759 {
760 ptm_getstate pgs;
761 ptm_res res;
762 ssize_t n;
763 uint32_t totlength, length;
764
765 tpm_sized_buffer_reset(tsb);
766
767 pgs.u.req.state_flags = cpu_to_be32(PTM_STATE_FLAG_DECRYPTED);
768 pgs.u.req.type = cpu_to_be32(type);
769 pgs.u.req.offset = 0;
770
771 if (tpm_emulator_ctrlcmd(tpm_emu, CMD_GET_STATEBLOB,
772 &pgs, sizeof(pgs.u.req),
773 /* always returns up to resp.data */
774 offsetof(ptm_getstate, u.resp.data),
775 offsetof(ptm_getstate, u.resp.data)) < 0) {
776 error_report("tpm-emulator: could not get state blob type %d", type);
777 return -1;
778 }
779
780 res = be32_to_cpu(pgs.u.resp.tpm_result);
781 if (res != 0 && (res & 0x800) == 0) {
782 error_report("tpm-emulator: Getting the stateblob (type %d) failed "
783 "with a TPM error 0x%x %s", type, res,
784 tpm_emulator_strerror(res));
785 return -1;
786 }
787
788 totlength = be32_to_cpu(pgs.u.resp.totlength);
789 length = be32_to_cpu(pgs.u.resp.length);
790 if (totlength != length) {
791 error_report("tpm-emulator: Expecting to read %u bytes "
792 "but would get %u", totlength, length);
793 return -1;
794 }
795
796 *flags = be32_to_cpu(pgs.u.resp.state_flags);
797
798 if (totlength > 0) {
799 tsb->buffer = g_try_malloc(totlength);
800 if (!tsb->buffer) {
801 error_report("tpm-emulator: Out of memory allocating %u bytes",
802 totlength);
803 return -1;
804 }
805
806 n = qemu_chr_fe_read_all(&tpm_emu->ctrl_chr, tsb->buffer, totlength);
807 if (n != totlength) {
808 error_report("tpm-emulator: Could not read stateblob (type %d); "
809 "expected %u bytes, got %zd",
810 type, totlength, n);
811 return -1;
812 }
813 }
814 tsb->size = totlength;
815
816 trace_tpm_emulator_get_state_blob(type, tsb->size, *flags);
817
818 return 0;
819 }
820
821 static int tpm_emulator_get_state_blobs(TPMEmulator *tpm_emu)
822 {
823 TPMBlobBuffers *state_blobs = &tpm_emu->state_blobs;
824
825 if (tpm_emulator_get_state_blob(tpm_emu, PTM_BLOB_TYPE_PERMANENT,
826 &state_blobs->permanent,
827 &state_blobs->permanent_flags) < 0 ||
828 tpm_emulator_get_state_blob(tpm_emu, PTM_BLOB_TYPE_VOLATILE,
829 &state_blobs->volatil,
830 &state_blobs->volatil_flags) < 0 ||
831 tpm_emulator_get_state_blob(tpm_emu, PTM_BLOB_TYPE_SAVESTATE,
832 &state_blobs->savestate,
833 &state_blobs->savestate_flags) < 0) {
834 goto err_exit;
835 }
836
837 return 0;
838
839 err_exit:
840 tpm_sized_buffer_reset(&state_blobs->volatil);
841 tpm_sized_buffer_reset(&state_blobs->permanent);
842 tpm_sized_buffer_reset(&state_blobs->savestate);
843
844 return -1;
845 }
846
847 /*
848 * Transfer a TPM state blob to the TPM emulator.
849 *
850 * @tpm_emu: TPMEmulator
851 * @type: the type of TPM state blob to transfer
852 * @tsb: TPMSizedBuffer containing the TPM state blob
853 * @flags: Flags describing the (encryption) state of the TPM state blob
854 */
855 static int tpm_emulator_set_state_blob(TPMEmulator *tpm_emu,
856 uint32_t type,
857 TPMSizedBuffer *tsb,
858 uint32_t flags,
859 Error **errp)
860 {
861 ssize_t n;
862 ptm_setstate pss;
863 ptm_res tpm_result;
864
865 if (tsb->size == 0) {
866 return 0;
867 }
868
869 pss = (ptm_setstate) {
870 .u.req.state_flags = cpu_to_be32(flags),
871 .u.req.type = cpu_to_be32(type),
872 .u.req.length = cpu_to_be32(tsb->size),
873 };
874
875 /* write the header only */
876 if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_STATEBLOB, &pss,
877 offsetof(ptm_setstate, u.req.data), 0, 0) < 0) {
878 error_setg(errp, "tpm-emulator: could not set state blob type %d",
879 type);
880 return -1;
881 }
882
883 /* now the body */
884 n = qemu_chr_fe_write_all(&tpm_emu->ctrl_chr, tsb->buffer, tsb->size);
885 if (n != tsb->size) {
886 error_setg(errp, "tpm-emulator: Writing the stateblob (type %d) "
887 "failed; could not write %u bytes, but only %zd",
888 type, tsb->size, n);
889 return -1;
890 }
891
892 /* now get the result */
893 n = qemu_chr_fe_read_all(&tpm_emu->ctrl_chr,
894 (uint8_t *)&pss, sizeof(pss.u.resp));
895 if (n != sizeof(pss.u.resp)) {
896 error_setg(errp, "tpm-emulator: Reading response from writing "
897 "stateblob (type %d) failed; expected %zu bytes, "
898 "got %zd", type, sizeof(pss.u.resp), n);
899 return -1;
900 }
901
902 tpm_result = be32_to_cpu(pss.u.resp.tpm_result);
903 if (tpm_result != 0) {
904 error_setg(errp, "tpm-emulator: Setting the stateblob (type %d) "
905 "failed with a TPM error 0x%x %s", type, tpm_result,
906 tpm_emulator_strerror(tpm_result));
907 return -1;
908 }
909
910 trace_tpm_emulator_set_state_blob(type, tsb->size, flags);
911
912 return 0;
913 }
914
915 /*
916 * Set all the TPM state blobs.
917 */
918 static bool tpm_emulator_set_state_blobs(TPMBackend *tb, Error **errp)
919 {
920 TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
921 TPMBlobBuffers *state_blobs = &tpm_emu->state_blobs;
922
923 trace_tpm_emulator_set_state_blobs();
924
925 if (tpm_emulator_stop_tpm(tb, errp) < 0) {
926 trace_tpm_emulator_set_state_blobs_error("Could not stop TPM");
927 return false;
928 }
929
930 if (tpm_emulator_set_state_blob(tpm_emu, PTM_BLOB_TYPE_PERMANENT,
931 &state_blobs->permanent,
932 state_blobs->permanent_flags, errp) < 0 ||
933 tpm_emulator_set_state_blob(tpm_emu, PTM_BLOB_TYPE_VOLATILE,
934 &state_blobs->volatil,
935 state_blobs->volatil_flags, errp) < 0 ||
936 tpm_emulator_set_state_blob(tpm_emu, PTM_BLOB_TYPE_SAVESTATE,
937 &state_blobs->savestate,
938 state_blobs->savestate_flags, errp) < 0) {
939 return false;
940 }
941
942 trace_tpm_emulator_set_state_blobs_done();
943
944 return true;
945 }
946
947 static int tpm_emulator_pre_save(void *opaque)
948 {
949 TPMBackend *tb = opaque;
950 TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
951 int ret;
952
953 trace_tpm_emulator_pre_save();
954
955 tpm_backend_finish_sync(tb);
956
957 /* get the state blobs from the TPM */
958 ret = tpm_emulator_get_state_blobs(tpm_emu);
959
960 tpm_emu->relock_storage = ret == 0;
961
962 return ret;
963 }
964
965 static void tpm_emulator_vm_state_change(void *opaque, bool running,
966 RunState state)
967 {
968 TPMBackend *tb = opaque;
969 TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
970
971 trace_tpm_emulator_vm_state_change(running, state);
972
973 if (!running || !tpm_emu->relock_storage) {
974 return;
975 }
976
977 /* lock storage after migration fall-back */
978 tpm_emulator_lock_storage(tpm_emu);
979 }
980
981 /*
982 * Load the TPM state blobs into the TPM.
983 */
984 static bool tpm_emulator_post_load(void *opaque, int version_id, Error **errp)
985 {
986 TPMBackend *tb = opaque;
987
988 if (!tpm_emulator_set_state_blobs(tb, errp)) {
989 return false;
990 }
991
992 if (tpm_emulator_startup_tpm_resume(tb, 0, true, errp) < 0) {
993 return false;
994 }
995
996 return true;
997 }
998
999 static const VMStateDescription vmstate_tpm_emulator = {
1000 .name = "tpm-emulator",
1001 .version_id = 0,
1002 .pre_save = tpm_emulator_pre_save,
1003 .post_load_errp = tpm_emulator_post_load,
1004 .fields = (const VMStateField[]) {
1005 VMSTATE_UINT32(state_blobs.permanent_flags, TPMEmulator),
1006 VMSTATE_UINT32(state_blobs.permanent.size, TPMEmulator),
1007 VMSTATE_VBUFFER_ALLOC_UINT32(state_blobs.permanent.buffer,
1008 TPMEmulator, 0, 0,
1009 state_blobs.permanent.size),
1010
1011 VMSTATE_UINT32(state_blobs.volatil_flags, TPMEmulator),
1012 VMSTATE_UINT32(state_blobs.volatil.size, TPMEmulator),
1013 VMSTATE_VBUFFER_ALLOC_UINT32(state_blobs.volatil.buffer,
1014 TPMEmulator, 0, 0,
1015 state_blobs.volatil.size),
1016
1017 VMSTATE_UINT32(state_blobs.savestate_flags, TPMEmulator),
1018 VMSTATE_UINT32(state_blobs.savestate.size, TPMEmulator),
1019 VMSTATE_VBUFFER_ALLOC_UINT32(state_blobs.savestate.buffer,
1020 TPMEmulator, 0, 0,
1021 state_blobs.savestate.size),
1022
1023 VMSTATE_END_OF_LIST()
1024 }
1025 };
1026
1027 static void tpm_emulator_inst_init(Object *obj)
1028 {
1029 TPMEmulator *tpm_emu = TPM_EMULATOR(obj);
1030
1031 trace_tpm_emulator_inst_init();
1032
1033 tpm_emu->options = g_new0(TPMEmulatorOptions, 1);
1034 tpm_emu->cur_locty_number = ~0;
1035 qemu_mutex_init(&tpm_emu->mutex);
1036 tpm_emu->vmstate =
1037 qemu_add_vm_change_state_handler(tpm_emulator_vm_state_change,
1038 tpm_emu);
1039
1040 vmstate_register_any(NULL, &vmstate_tpm_emulator, obj);
1041 }
1042
1043 /*
1044 * Gracefully shut down the external TPM
1045 */
1046 static void tpm_emulator_shutdown(TPMEmulator *tpm_emu)
1047 {
1048 ptm_res res;
1049
1050 if (!tpm_emu->options->chardev) {
1051 /* was never properly initialized */
1052 return;
1053 }
1054
1055 if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SHUTDOWN, &res, 0,
1056 sizeof(ptm_res), sizeof(res)) < 0) {
1057 error_report("tpm-emulator: Could not cleanly shutdown the TPM");
1058 } else if (res != 0) {
1059 error_report("tpm-emulator: TPM result for shutdown: 0x%x %s",
1060 be32_to_cpu(res), tpm_emulator_strerror(be32_to_cpu(res)));
1061 }
1062 }
1063
1064 static void tpm_emulator_inst_finalize(Object *obj)
1065 {
1066 TPMEmulator *tpm_emu = TPM_EMULATOR(obj);
1067 TPMBlobBuffers *state_blobs = &tpm_emu->state_blobs;
1068
1069 tpm_emulator_shutdown(tpm_emu);
1070
1071 object_unref(OBJECT(tpm_emu->data_ioc));
1072
1073 qemu_chr_fe_deinit(&tpm_emu->ctrl_chr, false);
1074
1075 qapi_free_TPMEmulatorOptions(tpm_emu->options);
1076
1077 migrate_del_blocker(&tpm_emu->migration_blocker);
1078
1079 tpm_sized_buffer_reset(&state_blobs->volatil);
1080 tpm_sized_buffer_reset(&state_blobs->permanent);
1081 tpm_sized_buffer_reset(&state_blobs->savestate);
1082
1083 qemu_mutex_destroy(&tpm_emu->mutex);
1084 qemu_del_vm_change_state_handler(tpm_emu->vmstate);
1085
1086 vmstate_unregister(NULL, &vmstate_tpm_emulator, obj);
1087 }
1088
1089 static void tpm_emulator_class_init(ObjectClass *klass, const void *data)
1090 {
1091 TPMBackendClass *tbc = TPM_BACKEND_CLASS(klass);
1092
1093 tbc->type = TPM_TYPE_EMULATOR;
1094 tbc->opts = tpm_emulator_cmdline_opts;
1095 tbc->desc = "TPM emulator backend driver";
1096 tbc->create = tpm_emulator_create;
1097 tbc->startup_tpm = tpm_emulator_startup_tpm;
1098 tbc->cancel_cmd = tpm_emulator_cancel_cmd;
1099 tbc->get_tpm_established_flag = tpm_emulator_get_tpm_established_flag;
1100 tbc->reset_tpm_established_flag = tpm_emulator_reset_tpm_established_flag;
1101 tbc->get_tpm_version = tpm_emulator_get_tpm_version;
1102 tbc->get_buffer_size = tpm_emulator_get_buffer_size;
1103 tbc->get_tpm_options = tpm_emulator_get_tpm_options;
1104
1105 tbc->handle_request = tpm_emulator_handle_request;
1106 }
1107
1108 static const TypeInfo tpm_emulator_info = {
1109 .name = TYPE_TPM_EMULATOR,
1110 .parent = TYPE_TPM_BACKEND,
1111 .instance_size = sizeof(TPMEmulator),
1112 .class_init = tpm_emulator_class_init,
1113 .instance_init = tpm_emulator_inst_init,
1114 .instance_finalize = tpm_emulator_inst_finalize,
1115 };
1116
1117 static void tpm_emulator_register(void)
1118 {
1119 type_register_static(&tpm_emulator_info);
1120 }
1121
1122 type_init(tpm_emulator_register)