xref: /openbmc/qemu/backends/tpm/tpm_emulator.c (revision 7d87775f)
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 "sysemu/runstate.h"
36 #include "sysemu/tpm_backend.h"
37 #include "sysemu/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     CharBackend 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     CharBackend *dev = &tpm->ctrl_chr;
130     uint32_t cmd_no = cpu_to_be32(cmd);
131     ssize_t n = sizeof(uint32_t) + msg_len_in;
132     uint8_t *buf = NULL;
133     ptm_res res;
134 
135     WITH_QEMU_LOCK_GUARD(&tpm->mutex) {
136         buf = g_alloca(n);
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     ssize_t ret;
180     bool is_selftest = false;
181 
182     if (selftest_done) {
183         *selftest_done = false;
184         is_selftest = tpm_util_is_selftest(in, in_len);
185     }
186 
187     ret = qio_channel_write_all(tpm_emu->data_ioc, (char *)in, in_len, errp);
188     if (ret != 0) {
189         return -1;
190     }
191 
192     ret = qio_channel_read_all(tpm_emu->data_ioc, (char *)out,
193               sizeof(struct tpm_resp_hdr), errp);
194     if (ret != 0) {
195         return -1;
196     }
197 
198     ret = qio_channel_read_all(tpm_emu->data_ioc,
199               (char *)out + sizeof(struct tpm_resp_hdr),
200               tpm_cmd_get_size(out) - sizeof(struct tpm_resp_hdr), errp);
201     if (ret != 0) {
202         return -1;
203     }
204 
205     if (is_selftest) {
206         *selftest_done = tpm_cmd_get_errcode(out) == 0;
207     }
208 
209     return 0;
210 }
211 
212 static int tpm_emulator_set_locality(TPMEmulator *tpm_emu, uint8_t locty_number,
213                                      Error **errp)
214 {
215     ptm_loc loc;
216 
217     if (tpm_emu->cur_locty_number == locty_number) {
218         return 0;
219     }
220 
221     trace_tpm_emulator_set_locality(locty_number);
222 
223     memset(&loc, 0, sizeof(loc));
224     loc.u.req.loc = locty_number;
225     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_LOCALITY, &loc,
226                              sizeof(loc), sizeof(loc.u.resp.tpm_result),
227                              sizeof(loc)) < 0) {
228         error_setg(errp, "tpm-emulator: could not set locality : %s",
229                    strerror(errno));
230         return -1;
231     }
232 
233     loc.u.resp.tpm_result = be32_to_cpu(loc.u.resp.tpm_result);
234     if (loc.u.resp.tpm_result != 0) {
235         error_setg(errp, "tpm-emulator: TPM result for set locality : 0x%x",
236                    loc.u.resp.tpm_result);
237         return -1;
238     }
239 
240     tpm_emu->cur_locty_number = locty_number;
241 
242     return 0;
243 }
244 
245 static void tpm_emulator_handle_request(TPMBackend *tb, TPMBackendCmd *cmd,
246                                         Error **errp)
247 {
248     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
249 
250     trace_tpm_emulator_handle_request();
251 
252     if (tpm_emulator_set_locality(tpm_emu, cmd->locty, errp) < 0 ||
253         tpm_emulator_unix_tx_bufs(tpm_emu, cmd->in, cmd->in_len,
254                                   cmd->out, cmd->out_len,
255                                   &cmd->selftest_done, errp) < 0) {
256         tpm_util_write_fatal_error_response(cmd->out, cmd->out_len);
257     }
258 }
259 
260 static int tpm_emulator_probe_caps(TPMEmulator *tpm_emu)
261 {
262     ptm_cap_n cap_n;
263 
264     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_GET_CAPABILITY, &cap_n, 0,
265                              sizeof(cap_n.u.resp.tpm_result),
266                              sizeof(cap_n)) < 0) {
267         error_report("tpm-emulator: probing failed : %s", strerror(errno));
268         return -1;
269     }
270 
271     tpm_emu->caps = be32_to_cpu(cap_n.u.resp.caps);
272 
273     trace_tpm_emulator_probe_caps(tpm_emu->caps);
274 
275     return 0;
276 }
277 
278 static int tpm_emulator_check_caps(TPMEmulator *tpm_emu)
279 {
280     uint32_t caps = 0;
281     const char *tpm = NULL;
282 
283     /* check for min. required capabilities */
284     switch (tpm_emu->tpm_version) {
285     case TPM_VERSION_1_2:
286         caps = PTM_CAP_INIT | PTM_CAP_SHUTDOWN | PTM_CAP_GET_TPMESTABLISHED |
287                PTM_CAP_SET_LOCALITY | PTM_CAP_SET_DATAFD | PTM_CAP_STOP |
288                PTM_CAP_SET_BUFFERSIZE;
289         tpm = "1.2";
290         break;
291     case TPM_VERSION_2_0:
292         caps = PTM_CAP_INIT | PTM_CAP_SHUTDOWN | PTM_CAP_GET_TPMESTABLISHED |
293                PTM_CAP_SET_LOCALITY | PTM_CAP_RESET_TPMESTABLISHED |
294                PTM_CAP_SET_DATAFD | PTM_CAP_STOP | PTM_CAP_SET_BUFFERSIZE;
295         tpm = "2";
296         break;
297     case TPM_VERSION_UNSPEC:
298         error_report("tpm-emulator: TPM version has not been set");
299         return -1;
300     }
301 
302     if (!TPM_EMULATOR_IMPLEMENTS_ALL_CAPS(tpm_emu, caps)) {
303         error_report("tpm-emulator: TPM does not implement minimum set of "
304                      "required capabilities for TPM %s (0x%x)", tpm, (int)caps);
305         return -1;
306     }
307 
308     return 0;
309 }
310 
311 static int tpm_emulator_stop_tpm(TPMBackend *tb)
312 {
313     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
314     ptm_res res;
315 
316     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_STOP, &res, 0,
317                              sizeof(ptm_res), sizeof(res)) < 0) {
318         error_report("tpm-emulator: Could not stop TPM: %s",
319                      strerror(errno));
320         return -1;
321     }
322 
323     res = be32_to_cpu(res);
324     if (res) {
325         error_report("tpm-emulator: TPM result for CMD_STOP: 0x%x %s", res,
326                      tpm_emulator_strerror(res));
327         return -1;
328     }
329 
330     return 0;
331 }
332 
333 static int tpm_emulator_lock_storage(TPMEmulator *tpm_emu)
334 {
335     ptm_lockstorage pls;
336 
337     if (!TPM_EMULATOR_IMPLEMENTS_ALL_CAPS(tpm_emu, PTM_CAP_LOCK_STORAGE)) {
338         trace_tpm_emulator_lock_storage_cmd_not_supt();
339         return 0;
340     }
341 
342     /* give failing side 300 * 10ms time to release lock */
343     pls.u.req.retries = cpu_to_be32(300);
344     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_LOCK_STORAGE, &pls, sizeof(pls.u.req),
345                              sizeof(pls.u.resp.tpm_result),
346                              sizeof(pls.u.resp)) < 0) {
347         error_report("tpm-emulator: Could not lock storage within 3 seconds: "
348                      "%s", strerror(errno));
349         return -1;
350     }
351 
352     pls.u.resp.tpm_result = be32_to_cpu(pls.u.resp.tpm_result);
353     if (pls.u.resp.tpm_result != 0) {
354         error_report("tpm-emulator: TPM result for CMD_LOCK_STORAGE: 0x%x %s",
355                      pls.u.resp.tpm_result,
356                      tpm_emulator_strerror(pls.u.resp.tpm_result));
357         return -1;
358     }
359 
360     return 0;
361 }
362 
363 static int tpm_emulator_set_buffer_size(TPMBackend *tb,
364                                         size_t wanted_size,
365                                         size_t *actual_size)
366 {
367     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
368     ptm_setbuffersize psbs;
369 
370     if (tpm_emulator_stop_tpm(tb) < 0) {
371         return -1;
372     }
373 
374     psbs.u.req.buffersize = cpu_to_be32(wanted_size);
375 
376     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_BUFFERSIZE, &psbs,
377                              sizeof(psbs.u.req), sizeof(psbs.u.resp.tpm_result),
378                              sizeof(psbs.u.resp)) < 0) {
379         error_report("tpm-emulator: Could not set buffer size: %s",
380                      strerror(errno));
381         return -1;
382     }
383 
384     psbs.u.resp.tpm_result = be32_to_cpu(psbs.u.resp.tpm_result);
385     if (psbs.u.resp.tpm_result != 0) {
386         error_report("tpm-emulator: TPM result for set buffer size : 0x%x %s",
387                      psbs.u.resp.tpm_result,
388                      tpm_emulator_strerror(psbs.u.resp.tpm_result));
389         return -1;
390     }
391 
392     if (actual_size) {
393         *actual_size = be32_to_cpu(psbs.u.resp.buffersize);
394     }
395 
396     trace_tpm_emulator_set_buffer_size(
397             be32_to_cpu(psbs.u.resp.buffersize),
398             be32_to_cpu(psbs.u.resp.minsize),
399             be32_to_cpu(psbs.u.resp.maxsize));
400 
401     return 0;
402 }
403 
404 static int tpm_emulator_startup_tpm_resume(TPMBackend *tb, size_t buffersize,
405                                      bool is_resume)
406 {
407     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
408     ptm_init init = {
409         .u.req.init_flags = 0,
410     };
411     ptm_res res;
412 
413     trace_tpm_emulator_startup_tpm_resume(is_resume, buffersize);
414 
415     if (buffersize != 0 &&
416         tpm_emulator_set_buffer_size(tb, buffersize, NULL) < 0) {
417         goto err_exit;
418     }
419 
420     if (is_resume) {
421         init.u.req.init_flags |= cpu_to_be32(PTM_INIT_FLAG_DELETE_VOLATILE);
422     }
423 
424     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_INIT, &init, sizeof(init),
425                              sizeof(init.u.resp.tpm_result),
426                              sizeof(init)) < 0) {
427         error_report("tpm-emulator: could not send INIT: %s",
428                      strerror(errno));
429         goto err_exit;
430     }
431 
432     res = be32_to_cpu(init.u.resp.tpm_result);
433     if (res) {
434         error_report("tpm-emulator: TPM result for CMD_INIT: 0x%x %s", res,
435                      tpm_emulator_strerror(res));
436         goto err_exit;
437     }
438     return 0;
439 
440 err_exit:
441     return -1;
442 }
443 
444 static int tpm_emulator_startup_tpm(TPMBackend *tb, size_t buffersize)
445 {
446     /* TPM startup will be done from post_load hook */
447     if (runstate_check(RUN_STATE_INMIGRATE)) {
448         if (buffersize != 0) {
449             return tpm_emulator_set_buffer_size(tb, buffersize, NULL);
450         }
451 
452         return 0;
453     }
454 
455     return tpm_emulator_startup_tpm_resume(tb, buffersize, false);
456 }
457 
458 static bool tpm_emulator_get_tpm_established_flag(TPMBackend *tb)
459 {
460     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
461     ptm_est est;
462 
463     if (tpm_emu->established_flag_cached) {
464         return tpm_emu->established_flag;
465     }
466 
467     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_GET_TPMESTABLISHED, &est, 0,
468                              sizeof(est) /* always returns resp.bit */,
469                              sizeof(est)) < 0) {
470         error_report("tpm-emulator: Could not get the TPM established flag: %s",
471                      strerror(errno));
472         return false;
473     }
474     trace_tpm_emulator_get_tpm_established_flag(est.u.resp.bit);
475 
476     tpm_emu->established_flag_cached = 1;
477     tpm_emu->established_flag = (est.u.resp.bit != 0);
478 
479     return tpm_emu->established_flag;
480 }
481 
482 static int tpm_emulator_reset_tpm_established_flag(TPMBackend *tb,
483                                                    uint8_t locty)
484 {
485     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
486     ptm_reset_est reset_est;
487     ptm_res res;
488 
489     /* only a TPM 2.0 will support this */
490     if (tpm_emu->tpm_version != TPM_VERSION_2_0) {
491         return 0;
492     }
493 
494     reset_est.u.req.loc = tpm_emu->cur_locty_number;
495     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_RESET_TPMESTABLISHED,
496                              &reset_est, sizeof(reset_est),
497                              sizeof(reset_est.u.resp.tpm_result),
498                              sizeof(reset_est)) < 0) {
499         error_report("tpm-emulator: Could not reset the establishment bit: %s",
500                      strerror(errno));
501         return -1;
502     }
503 
504     res = be32_to_cpu(reset_est.u.resp.tpm_result);
505     if (res) {
506         error_report(
507             "tpm-emulator: TPM result for rest established flag: 0x%x %s",
508             res, tpm_emulator_strerror(res));
509         return -1;
510     }
511 
512     tpm_emu->established_flag_cached = 0;
513 
514     return 0;
515 }
516 
517 static void tpm_emulator_cancel_cmd(TPMBackend *tb)
518 {
519     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
520     ptm_res res;
521 
522     if (!TPM_EMULATOR_IMPLEMENTS_ALL_CAPS(tpm_emu, PTM_CAP_CANCEL_TPM_CMD)) {
523         trace_tpm_emulator_cancel_cmd_not_supt();
524         return;
525     }
526 
527     /* FIXME: make the function non-blocking, or it may block a VCPU */
528     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_CANCEL_TPM_CMD, &res, 0,
529                              sizeof(ptm_res), sizeof(res)) < 0) {
530         error_report("tpm-emulator: Could not cancel command: %s",
531                      strerror(errno));
532     } else if (res != 0) {
533         error_report("tpm-emulator: Failed to cancel TPM: 0x%x",
534                      be32_to_cpu(res));
535     }
536 }
537 
538 static TPMVersion tpm_emulator_get_tpm_version(TPMBackend *tb)
539 {
540     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
541 
542     return tpm_emu->tpm_version;
543 }
544 
545 static size_t tpm_emulator_get_buffer_size(TPMBackend *tb)
546 {
547     size_t actual_size;
548 
549     if (tpm_emulator_set_buffer_size(tb, 0, &actual_size) < 0) {
550         return 4096;
551     }
552 
553     return actual_size;
554 }
555 
556 static int tpm_emulator_block_migration(TPMEmulator *tpm_emu)
557 {
558     Error *err = NULL;
559     uint32_t caps = PTM_CAP_GET_STATEBLOB | PTM_CAP_SET_STATEBLOB |
560                     PTM_CAP_STOP;
561 
562     if (!TPM_EMULATOR_IMPLEMENTS_ALL_CAPS(tpm_emu, caps)) {
563         error_setg(&tpm_emu->migration_blocker,
564                    "Migration disabled: TPM emulator does not support "
565                    "migration");
566         if (migrate_add_blocker(&tpm_emu->migration_blocker, &err) < 0) {
567             error_report_err(err);
568             return -1;
569         }
570     }
571 
572     return 0;
573 }
574 
575 static int tpm_emulator_prepare_data_fd(TPMEmulator *tpm_emu)
576 {
577     ptm_res res;
578     Error *err = NULL;
579     int fds[2] = { -1, -1 };
580 
581     if (qemu_socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
582         error_report("tpm-emulator: Failed to create socketpair");
583         return -1;
584     }
585 
586     qemu_chr_fe_set_msgfds(&tpm_emu->ctrl_chr, fds + 1, 1);
587 
588     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_DATAFD, &res, 0,
589                              sizeof(ptm_res), sizeof(res)) < 0 || res != 0) {
590         error_report("tpm-emulator: Failed to send CMD_SET_DATAFD: %s",
591                      strerror(errno));
592         goto err_exit;
593     }
594 
595     tpm_emu->data_ioc = QIO_CHANNEL(qio_channel_socket_new_fd(fds[0], &err));
596     if (err) {
597         error_prepend(&err, "tpm-emulator: Failed to create io channel: ");
598         error_report_err(err);
599         goto err_exit;
600     }
601 
602     close(fds[1]);
603 
604     return 0;
605 
606 err_exit:
607     close(fds[0]);
608     close(fds[1]);
609     return -1;
610 }
611 
612 static int tpm_emulator_handle_device_opts(TPMEmulator *tpm_emu, QemuOpts *opts)
613 {
614     const char *value;
615     Error *err = NULL;
616     Chardev *dev;
617 
618     value = qemu_opt_get(opts, "chardev");
619     if (!value) {
620         error_report("tpm-emulator: parameter 'chardev' is missing");
621         goto err;
622     }
623 
624     dev = qemu_chr_find(value);
625     if (!dev) {
626         error_report("tpm-emulator: tpm chardev '%s' not found", value);
627         goto err;
628     }
629 
630     if (!qemu_chr_fe_init(&tpm_emu->ctrl_chr, dev, &err)) {
631         error_prepend(&err, "tpm-emulator: No valid chardev found at '%s':",
632                       value);
633         error_report_err(err);
634         goto err;
635     }
636 
637     tpm_emu->options->chardev = g_strdup(value);
638 
639     if (tpm_emulator_prepare_data_fd(tpm_emu) < 0) {
640         goto err;
641     }
642 
643     /* FIXME: tpm_util_test_tpmdev() accepts only on socket fd, as it also used
644      * by passthrough driver, which not yet using GIOChannel.
645      */
646     if (tpm_util_test_tpmdev(QIO_CHANNEL_SOCKET(tpm_emu->data_ioc)->fd,
647                              &tpm_emu->tpm_version)) {
648         error_report("'%s' is not emulating TPM device. Error: %s",
649                       tpm_emu->options->chardev, strerror(errno));
650         goto err;
651     }
652 
653     switch (tpm_emu->tpm_version) {
654     case TPM_VERSION_1_2:
655         trace_tpm_emulator_handle_device_opts_tpm12();
656         break;
657     case TPM_VERSION_2_0:
658         trace_tpm_emulator_handle_device_opts_tpm2();
659         break;
660     default:
661         trace_tpm_emulator_handle_device_opts_unspec();
662     }
663 
664     if (tpm_emulator_probe_caps(tpm_emu) ||
665         tpm_emulator_check_caps(tpm_emu)) {
666         goto err;
667     }
668 
669     return tpm_emulator_block_migration(tpm_emu);
670 
671 err:
672     trace_tpm_emulator_handle_device_opts_startup_error();
673 
674     return -1;
675 }
676 
677 static TPMBackend *tpm_emulator_create(QemuOpts *opts)
678 {
679     TPMBackend *tb = TPM_BACKEND(object_new(TYPE_TPM_EMULATOR));
680 
681     if (tpm_emulator_handle_device_opts(TPM_EMULATOR(tb), opts)) {
682         object_unref(OBJECT(tb));
683         return NULL;
684     }
685 
686     return tb;
687 }
688 
689 static TpmTypeOptions *tpm_emulator_get_tpm_options(TPMBackend *tb)
690 {
691     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
692     TpmTypeOptions *options = g_new0(TpmTypeOptions, 1);
693 
694     options->type = TPM_TYPE_EMULATOR;
695     options->u.emulator.data = QAPI_CLONE(TPMEmulatorOptions, tpm_emu->options);
696 
697     return options;
698 }
699 
700 static const QemuOptDesc tpm_emulator_cmdline_opts[] = {
701     TPM_STANDARD_CMDLINE_OPTS,
702     {
703         .name = "chardev",
704         .type = QEMU_OPT_STRING,
705         .help = "Character device to use for out-of-band control messages",
706     },
707     { /* end of list */ },
708 };
709 
710 /*
711  * Transfer a TPM state blob from the TPM into a provided buffer.
712  *
713  * @tpm_emu: TPMEmulator
714  * @type: the type of blob to transfer
715  * @tsb: the TPMSizeBuffer to fill with the blob
716  * @flags: the flags to return to the caller
717  */
718 static int tpm_emulator_get_state_blob(TPMEmulator *tpm_emu,
719                                        uint8_t type,
720                                        TPMSizedBuffer *tsb,
721                                        uint32_t *flags)
722 {
723     ptm_getstate pgs;
724     ptm_res res;
725     ssize_t n;
726     uint32_t totlength, length;
727 
728     tpm_sized_buffer_reset(tsb);
729 
730     pgs.u.req.state_flags = cpu_to_be32(PTM_STATE_FLAG_DECRYPTED);
731     pgs.u.req.type = cpu_to_be32(type);
732     pgs.u.req.offset = 0;
733 
734     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_GET_STATEBLOB,
735                              &pgs, sizeof(pgs.u.req),
736                              /* always returns up to resp.data */
737                              offsetof(ptm_getstate, u.resp.data),
738                              offsetof(ptm_getstate, u.resp.data)) < 0) {
739         error_report("tpm-emulator: could not get state blob type %d : %s",
740                      type, strerror(errno));
741         return -1;
742     }
743 
744     res = be32_to_cpu(pgs.u.resp.tpm_result);
745     if (res != 0 && (res & 0x800) == 0) {
746         error_report("tpm-emulator: Getting the stateblob (type %d) failed "
747                      "with a TPM error 0x%x %s", type, res,
748                      tpm_emulator_strerror(res));
749         return -1;
750     }
751 
752     totlength = be32_to_cpu(pgs.u.resp.totlength);
753     length = be32_to_cpu(pgs.u.resp.length);
754     if (totlength != length) {
755         error_report("tpm-emulator: Expecting to read %u bytes "
756                      "but would get %u", totlength, length);
757         return -1;
758     }
759 
760     *flags = be32_to_cpu(pgs.u.resp.state_flags);
761 
762     if (totlength > 0) {
763         tsb->buffer = g_try_malloc(totlength);
764         if (!tsb->buffer) {
765             error_report("tpm-emulator: Out of memory allocating %u bytes",
766                          totlength);
767             return -1;
768         }
769 
770         n = qemu_chr_fe_read_all(&tpm_emu->ctrl_chr, tsb->buffer, totlength);
771         if (n != totlength) {
772             error_report("tpm-emulator: Could not read stateblob (type %d); "
773                          "expected %u bytes, got %zd",
774                          type, totlength, n);
775             return -1;
776         }
777     }
778     tsb->size = totlength;
779 
780     trace_tpm_emulator_get_state_blob(type, tsb->size, *flags);
781 
782     return 0;
783 }
784 
785 static int tpm_emulator_get_state_blobs(TPMEmulator *tpm_emu)
786 {
787     TPMBlobBuffers *state_blobs = &tpm_emu->state_blobs;
788 
789     if (tpm_emulator_get_state_blob(tpm_emu, PTM_BLOB_TYPE_PERMANENT,
790                                     &state_blobs->permanent,
791                                     &state_blobs->permanent_flags) < 0 ||
792         tpm_emulator_get_state_blob(tpm_emu, PTM_BLOB_TYPE_VOLATILE,
793                                     &state_blobs->volatil,
794                                     &state_blobs->volatil_flags) < 0 ||
795         tpm_emulator_get_state_blob(tpm_emu, PTM_BLOB_TYPE_SAVESTATE,
796                                     &state_blobs->savestate,
797                                     &state_blobs->savestate_flags) < 0) {
798         goto err_exit;
799     }
800 
801     return 0;
802 
803  err_exit:
804     tpm_sized_buffer_reset(&state_blobs->volatil);
805     tpm_sized_buffer_reset(&state_blobs->permanent);
806     tpm_sized_buffer_reset(&state_blobs->savestate);
807 
808     return -1;
809 }
810 
811 /*
812  * Transfer a TPM state blob to the TPM emulator.
813  *
814  * @tpm_emu: TPMEmulator
815  * @type: the type of TPM state blob to transfer
816  * @tsb: TPMSizedBuffer containing the TPM state blob
817  * @flags: Flags describing the (encryption) state of the TPM state blob
818  */
819 static int tpm_emulator_set_state_blob(TPMEmulator *tpm_emu,
820                                        uint32_t type,
821                                        TPMSizedBuffer *tsb,
822                                        uint32_t flags)
823 {
824     ssize_t n;
825     ptm_setstate pss;
826     ptm_res tpm_result;
827 
828     if (tsb->size == 0) {
829         return 0;
830     }
831 
832     pss = (ptm_setstate) {
833         .u.req.state_flags = cpu_to_be32(flags),
834         .u.req.type = cpu_to_be32(type),
835         .u.req.length = cpu_to_be32(tsb->size),
836     };
837 
838     /* write the header only */
839     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SET_STATEBLOB, &pss,
840                              offsetof(ptm_setstate, u.req.data), 0, 0) < 0) {
841         error_report("tpm-emulator: could not set state blob type %d : %s",
842                      type, strerror(errno));
843         return -1;
844     }
845 
846     /* now the body */
847     n = qemu_chr_fe_write_all(&tpm_emu->ctrl_chr, tsb->buffer, tsb->size);
848     if (n != tsb->size) {
849         error_report("tpm-emulator: Writing the stateblob (type %d) "
850                      "failed; could not write %u bytes, but only %zd",
851                      type, tsb->size, n);
852         return -1;
853     }
854 
855     /* now get the result */
856     n = qemu_chr_fe_read_all(&tpm_emu->ctrl_chr,
857                              (uint8_t *)&pss, sizeof(pss.u.resp));
858     if (n != sizeof(pss.u.resp)) {
859         error_report("tpm-emulator: Reading response from writing stateblob "
860                      "(type %d) failed; expected %zu bytes, got %zd", type,
861                      sizeof(pss.u.resp), n);
862         return -1;
863     }
864 
865     tpm_result = be32_to_cpu(pss.u.resp.tpm_result);
866     if (tpm_result != 0) {
867         error_report("tpm-emulator: Setting the stateblob (type %d) failed "
868                      "with a TPM error 0x%x %s", type, tpm_result,
869                      tpm_emulator_strerror(tpm_result));
870         return -1;
871     }
872 
873     trace_tpm_emulator_set_state_blob(type, tsb->size, flags);
874 
875     return 0;
876 }
877 
878 /*
879  * Set all the TPM state blobs.
880  *
881  * Returns a negative errno code in case of error.
882  */
883 static int tpm_emulator_set_state_blobs(TPMBackend *tb)
884 {
885     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
886     TPMBlobBuffers *state_blobs = &tpm_emu->state_blobs;
887 
888     trace_tpm_emulator_set_state_blobs();
889 
890     if (tpm_emulator_stop_tpm(tb) < 0) {
891         trace_tpm_emulator_set_state_blobs_error("Could not stop TPM");
892         return -EIO;
893     }
894 
895     if (tpm_emulator_set_state_blob(tpm_emu, PTM_BLOB_TYPE_PERMANENT,
896                                     &state_blobs->permanent,
897                                     state_blobs->permanent_flags) < 0 ||
898         tpm_emulator_set_state_blob(tpm_emu, PTM_BLOB_TYPE_VOLATILE,
899                                     &state_blobs->volatil,
900                                     state_blobs->volatil_flags) < 0 ||
901         tpm_emulator_set_state_blob(tpm_emu, PTM_BLOB_TYPE_SAVESTATE,
902                                     &state_blobs->savestate,
903                                     state_blobs->savestate_flags) < 0) {
904         return -EIO;
905     }
906 
907     trace_tpm_emulator_set_state_blobs_done();
908 
909     return 0;
910 }
911 
912 static int tpm_emulator_pre_save(void *opaque)
913 {
914     TPMBackend *tb = opaque;
915     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
916     int ret;
917 
918     trace_tpm_emulator_pre_save();
919 
920     tpm_backend_finish_sync(tb);
921 
922     /* get the state blobs from the TPM */
923     ret = tpm_emulator_get_state_blobs(tpm_emu);
924 
925     tpm_emu->relock_storage = ret == 0;
926 
927     return ret;
928 }
929 
930 static void tpm_emulator_vm_state_change(void *opaque, bool running,
931                                          RunState state)
932 {
933     TPMBackend *tb = opaque;
934     TPMEmulator *tpm_emu = TPM_EMULATOR(tb);
935 
936     trace_tpm_emulator_vm_state_change(running, state);
937 
938     if (!running || !tpm_emu->relock_storage) {
939         return;
940     }
941 
942     /* lock storage after migration fall-back */
943     tpm_emulator_lock_storage(tpm_emu);
944 }
945 
946 /*
947  * Load the TPM state blobs into the TPM.
948  *
949  * Returns negative errno codes in case of error.
950  */
951 static int tpm_emulator_post_load(void *opaque, int version_id)
952 {
953     TPMBackend *tb = opaque;
954     int ret;
955 
956     ret = tpm_emulator_set_state_blobs(tb);
957     if (ret < 0) {
958         return ret;
959     }
960 
961     if (tpm_emulator_startup_tpm_resume(tb, 0, true) < 0) {
962         return -EIO;
963     }
964 
965     return 0;
966 }
967 
968 static const VMStateDescription vmstate_tpm_emulator = {
969     .name = "tpm-emulator",
970     .version_id = 0,
971     .pre_save = tpm_emulator_pre_save,
972     .post_load = tpm_emulator_post_load,
973     .fields = (const VMStateField[]) {
974         VMSTATE_UINT32(state_blobs.permanent_flags, TPMEmulator),
975         VMSTATE_UINT32(state_blobs.permanent.size, TPMEmulator),
976         VMSTATE_VBUFFER_ALLOC_UINT32(state_blobs.permanent.buffer,
977                                      TPMEmulator, 0, 0,
978                                      state_blobs.permanent.size),
979 
980         VMSTATE_UINT32(state_blobs.volatil_flags, TPMEmulator),
981         VMSTATE_UINT32(state_blobs.volatil.size, TPMEmulator),
982         VMSTATE_VBUFFER_ALLOC_UINT32(state_blobs.volatil.buffer,
983                                      TPMEmulator, 0, 0,
984                                      state_blobs.volatil.size),
985 
986         VMSTATE_UINT32(state_blobs.savestate_flags, TPMEmulator),
987         VMSTATE_UINT32(state_blobs.savestate.size, TPMEmulator),
988         VMSTATE_VBUFFER_ALLOC_UINT32(state_blobs.savestate.buffer,
989                                      TPMEmulator, 0, 0,
990                                      state_blobs.savestate.size),
991 
992         VMSTATE_END_OF_LIST()
993     }
994 };
995 
996 static void tpm_emulator_inst_init(Object *obj)
997 {
998     TPMEmulator *tpm_emu = TPM_EMULATOR(obj);
999 
1000     trace_tpm_emulator_inst_init();
1001 
1002     tpm_emu->options = g_new0(TPMEmulatorOptions, 1);
1003     tpm_emu->cur_locty_number = ~0;
1004     qemu_mutex_init(&tpm_emu->mutex);
1005     tpm_emu->vmstate =
1006         qemu_add_vm_change_state_handler(tpm_emulator_vm_state_change,
1007                                          tpm_emu);
1008 
1009     vmstate_register_any(NULL, &vmstate_tpm_emulator, obj);
1010 }
1011 
1012 /*
1013  * Gracefully shut down the external TPM
1014  */
1015 static void tpm_emulator_shutdown(TPMEmulator *tpm_emu)
1016 {
1017     ptm_res res;
1018 
1019     if (!tpm_emu->options->chardev) {
1020         /* was never properly initialized */
1021         return;
1022     }
1023 
1024     if (tpm_emulator_ctrlcmd(tpm_emu, CMD_SHUTDOWN, &res, 0,
1025                              sizeof(ptm_res), sizeof(res)) < 0) {
1026         error_report("tpm-emulator: Could not cleanly shutdown the TPM: %s",
1027                      strerror(errno));
1028     } else if (res != 0) {
1029         error_report("tpm-emulator: TPM result for shutdown: 0x%x %s",
1030                      be32_to_cpu(res), tpm_emulator_strerror(be32_to_cpu(res)));
1031     }
1032 }
1033 
1034 static void tpm_emulator_inst_finalize(Object *obj)
1035 {
1036     TPMEmulator *tpm_emu = TPM_EMULATOR(obj);
1037     TPMBlobBuffers *state_blobs = &tpm_emu->state_blobs;
1038 
1039     tpm_emulator_shutdown(tpm_emu);
1040 
1041     object_unref(OBJECT(tpm_emu->data_ioc));
1042 
1043     qemu_chr_fe_deinit(&tpm_emu->ctrl_chr, false);
1044 
1045     qapi_free_TPMEmulatorOptions(tpm_emu->options);
1046 
1047     migrate_del_blocker(&tpm_emu->migration_blocker);
1048 
1049     tpm_sized_buffer_reset(&state_blobs->volatil);
1050     tpm_sized_buffer_reset(&state_blobs->permanent);
1051     tpm_sized_buffer_reset(&state_blobs->savestate);
1052 
1053     qemu_mutex_destroy(&tpm_emu->mutex);
1054     qemu_del_vm_change_state_handler(tpm_emu->vmstate);
1055 
1056     vmstate_unregister(NULL, &vmstate_tpm_emulator, obj);
1057 }
1058 
1059 static void tpm_emulator_class_init(ObjectClass *klass, void *data)
1060 {
1061     TPMBackendClass *tbc = TPM_BACKEND_CLASS(klass);
1062 
1063     tbc->type = TPM_TYPE_EMULATOR;
1064     tbc->opts = tpm_emulator_cmdline_opts;
1065     tbc->desc = "TPM emulator backend driver";
1066     tbc->create = tpm_emulator_create;
1067     tbc->startup_tpm = tpm_emulator_startup_tpm;
1068     tbc->cancel_cmd = tpm_emulator_cancel_cmd;
1069     tbc->get_tpm_established_flag = tpm_emulator_get_tpm_established_flag;
1070     tbc->reset_tpm_established_flag = tpm_emulator_reset_tpm_established_flag;
1071     tbc->get_tpm_version = tpm_emulator_get_tpm_version;
1072     tbc->get_buffer_size = tpm_emulator_get_buffer_size;
1073     tbc->get_tpm_options = tpm_emulator_get_tpm_options;
1074 
1075     tbc->handle_request = tpm_emulator_handle_request;
1076 }
1077 
1078 static const TypeInfo tpm_emulator_info = {
1079     .name = TYPE_TPM_EMULATOR,
1080     .parent = TYPE_TPM_BACKEND,
1081     .instance_size = sizeof(TPMEmulator),
1082     .class_init = tpm_emulator_class_init,
1083     .instance_init = tpm_emulator_inst_init,
1084     .instance_finalize = tpm_emulator_inst_finalize,
1085 };
1086 
1087 static void tpm_emulator_register(void)
1088 {
1089     type_register_static(&tpm_emulator_info);
1090 }
1091 
1092 type_init(tpm_emulator_register)
1093