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