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