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