xref: /openbmc/qemu/target/i386/sev.c (revision 7b34df44)
1 /*
2  * QEMU SEV support
3  *
4  * Copyright Advanced Micro Devices 2016-2018
5  *
6  * Author:
7  *      Brijesh Singh <brijesh.singh@amd.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2 or later.
10  * See the COPYING file in the top-level directory.
11  *
12  */
13 
14 #include "qemu/osdep.h"
15 
16 #include <linux/kvm.h>
17 #include <linux/psp-sev.h>
18 
19 #include <sys/ioctl.h>
20 
21 #include "qapi/error.h"
22 #include "qom/object_interfaces.h"
23 #include "qemu/base64.h"
24 #include "qemu/module.h"
25 #include "qemu/uuid.h"
26 #include "qemu/error-report.h"
27 #include "crypto/hash.h"
28 #include "sysemu/kvm.h"
29 #include "kvm/kvm_i386.h"
30 #include "sev.h"
31 #include "sysemu/sysemu.h"
32 #include "sysemu/runstate.h"
33 #include "trace.h"
34 #include "migration/blocker.h"
35 #include "qom/object.h"
36 #include "monitor/monitor.h"
37 #include "monitor/hmp-target.h"
38 #include "qapi/qapi-commands-misc-target.h"
39 #include "confidential-guest.h"
40 #include "hw/i386/pc.h"
41 #include "exec/address-spaces.h"
42 
43 OBJECT_DECLARE_TYPE(SevCommonState, SevCommonStateClass, SEV_COMMON)
44 OBJECT_DECLARE_TYPE(SevGuestState, SevCommonStateClass, SEV_GUEST)
45 OBJECT_DECLARE_TYPE(SevSnpGuestState, SevCommonStateClass, SEV_SNP_GUEST)
46 
47 struct SevCommonState {
48     X86ConfidentialGuest parent_obj;
49 
50     int kvm_type;
51 
52     /* configuration parameters */
53     char *sev_device;
54     uint32_t cbitpos;
55     uint32_t reduced_phys_bits;
56     bool kernel_hashes;
57 
58     /* runtime state */
59     uint8_t api_major;
60     uint8_t api_minor;
61     uint8_t build_id;
62     int sev_fd;
63     SevState state;
64 
65     uint32_t reset_cs;
66     uint32_t reset_ip;
67     bool reset_data_valid;
68 };
69 
70 struct SevCommonStateClass {
71     X86ConfidentialGuestClass parent_class;
72 
73     /* public */
74     int (*launch_start)(SevCommonState *sev_common);
75     void (*launch_finish)(SevCommonState *sev_common);
76 };
77 
78 /**
79  * SevGuestState:
80  *
81  * The SevGuestState object is used for creating and managing a SEV
82  * guest.
83  *
84  * # $QEMU \
85  *         -object sev-guest,id=sev0 \
86  *         -machine ...,memory-encryption=sev0
87  */
88 struct SevGuestState {
89     SevCommonState parent_obj;
90     gchar *measurement;
91 
92     /* configuration parameters */
93     uint32_t handle;
94     uint32_t policy;
95     char *dh_cert_file;
96     char *session_file;
97     bool legacy_vm_type;
98 };
99 
100 struct SevSnpGuestState {
101     SevCommonState parent_obj;
102 
103     /* configuration parameters */
104     char *guest_visible_workarounds;
105     char *id_block;
106     char *id_auth;
107     char *host_data;
108 
109     struct kvm_sev_snp_launch_start kvm_start_conf;
110     struct kvm_sev_snp_launch_finish kvm_finish_conf;
111 };
112 
113 #define DEFAULT_GUEST_POLICY    0x1 /* disable debug */
114 #define DEFAULT_SEV_DEVICE      "/dev/sev"
115 #define DEFAULT_SEV_SNP_POLICY  0x30000
116 
117 #define SEV_INFO_BLOCK_GUID     "00f771de-1a7e-4fcb-890e-68c77e2fb44e"
118 typedef struct __attribute__((__packed__)) SevInfoBlock {
119     /* SEV-ES Reset Vector Address */
120     uint32_t reset_addr;
121 } SevInfoBlock;
122 
123 #define SEV_HASH_TABLE_RV_GUID  "7255371f-3a3b-4b04-927b-1da6efa8d454"
124 typedef struct QEMU_PACKED SevHashTableDescriptor {
125     /* SEV hash table area guest address */
126     uint32_t base;
127     /* SEV hash table area size (in bytes) */
128     uint32_t size;
129 } SevHashTableDescriptor;
130 
131 /* hard code sha256 digest size */
132 #define HASH_SIZE 32
133 
134 typedef struct QEMU_PACKED SevHashTableEntry {
135     QemuUUID guid;
136     uint16_t len;
137     uint8_t hash[HASH_SIZE];
138 } SevHashTableEntry;
139 
140 typedef struct QEMU_PACKED SevHashTable {
141     QemuUUID guid;
142     uint16_t len;
143     SevHashTableEntry cmdline;
144     SevHashTableEntry initrd;
145     SevHashTableEntry kernel;
146 } SevHashTable;
147 
148 /*
149  * Data encrypted by sev_encrypt_flash() must be padded to a multiple of
150  * 16 bytes.
151  */
152 typedef struct QEMU_PACKED PaddedSevHashTable {
153     SevHashTable ht;
154     uint8_t padding[ROUND_UP(sizeof(SevHashTable), 16) - sizeof(SevHashTable)];
155 } PaddedSevHashTable;
156 
157 QEMU_BUILD_BUG_ON(sizeof(PaddedSevHashTable) % 16 != 0);
158 
159 static Error *sev_mig_blocker;
160 
161 static const char *const sev_fw_errlist[] = {
162     [SEV_RET_SUCCESS]                = "",
163     [SEV_RET_INVALID_PLATFORM_STATE] = "Platform state is invalid",
164     [SEV_RET_INVALID_GUEST_STATE]    = "Guest state is invalid",
165     [SEV_RET_INAVLID_CONFIG]         = "Platform configuration is invalid",
166     [SEV_RET_INVALID_LEN]            = "Buffer too small",
167     [SEV_RET_ALREADY_OWNED]          = "Platform is already owned",
168     [SEV_RET_INVALID_CERTIFICATE]    = "Certificate is invalid",
169     [SEV_RET_POLICY_FAILURE]         = "Policy is not allowed",
170     [SEV_RET_INACTIVE]               = "Guest is not active",
171     [SEV_RET_INVALID_ADDRESS]        = "Invalid address",
172     [SEV_RET_BAD_SIGNATURE]          = "Bad signature",
173     [SEV_RET_BAD_MEASUREMENT]        = "Bad measurement",
174     [SEV_RET_ASID_OWNED]             = "ASID is already owned",
175     [SEV_RET_INVALID_ASID]           = "Invalid ASID",
176     [SEV_RET_WBINVD_REQUIRED]        = "WBINVD is required",
177     [SEV_RET_DFFLUSH_REQUIRED]       = "DF_FLUSH is required",
178     [SEV_RET_INVALID_GUEST]          = "Guest handle is invalid",
179     [SEV_RET_INVALID_COMMAND]        = "Invalid command",
180     [SEV_RET_ACTIVE]                 = "Guest is active",
181     [SEV_RET_HWSEV_RET_PLATFORM]     = "Hardware error",
182     [SEV_RET_HWSEV_RET_UNSAFE]       = "Hardware unsafe",
183     [SEV_RET_UNSUPPORTED]            = "Feature not supported",
184     [SEV_RET_INVALID_PARAM]          = "Invalid parameter",
185     [SEV_RET_RESOURCE_LIMIT]         = "Required firmware resource depleted",
186     [SEV_RET_SECURE_DATA_INVALID]    = "Part-specific integrity check failure",
187 };
188 
189 #define SEV_FW_MAX_ERROR      ARRAY_SIZE(sev_fw_errlist)
190 
191 static int
192 sev_ioctl(int fd, int cmd, void *data, int *error)
193 {
194     int r;
195     struct kvm_sev_cmd input;
196 
197     memset(&input, 0x0, sizeof(input));
198 
199     input.id = cmd;
200     input.sev_fd = fd;
201     input.data = (uintptr_t)data;
202 
203     r = kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_OP, &input);
204 
205     if (error) {
206         *error = input.error;
207     }
208 
209     return r;
210 }
211 
212 static int
213 sev_platform_ioctl(int fd, int cmd, void *data, int *error)
214 {
215     int r;
216     struct sev_issue_cmd arg;
217 
218     arg.cmd = cmd;
219     arg.data = (unsigned long)data;
220     r = ioctl(fd, SEV_ISSUE_CMD, &arg);
221     if (error) {
222         *error = arg.error;
223     }
224 
225     return r;
226 }
227 
228 static const char *
229 fw_error_to_str(int code)
230 {
231     if (code < 0 || code >= SEV_FW_MAX_ERROR) {
232         return "unknown error";
233     }
234 
235     return sev_fw_errlist[code];
236 }
237 
238 static bool
239 sev_check_state(const SevCommonState *sev_common, SevState state)
240 {
241     assert(sev_common);
242     return sev_common->state == state ? true : false;
243 }
244 
245 static void
246 sev_set_guest_state(SevCommonState *sev_common, SevState new_state)
247 {
248     assert(new_state < SEV_STATE__MAX);
249     assert(sev_common);
250 
251     trace_kvm_sev_change_state(SevState_str(sev_common->state),
252                                SevState_str(new_state));
253     sev_common->state = new_state;
254 }
255 
256 static void
257 sev_ram_block_added(RAMBlockNotifier *n, void *host, size_t size,
258                     size_t max_size)
259 {
260     int r;
261     struct kvm_enc_region range;
262     ram_addr_t offset;
263     MemoryRegion *mr;
264 
265     /*
266      * The RAM device presents a memory region that should be treated
267      * as IO region and should not be pinned.
268      */
269     mr = memory_region_from_host(host, &offset);
270     if (mr && memory_region_is_ram_device(mr)) {
271         return;
272     }
273 
274     range.addr = (uintptr_t)host;
275     range.size = max_size;
276 
277     trace_kvm_memcrypt_register_region(host, max_size);
278     r = kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_REG_REGION, &range);
279     if (r) {
280         error_report("%s: failed to register region (%p+%#zx) error '%s'",
281                      __func__, host, max_size, strerror(errno));
282         exit(1);
283     }
284 }
285 
286 static void
287 sev_ram_block_removed(RAMBlockNotifier *n, void *host, size_t size,
288                       size_t max_size)
289 {
290     int r;
291     struct kvm_enc_region range;
292     ram_addr_t offset;
293     MemoryRegion *mr;
294 
295     /*
296      * The RAM device presents a memory region that should be treated
297      * as IO region and should not have been pinned.
298      */
299     mr = memory_region_from_host(host, &offset);
300     if (mr && memory_region_is_ram_device(mr)) {
301         return;
302     }
303 
304     range.addr = (uintptr_t)host;
305     range.size = max_size;
306 
307     trace_kvm_memcrypt_unregister_region(host, max_size);
308     r = kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_UNREG_REGION, &range);
309     if (r) {
310         error_report("%s: failed to unregister region (%p+%#zx)",
311                      __func__, host, max_size);
312     }
313 }
314 
315 static struct RAMBlockNotifier sev_ram_notifier = {
316     .ram_block_added = sev_ram_block_added,
317     .ram_block_removed = sev_ram_block_removed,
318 };
319 
320 bool
321 sev_enabled(void)
322 {
323     ConfidentialGuestSupport *cgs = MACHINE(qdev_get_machine())->cgs;
324 
325     return !!object_dynamic_cast(OBJECT(cgs), TYPE_SEV_COMMON);
326 }
327 
328 bool
329 sev_es_enabled(void)
330 {
331     ConfidentialGuestSupport *cgs = MACHINE(qdev_get_machine())->cgs;
332 
333     return sev_enabled() && (SEV_GUEST(cgs)->policy & SEV_POLICY_ES);
334 }
335 
336 uint32_t
337 sev_get_cbit_position(void)
338 {
339     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
340 
341     return sev_common ? sev_common->cbitpos : 0;
342 }
343 
344 uint32_t
345 sev_get_reduced_phys_bits(void)
346 {
347     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
348 
349     return sev_common ? sev_common->reduced_phys_bits : 0;
350 }
351 
352 static SevInfo *sev_get_info(void)
353 {
354     SevInfo *info;
355     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
356     SevGuestState *sev_guest =
357         (SevGuestState *)object_dynamic_cast(OBJECT(sev_common),
358                                              TYPE_SEV_GUEST);
359 
360     info = g_new0(SevInfo, 1);
361     info->enabled = sev_enabled();
362 
363     if (info->enabled) {
364         if (sev_guest) {
365             info->handle = sev_guest->handle;
366         }
367         info->api_major = sev_common->api_major;
368         info->api_minor = sev_common->api_minor;
369         info->build_id = sev_common->build_id;
370         info->state = sev_common->state;
371         /* we only report the lower 32-bits of policy for SNP, ok for now... */
372         info->policy =
373             (uint32_t)object_property_get_uint(OBJECT(sev_common),
374                                                "policy", NULL);
375     }
376 
377     return info;
378 }
379 
380 SevInfo *qmp_query_sev(Error **errp)
381 {
382     SevInfo *info;
383 
384     info = sev_get_info();
385     if (!info) {
386         error_setg(errp, "SEV feature is not available");
387         return NULL;
388     }
389 
390     return info;
391 }
392 
393 void hmp_info_sev(Monitor *mon, const QDict *qdict)
394 {
395     SevInfo *info = sev_get_info();
396 
397     if (info && info->enabled) {
398         monitor_printf(mon, "handle: %d\n", info->handle);
399         monitor_printf(mon, "state: %s\n", SevState_str(info->state));
400         monitor_printf(mon, "build: %d\n", info->build_id);
401         monitor_printf(mon, "api version: %d.%d\n",
402                        info->api_major, info->api_minor);
403         monitor_printf(mon, "debug: %s\n",
404                        info->policy & SEV_POLICY_NODBG ? "off" : "on");
405         monitor_printf(mon, "key-sharing: %s\n",
406                        info->policy & SEV_POLICY_NOKS ? "off" : "on");
407     } else {
408         monitor_printf(mon, "SEV is not enabled\n");
409     }
410 
411     qapi_free_SevInfo(info);
412 }
413 
414 static int
415 sev_get_pdh_info(int fd, guchar **pdh, size_t *pdh_len, guchar **cert_chain,
416                  size_t *cert_chain_len, Error **errp)
417 {
418     guchar *pdh_data = NULL;
419     guchar *cert_chain_data = NULL;
420     struct sev_user_data_pdh_cert_export export = {};
421     int err, r;
422 
423     /* query the certificate length */
424     r = sev_platform_ioctl(fd, SEV_PDH_CERT_EXPORT, &export, &err);
425     if (r < 0) {
426         if (err != SEV_RET_INVALID_LEN) {
427             error_setg(errp, "SEV: Failed to export PDH cert"
428                              " ret=%d fw_err=%d (%s)",
429                        r, err, fw_error_to_str(err));
430             return 1;
431         }
432     }
433 
434     pdh_data = g_new(guchar, export.pdh_cert_len);
435     cert_chain_data = g_new(guchar, export.cert_chain_len);
436     export.pdh_cert_address = (unsigned long)pdh_data;
437     export.cert_chain_address = (unsigned long)cert_chain_data;
438 
439     r = sev_platform_ioctl(fd, SEV_PDH_CERT_EXPORT, &export, &err);
440     if (r < 0) {
441         error_setg(errp, "SEV: Failed to export PDH cert ret=%d fw_err=%d (%s)",
442                    r, err, fw_error_to_str(err));
443         goto e_free;
444     }
445 
446     *pdh = pdh_data;
447     *pdh_len = export.pdh_cert_len;
448     *cert_chain = cert_chain_data;
449     *cert_chain_len = export.cert_chain_len;
450     return 0;
451 
452 e_free:
453     g_free(pdh_data);
454     g_free(cert_chain_data);
455     return 1;
456 }
457 
458 static int sev_get_cpu0_id(int fd, guchar **id, size_t *id_len, Error **errp)
459 {
460     guchar *id_data;
461     struct sev_user_data_get_id2 get_id2 = {};
462     int err, r;
463 
464     /* query the ID length */
465     r = sev_platform_ioctl(fd, SEV_GET_ID2, &get_id2, &err);
466     if (r < 0 && err != SEV_RET_INVALID_LEN) {
467         error_setg(errp, "SEV: Failed to get ID ret=%d fw_err=%d (%s)",
468                    r, err, fw_error_to_str(err));
469         return 1;
470     }
471 
472     id_data = g_new(guchar, get_id2.length);
473     get_id2.address = (unsigned long)id_data;
474 
475     r = sev_platform_ioctl(fd, SEV_GET_ID2, &get_id2, &err);
476     if (r < 0) {
477         error_setg(errp, "SEV: Failed to get ID ret=%d fw_err=%d (%s)",
478                    r, err, fw_error_to_str(err));
479         goto err;
480     }
481 
482     *id = id_data;
483     *id_len = get_id2.length;
484     return 0;
485 
486 err:
487     g_free(id_data);
488     return 1;
489 }
490 
491 static SevCapability *sev_get_capabilities(Error **errp)
492 {
493     SevCapability *cap = NULL;
494     guchar *pdh_data = NULL;
495     guchar *cert_chain_data = NULL;
496     guchar *cpu0_id_data = NULL;
497     size_t pdh_len = 0, cert_chain_len = 0, cpu0_id_len = 0;
498     uint32_t ebx;
499     int fd;
500     SevCommonState *sev_common;
501     char *sev_device;
502 
503     if (!kvm_enabled()) {
504         error_setg(errp, "KVM not enabled");
505         return NULL;
506     }
507     if (kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_OP, NULL) < 0) {
508         error_setg(errp, "SEV is not enabled in KVM");
509         return NULL;
510     }
511 
512     sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
513     if (!sev_common) {
514         error_setg(errp, "SEV is not configured");
515     }
516 
517     sev_device = object_property_get_str(OBJECT(sev_common), "sev-device",
518                                          &error_abort);
519     fd = open(sev_device, O_RDWR);
520     if (fd < 0) {
521         error_setg_errno(errp, errno, "SEV: Failed to open %s",
522                          DEFAULT_SEV_DEVICE);
523         g_free(sev_device);
524         return NULL;
525     }
526     g_free(sev_device);
527 
528     if (sev_get_pdh_info(fd, &pdh_data, &pdh_len,
529                          &cert_chain_data, &cert_chain_len, errp)) {
530         goto out;
531     }
532 
533     if (sev_get_cpu0_id(fd, &cpu0_id_data, &cpu0_id_len, errp)) {
534         goto out;
535     }
536 
537     cap = g_new0(SevCapability, 1);
538     cap->pdh = g_base64_encode(pdh_data, pdh_len);
539     cap->cert_chain = g_base64_encode(cert_chain_data, cert_chain_len);
540     cap->cpu0_id = g_base64_encode(cpu0_id_data, cpu0_id_len);
541 
542     host_cpuid(0x8000001F, 0, NULL, &ebx, NULL, NULL);
543     cap->cbitpos = ebx & 0x3f;
544 
545     /*
546      * When SEV feature is enabled, we loose one bit in guest physical
547      * addressing.
548      */
549     cap->reduced_phys_bits = 1;
550 
551 out:
552     g_free(cpu0_id_data);
553     g_free(pdh_data);
554     g_free(cert_chain_data);
555     close(fd);
556     return cap;
557 }
558 
559 SevCapability *qmp_query_sev_capabilities(Error **errp)
560 {
561     return sev_get_capabilities(errp);
562 }
563 
564 static SevAttestationReport *sev_get_attestation_report(const char *mnonce,
565                                                         Error **errp)
566 {
567     struct kvm_sev_attestation_report input = {};
568     SevAttestationReport *report = NULL;
569     SevCommonState *sev_common;
570     g_autofree guchar *data = NULL;
571     g_autofree guchar *buf = NULL;
572     gsize len;
573     int err = 0, ret;
574 
575     if (!sev_enabled()) {
576         error_setg(errp, "SEV is not enabled");
577         return NULL;
578     }
579 
580     /* lets decode the mnonce string */
581     buf = g_base64_decode(mnonce, &len);
582     if (!buf) {
583         error_setg(errp, "SEV: failed to decode mnonce input");
584         return NULL;
585     }
586 
587     /* verify the input mnonce length */
588     if (len != sizeof(input.mnonce)) {
589         error_setg(errp, "SEV: mnonce must be %zu bytes (got %" G_GSIZE_FORMAT ")",
590                 sizeof(input.mnonce), len);
591         return NULL;
592     }
593 
594     sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
595 
596     /* Query the report length */
597     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_GET_ATTESTATION_REPORT,
598             &input, &err);
599     if (ret < 0) {
600         if (err != SEV_RET_INVALID_LEN) {
601             error_setg(errp, "SEV: Failed to query the attestation report"
602                              " length ret=%d fw_err=%d (%s)",
603                        ret, err, fw_error_to_str(err));
604             return NULL;
605         }
606     }
607 
608     data = g_malloc(input.len);
609     input.uaddr = (unsigned long)data;
610     memcpy(input.mnonce, buf, sizeof(input.mnonce));
611 
612     /* Query the report */
613     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_GET_ATTESTATION_REPORT,
614             &input, &err);
615     if (ret) {
616         error_setg_errno(errp, errno, "SEV: Failed to get attestation report"
617                 " ret=%d fw_err=%d (%s)", ret, err, fw_error_to_str(err));
618         return NULL;
619     }
620 
621     report = g_new0(SevAttestationReport, 1);
622     report->data = g_base64_encode(data, input.len);
623 
624     trace_kvm_sev_attestation_report(mnonce, report->data);
625 
626     return report;
627 }
628 
629 SevAttestationReport *qmp_query_sev_attestation_report(const char *mnonce,
630                                                        Error **errp)
631 {
632     return sev_get_attestation_report(mnonce, errp);
633 }
634 
635 static int
636 sev_read_file_base64(const char *filename, guchar **data, gsize *len)
637 {
638     gsize sz;
639     g_autofree gchar *base64 = NULL;
640     GError *error = NULL;
641 
642     if (!g_file_get_contents(filename, &base64, &sz, &error)) {
643         error_report("SEV: Failed to read '%s' (%s)", filename, error->message);
644         g_error_free(error);
645         return -1;
646     }
647 
648     *data = g_base64_decode(base64, len);
649     return 0;
650 }
651 
652 static int
653 sev_launch_start(SevCommonState *sev_common)
654 {
655     gsize sz;
656     int ret = 1;
657     int fw_error, rc;
658     SevGuestState *sev_guest = SEV_GUEST(sev_common);
659     struct kvm_sev_launch_start start = {
660         .handle = sev_guest->handle, .policy = sev_guest->policy
661     };
662     guchar *session = NULL, *dh_cert = NULL;
663 
664     if (sev_guest->session_file) {
665         if (sev_read_file_base64(sev_guest->session_file, &session, &sz) < 0) {
666             goto out;
667         }
668         start.session_uaddr = (unsigned long)session;
669         start.session_len = sz;
670     }
671 
672     if (sev_guest->dh_cert_file) {
673         if (sev_read_file_base64(sev_guest->dh_cert_file, &dh_cert, &sz) < 0) {
674             goto out;
675         }
676         start.dh_uaddr = (unsigned long)dh_cert;
677         start.dh_len = sz;
678     }
679 
680     trace_kvm_sev_launch_start(start.policy, session, dh_cert);
681     rc = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_START, &start, &fw_error);
682     if (rc < 0) {
683         error_report("%s: LAUNCH_START ret=%d fw_error=%d '%s'",
684                 __func__, ret, fw_error, fw_error_to_str(fw_error));
685         goto out;
686     }
687 
688     sev_set_guest_state(sev_common, SEV_STATE_LAUNCH_UPDATE);
689     sev_guest->handle = start.handle;
690     ret = 0;
691 
692 out:
693     g_free(session);
694     g_free(dh_cert);
695     return ret;
696 }
697 
698 static int
699 sev_launch_update_data(SevGuestState *sev_guest, uint8_t *addr, uint64_t len)
700 {
701     int ret, fw_error;
702     struct kvm_sev_launch_update_data update;
703 
704     if (!addr || !len) {
705         return 1;
706     }
707 
708     update.uaddr = (uintptr_t)addr;
709     update.len = len;
710     trace_kvm_sev_launch_update_data(addr, len);
711     ret = sev_ioctl(SEV_COMMON(sev_guest)->sev_fd, KVM_SEV_LAUNCH_UPDATE_DATA,
712                     &update, &fw_error);
713     if (ret) {
714         error_report("%s: LAUNCH_UPDATE ret=%d fw_error=%d '%s'",
715                 __func__, ret, fw_error, fw_error_to_str(fw_error));
716     }
717 
718     return ret;
719 }
720 
721 static int
722 sev_launch_update_vmsa(SevGuestState *sev_guest)
723 {
724     int ret, fw_error;
725 
726     ret = sev_ioctl(SEV_COMMON(sev_guest)->sev_fd, KVM_SEV_LAUNCH_UPDATE_VMSA,
727                     NULL, &fw_error);
728     if (ret) {
729         error_report("%s: LAUNCH_UPDATE_VMSA ret=%d fw_error=%d '%s'",
730                 __func__, ret, fw_error, fw_error_to_str(fw_error));
731     }
732 
733     return ret;
734 }
735 
736 static void
737 sev_launch_get_measure(Notifier *notifier, void *unused)
738 {
739     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
740     SevGuestState *sev_guest = SEV_GUEST(sev_common);
741     int ret, error;
742     g_autofree guchar *data = NULL;
743     struct kvm_sev_launch_measure measurement = {};
744 
745     if (!sev_check_state(sev_common, SEV_STATE_LAUNCH_UPDATE)) {
746         return;
747     }
748 
749     if (sev_es_enabled()) {
750         /* measure all the VM save areas before getting launch_measure */
751         ret = sev_launch_update_vmsa(sev_guest);
752         if (ret) {
753             exit(1);
754         }
755         kvm_mark_guest_state_protected();
756     }
757 
758     /* query the measurement blob length */
759     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_MEASURE,
760                     &measurement, &error);
761     if (!measurement.len) {
762         error_report("%s: LAUNCH_MEASURE ret=%d fw_error=%d '%s'",
763                      __func__, ret, error, fw_error_to_str(errno));
764         return;
765     }
766 
767     data = g_new0(guchar, measurement.len);
768     measurement.uaddr = (unsigned long)data;
769 
770     /* get the measurement blob */
771     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_MEASURE,
772                     &measurement, &error);
773     if (ret) {
774         error_report("%s: LAUNCH_MEASURE ret=%d fw_error=%d '%s'",
775                      __func__, ret, error, fw_error_to_str(errno));
776         return;
777     }
778 
779     sev_set_guest_state(sev_common, SEV_STATE_LAUNCH_SECRET);
780 
781     /* encode the measurement value and emit the event */
782     sev_guest->measurement = g_base64_encode(data, measurement.len);
783     trace_kvm_sev_launch_measurement(sev_guest->measurement);
784 }
785 
786 static char *sev_get_launch_measurement(void)
787 {
788     SevGuestState *sev_guest = SEV_GUEST(MACHINE(qdev_get_machine())->cgs);
789 
790     if (sev_guest &&
791         SEV_COMMON(sev_guest)->state >= SEV_STATE_LAUNCH_SECRET) {
792         return g_strdup(sev_guest->measurement);
793     }
794 
795     return NULL;
796 }
797 
798 SevLaunchMeasureInfo *qmp_query_sev_launch_measure(Error **errp)
799 {
800     char *data;
801     SevLaunchMeasureInfo *info;
802 
803     data = sev_get_launch_measurement();
804     if (!data) {
805         error_setg(errp, "SEV launch measurement is not available");
806         return NULL;
807     }
808 
809     info = g_malloc0(sizeof(*info));
810     info->data = data;
811 
812     return info;
813 }
814 
815 static Notifier sev_machine_done_notify = {
816     .notify = sev_launch_get_measure,
817 };
818 
819 static void
820 sev_launch_finish(SevCommonState *sev_common)
821 {
822     int ret, error;
823 
824     trace_kvm_sev_launch_finish();
825     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_FINISH, 0,
826                     &error);
827     if (ret) {
828         error_report("%s: LAUNCH_FINISH ret=%d fw_error=%d '%s'",
829                      __func__, ret, error, fw_error_to_str(error));
830         exit(1);
831     }
832 
833     sev_set_guest_state(sev_common, SEV_STATE_RUNNING);
834 
835     /* add migration blocker */
836     error_setg(&sev_mig_blocker,
837                "SEV: Migration is not implemented");
838     migrate_add_blocker(&sev_mig_blocker, &error_fatal);
839 }
840 
841 static void
842 sev_vm_state_change(void *opaque, bool running, RunState state)
843 {
844     SevCommonState *sev_common = opaque;
845     SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(opaque);
846 
847     if (running) {
848         if (!sev_check_state(sev_common, SEV_STATE_RUNNING)) {
849             klass->launch_finish(sev_common);
850         }
851     }
852 }
853 
854 static int sev_kvm_type(X86ConfidentialGuest *cg)
855 {
856     SevCommonState *sev_common = SEV_COMMON(cg);
857     SevGuestState *sev_guest = SEV_GUEST(sev_common);
858     int kvm_type;
859 
860     if (sev_common->kvm_type != -1) {
861         goto out;
862     }
863 
864     kvm_type = (sev_guest->policy & SEV_POLICY_ES) ?
865                 KVM_X86_SEV_ES_VM : KVM_X86_SEV_VM;
866     if (kvm_is_vm_type_supported(kvm_type) && !sev_guest->legacy_vm_type) {
867         sev_common->kvm_type = kvm_type;
868     } else {
869         sev_common->kvm_type = KVM_X86_DEFAULT_VM;
870     }
871 
872 out:
873     return sev_common->kvm_type;
874 }
875 
876 static int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
877 {
878     SevCommonState *sev_common = SEV_COMMON(cgs);
879     char *devname;
880     int ret, fw_error, cmd;
881     uint32_t ebx;
882     uint32_t host_cbitpos;
883     struct sev_user_data_status status = {};
884     SevCommonStateClass *klass = SEV_COMMON_GET_CLASS(cgs);
885 
886     ret = ram_block_discard_disable(true);
887     if (ret) {
888         error_report("%s: cannot disable RAM discard", __func__);
889         return -1;
890     }
891 
892     sev_common->state = SEV_STATE_UNINIT;
893 
894     host_cpuid(0x8000001F, 0, NULL, &ebx, NULL, NULL);
895     host_cbitpos = ebx & 0x3f;
896 
897     /*
898      * The cbitpos value will be placed in bit positions 5:0 of the EBX
899      * register of CPUID 0x8000001F. No need to verify the range as the
900      * comparison against the host value accomplishes that.
901      */
902     if (host_cbitpos != sev_common->cbitpos) {
903         error_setg(errp, "%s: cbitpos check failed, host '%d' requested '%d'",
904                    __func__, host_cbitpos, sev_common->cbitpos);
905         goto err;
906     }
907 
908     /*
909      * The reduced-phys-bits value will be placed in bit positions 11:6 of
910      * the EBX register of CPUID 0x8000001F, so verify the supplied value
911      * is in the range of 1 to 63.
912      */
913     if (sev_common->reduced_phys_bits < 1 ||
914         sev_common->reduced_phys_bits > 63) {
915         error_setg(errp, "%s: reduced_phys_bits check failed,"
916                    " it should be in the range of 1 to 63, requested '%d'",
917                    __func__, sev_common->reduced_phys_bits);
918         goto err;
919     }
920 
921     devname = object_property_get_str(OBJECT(sev_common), "sev-device", NULL);
922     sev_common->sev_fd = open(devname, O_RDWR);
923     if (sev_common->sev_fd < 0) {
924         error_setg(errp, "%s: Failed to open %s '%s'", __func__,
925                    devname, strerror(errno));
926         g_free(devname);
927         goto err;
928     }
929     g_free(devname);
930 
931     ret = sev_platform_ioctl(sev_common->sev_fd, SEV_PLATFORM_STATUS, &status,
932                              &fw_error);
933     if (ret) {
934         error_setg(errp, "%s: failed to get platform status ret=%d "
935                    "fw_error='%d: %s'", __func__, ret, fw_error,
936                    fw_error_to_str(fw_error));
937         goto err;
938     }
939     sev_common->build_id = status.build;
940     sev_common->api_major = status.api_major;
941     sev_common->api_minor = status.api_minor;
942 
943     if (sev_es_enabled()) {
944         if (!kvm_kernel_irqchip_allowed()) {
945             error_setg(errp, "%s: SEV-ES guests require in-kernel irqchip"
946                        "support", __func__);
947             goto err;
948         }
949 
950         if (!(status.flags & SEV_STATUS_FLAGS_CONFIG_ES)) {
951             error_setg(errp, "%s: guest policy requires SEV-ES, but "
952                          "host SEV-ES support unavailable",
953                          __func__);
954             goto err;
955         }
956     }
957 
958     trace_kvm_sev_init();
959     if (sev_kvm_type(X86_CONFIDENTIAL_GUEST(sev_common)) == KVM_X86_DEFAULT_VM) {
960         cmd = sev_es_enabled() ? KVM_SEV_ES_INIT : KVM_SEV_INIT;
961 
962         ret = sev_ioctl(sev_common->sev_fd, cmd, NULL, &fw_error);
963     } else {
964         struct kvm_sev_init args = { 0 };
965 
966         ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_INIT2, &args, &fw_error);
967     }
968 
969     if (ret) {
970         error_setg(errp, "%s: failed to initialize ret=%d fw_error=%d '%s'",
971                    __func__, ret, fw_error, fw_error_to_str(fw_error));
972         goto err;
973     }
974 
975     ret = klass->launch_start(sev_common);
976     if (ret) {
977         error_setg(errp, "%s: failed to create encryption context", __func__);
978         goto err;
979     }
980 
981     ram_block_notifier_add(&sev_ram_notifier);
982     qemu_add_machine_init_done_notifier(&sev_machine_done_notify);
983     qemu_add_vm_change_state_handler(sev_vm_state_change, sev_common);
984 
985     cgs->ready = true;
986 
987     return 0;
988 err:
989     ram_block_discard_disable(false);
990     return -1;
991 }
992 
993 int
994 sev_encrypt_flash(uint8_t *ptr, uint64_t len, Error **errp)
995 {
996     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
997 
998     if (!sev_common) {
999         return 0;
1000     }
1001 
1002     /* if SEV is in update state then encrypt the data else do nothing */
1003     if (sev_check_state(sev_common, SEV_STATE_LAUNCH_UPDATE)) {
1004         int ret = sev_launch_update_data(SEV_GUEST(sev_common), ptr, len);
1005         if (ret < 0) {
1006             error_setg(errp, "SEV: Failed to encrypt pflash rom");
1007             return ret;
1008         }
1009     }
1010 
1011     return 0;
1012 }
1013 
1014 int sev_inject_launch_secret(const char *packet_hdr, const char *secret,
1015                              uint64_t gpa, Error **errp)
1016 {
1017     ERRP_GUARD();
1018     struct kvm_sev_launch_secret input;
1019     g_autofree guchar *data = NULL, *hdr = NULL;
1020     int error, ret = 1;
1021     void *hva;
1022     gsize hdr_sz = 0, data_sz = 0;
1023     MemoryRegion *mr = NULL;
1024     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1025 
1026     if (!sev_common) {
1027         error_setg(errp, "SEV not enabled for guest");
1028         return 1;
1029     }
1030 
1031     /* secret can be injected only in this state */
1032     if (!sev_check_state(sev_common, SEV_STATE_LAUNCH_SECRET)) {
1033         error_setg(errp, "SEV: Not in correct state. (LSECRET) %x",
1034                    sev_common->state);
1035         return 1;
1036     }
1037 
1038     hdr = g_base64_decode(packet_hdr, &hdr_sz);
1039     if (!hdr || !hdr_sz) {
1040         error_setg(errp, "SEV: Failed to decode sequence header");
1041         return 1;
1042     }
1043 
1044     data = g_base64_decode(secret, &data_sz);
1045     if (!data || !data_sz) {
1046         error_setg(errp, "SEV: Failed to decode data");
1047         return 1;
1048     }
1049 
1050     hva = gpa2hva(&mr, gpa, data_sz, errp);
1051     if (!hva) {
1052         error_prepend(errp, "SEV: Failed to calculate guest address: ");
1053         return 1;
1054     }
1055 
1056     input.hdr_uaddr = (uint64_t)(unsigned long)hdr;
1057     input.hdr_len = hdr_sz;
1058 
1059     input.trans_uaddr = (uint64_t)(unsigned long)data;
1060     input.trans_len = data_sz;
1061 
1062     input.guest_uaddr = (uint64_t)(unsigned long)hva;
1063     input.guest_len = data_sz;
1064 
1065     trace_kvm_sev_launch_secret(gpa, input.guest_uaddr,
1066                                 input.trans_uaddr, input.trans_len);
1067 
1068     ret = sev_ioctl(sev_common->sev_fd, KVM_SEV_LAUNCH_SECRET,
1069                     &input, &error);
1070     if (ret) {
1071         error_setg(errp, "SEV: failed to inject secret ret=%d fw_error=%d '%s'",
1072                      ret, error, fw_error_to_str(error));
1073         return ret;
1074     }
1075 
1076     return 0;
1077 }
1078 
1079 #define SEV_SECRET_GUID "4c2eb361-7d9b-4cc3-8081-127c90d3d294"
1080 struct sev_secret_area {
1081     uint32_t base;
1082     uint32_t size;
1083 };
1084 
1085 void qmp_sev_inject_launch_secret(const char *packet_hdr,
1086                                   const char *secret,
1087                                   bool has_gpa, uint64_t gpa,
1088                                   Error **errp)
1089 {
1090     if (!sev_enabled()) {
1091         error_setg(errp, "SEV not enabled for guest");
1092         return;
1093     }
1094     if (!has_gpa) {
1095         uint8_t *data;
1096         struct sev_secret_area *area;
1097 
1098         if (!pc_system_ovmf_table_find(SEV_SECRET_GUID, &data, NULL)) {
1099             error_setg(errp, "SEV: no secret area found in OVMF,"
1100                        " gpa must be specified.");
1101             return;
1102         }
1103         area = (struct sev_secret_area *)data;
1104         gpa = area->base;
1105     }
1106 
1107     sev_inject_launch_secret(packet_hdr, secret, gpa, errp);
1108 }
1109 
1110 static int
1111 sev_es_parse_reset_block(SevInfoBlock *info, uint32_t *addr)
1112 {
1113     if (!info->reset_addr) {
1114         error_report("SEV-ES reset address is zero");
1115         return 1;
1116     }
1117 
1118     *addr = info->reset_addr;
1119 
1120     return 0;
1121 }
1122 
1123 static int
1124 sev_es_find_reset_vector(void *flash_ptr, uint64_t flash_size,
1125                          uint32_t *addr)
1126 {
1127     QemuUUID info_guid, *guid;
1128     SevInfoBlock *info;
1129     uint8_t *data;
1130     uint16_t *len;
1131 
1132     /*
1133      * Initialize the address to zero. An address of zero with a successful
1134      * return code indicates that SEV-ES is not active.
1135      */
1136     *addr = 0;
1137 
1138     /*
1139      * Extract the AP reset vector for SEV-ES guests by locating the SEV GUID.
1140      * The SEV GUID is located on its own (original implementation) or within
1141      * the Firmware GUID Table (new implementation), either of which are
1142      * located 32 bytes from the end of the flash.
1143      *
1144      * Check the Firmware GUID Table first.
1145      */
1146     if (pc_system_ovmf_table_find(SEV_INFO_BLOCK_GUID, &data, NULL)) {
1147         return sev_es_parse_reset_block((SevInfoBlock *)data, addr);
1148     }
1149 
1150     /*
1151      * SEV info block not found in the Firmware GUID Table (or there isn't
1152      * a Firmware GUID Table), fall back to the original implementation.
1153      */
1154     data = flash_ptr + flash_size - 0x20;
1155 
1156     qemu_uuid_parse(SEV_INFO_BLOCK_GUID, &info_guid);
1157     info_guid = qemu_uuid_bswap(info_guid); /* GUIDs are LE */
1158 
1159     guid = (QemuUUID *)(data - sizeof(info_guid));
1160     if (!qemu_uuid_is_equal(guid, &info_guid)) {
1161         error_report("SEV information block/Firmware GUID Table block not found in pflash rom");
1162         return 1;
1163     }
1164 
1165     len = (uint16_t *)((uint8_t *)guid - sizeof(*len));
1166     info = (SevInfoBlock *)(data - le16_to_cpu(*len));
1167 
1168     return sev_es_parse_reset_block(info, addr);
1169 }
1170 
1171 void sev_es_set_reset_vector(CPUState *cpu)
1172 {
1173     X86CPU *x86;
1174     CPUX86State *env;
1175     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1176 
1177     /* Only update if we have valid reset information */
1178     if (!sev_common || !sev_common->reset_data_valid) {
1179         return;
1180     }
1181 
1182     /* Do not update the BSP reset state */
1183     if (cpu->cpu_index == 0) {
1184         return;
1185     }
1186 
1187     x86 = X86_CPU(cpu);
1188     env = &x86->env;
1189 
1190     cpu_x86_load_seg_cache(env, R_CS, 0xf000, sev_common->reset_cs, 0xffff,
1191                            DESC_P_MASK | DESC_S_MASK | DESC_CS_MASK |
1192                            DESC_R_MASK | DESC_A_MASK);
1193 
1194     env->eip = sev_common->reset_ip;
1195 }
1196 
1197 int sev_es_save_reset_vector(void *flash_ptr, uint64_t flash_size)
1198 {
1199     CPUState *cpu;
1200     uint32_t addr;
1201     int ret;
1202     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1203 
1204     if (!sev_es_enabled()) {
1205         return 0;
1206     }
1207 
1208     addr = 0;
1209     ret = sev_es_find_reset_vector(flash_ptr, flash_size,
1210                                    &addr);
1211     if (ret) {
1212         return ret;
1213     }
1214 
1215     if (addr) {
1216         sev_common->reset_cs = addr & 0xffff0000;
1217         sev_common->reset_ip = addr & 0x0000ffff;
1218         sev_common->reset_data_valid = true;
1219 
1220         CPU_FOREACH(cpu) {
1221             sev_es_set_reset_vector(cpu);
1222         }
1223     }
1224 
1225     return 0;
1226 }
1227 
1228 static const QemuUUID sev_hash_table_header_guid = {
1229     .data = UUID_LE(0x9438d606, 0x4f22, 0x4cc9, 0xb4, 0x79, 0xa7, 0x93,
1230                     0xd4, 0x11, 0xfd, 0x21)
1231 };
1232 
1233 static const QemuUUID sev_kernel_entry_guid = {
1234     .data = UUID_LE(0x4de79437, 0xabd2, 0x427f, 0xb8, 0x35, 0xd5, 0xb1,
1235                     0x72, 0xd2, 0x04, 0x5b)
1236 };
1237 static const QemuUUID sev_initrd_entry_guid = {
1238     .data = UUID_LE(0x44baf731, 0x3a2f, 0x4bd7, 0x9a, 0xf1, 0x41, 0xe2,
1239                     0x91, 0x69, 0x78, 0x1d)
1240 };
1241 static const QemuUUID sev_cmdline_entry_guid = {
1242     .data = UUID_LE(0x97d02dd8, 0xbd20, 0x4c94, 0xaa, 0x78, 0xe7, 0x71,
1243                     0x4d, 0x36, 0xab, 0x2a)
1244 };
1245 
1246 /*
1247  * Add the hashes of the linux kernel/initrd/cmdline to an encrypted guest page
1248  * which is included in SEV's initial memory measurement.
1249  */
1250 bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp)
1251 {
1252     uint8_t *data;
1253     SevHashTableDescriptor *area;
1254     SevHashTable *ht;
1255     PaddedSevHashTable *padded_ht;
1256     uint8_t cmdline_hash[HASH_SIZE];
1257     uint8_t initrd_hash[HASH_SIZE];
1258     uint8_t kernel_hash[HASH_SIZE];
1259     uint8_t *hashp;
1260     size_t hash_len = HASH_SIZE;
1261     hwaddr mapped_len = sizeof(*padded_ht);
1262     MemTxAttrs attrs = { 0 };
1263     bool ret = true;
1264     SevCommonState *sev_common = SEV_COMMON(MACHINE(qdev_get_machine())->cgs);
1265 
1266     /*
1267      * Only add the kernel hashes if the sev-guest configuration explicitly
1268      * stated kernel-hashes=on.
1269      */
1270     if (!sev_common->kernel_hashes) {
1271         return false;
1272     }
1273 
1274     if (!pc_system_ovmf_table_find(SEV_HASH_TABLE_RV_GUID, &data, NULL)) {
1275         error_setg(errp, "SEV: kernel specified but guest firmware "
1276                          "has no hashes table GUID");
1277         return false;
1278     }
1279     area = (SevHashTableDescriptor *)data;
1280     if (!area->base || area->size < sizeof(PaddedSevHashTable)) {
1281         error_setg(errp, "SEV: guest firmware hashes table area is invalid "
1282                          "(base=0x%x size=0x%x)", area->base, area->size);
1283         return false;
1284     }
1285 
1286     /*
1287      * Calculate hash of kernel command-line with the terminating null byte. If
1288      * the user doesn't supply a command-line via -append, the 1-byte "\0" will
1289      * be used.
1290      */
1291     hashp = cmdline_hash;
1292     if (qcrypto_hash_bytes(QCRYPTO_HASH_ALG_SHA256, ctx->cmdline_data,
1293                            ctx->cmdline_size, &hashp, &hash_len, errp) < 0) {
1294         return false;
1295     }
1296     assert(hash_len == HASH_SIZE);
1297 
1298     /*
1299      * Calculate hash of initrd. If the user doesn't supply an initrd via
1300      * -initrd, an empty buffer will be used (ctx->initrd_size == 0).
1301      */
1302     hashp = initrd_hash;
1303     if (qcrypto_hash_bytes(QCRYPTO_HASH_ALG_SHA256, ctx->initrd_data,
1304                            ctx->initrd_size, &hashp, &hash_len, errp) < 0) {
1305         return false;
1306     }
1307     assert(hash_len == HASH_SIZE);
1308 
1309     /* Calculate hash of the kernel */
1310     hashp = kernel_hash;
1311     struct iovec iov[2] = {
1312         { .iov_base = ctx->setup_data, .iov_len = ctx->setup_size },
1313         { .iov_base = ctx->kernel_data, .iov_len = ctx->kernel_size }
1314     };
1315     if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256, iov, ARRAY_SIZE(iov),
1316                             &hashp, &hash_len, errp) < 0) {
1317         return false;
1318     }
1319     assert(hash_len == HASH_SIZE);
1320 
1321     /*
1322      * Populate the hashes table in the guest's memory at the OVMF-designated
1323      * area for the SEV hashes table
1324      */
1325     padded_ht = address_space_map(&address_space_memory, area->base,
1326                                   &mapped_len, true, attrs);
1327     if (!padded_ht || mapped_len != sizeof(*padded_ht)) {
1328         error_setg(errp, "SEV: cannot map hashes table guest memory area");
1329         return false;
1330     }
1331     ht = &padded_ht->ht;
1332 
1333     ht->guid = sev_hash_table_header_guid;
1334     ht->len = sizeof(*ht);
1335 
1336     ht->cmdline.guid = sev_cmdline_entry_guid;
1337     ht->cmdline.len = sizeof(ht->cmdline);
1338     memcpy(ht->cmdline.hash, cmdline_hash, sizeof(ht->cmdline.hash));
1339 
1340     ht->initrd.guid = sev_initrd_entry_guid;
1341     ht->initrd.len = sizeof(ht->initrd);
1342     memcpy(ht->initrd.hash, initrd_hash, sizeof(ht->initrd.hash));
1343 
1344     ht->kernel.guid = sev_kernel_entry_guid;
1345     ht->kernel.len = sizeof(ht->kernel);
1346     memcpy(ht->kernel.hash, kernel_hash, sizeof(ht->kernel.hash));
1347 
1348     /* zero the excess data so the measurement can be reliably calculated */
1349     memset(padded_ht->padding, 0, sizeof(padded_ht->padding));
1350 
1351     if (sev_encrypt_flash((uint8_t *)padded_ht, sizeof(*padded_ht), errp) < 0) {
1352         ret = false;
1353     }
1354 
1355     address_space_unmap(&address_space_memory, padded_ht,
1356                         mapped_len, true, mapped_len);
1357 
1358     return ret;
1359 }
1360 
1361 static char *
1362 sev_common_get_sev_device(Object *obj, Error **errp)
1363 {
1364     return g_strdup(SEV_COMMON(obj)->sev_device);
1365 }
1366 
1367 static void
1368 sev_common_set_sev_device(Object *obj, const char *value, Error **errp)
1369 {
1370     SEV_COMMON(obj)->sev_device = g_strdup(value);
1371 }
1372 
1373 static bool sev_common_get_kernel_hashes(Object *obj, Error **errp)
1374 {
1375     return SEV_COMMON(obj)->kernel_hashes;
1376 }
1377 
1378 static void sev_common_set_kernel_hashes(Object *obj, bool value, Error **errp)
1379 {
1380     SEV_COMMON(obj)->kernel_hashes = value;
1381 }
1382 
1383 static void
1384 sev_common_class_init(ObjectClass *oc, void *data)
1385 {
1386     ConfidentialGuestSupportClass *klass = CONFIDENTIAL_GUEST_SUPPORT_CLASS(oc);
1387     X86ConfidentialGuestClass *x86_klass = X86_CONFIDENTIAL_GUEST_CLASS(oc);
1388 
1389     klass->kvm_init = sev_kvm_init;
1390     x86_klass->kvm_type = sev_kvm_type;
1391 
1392     object_class_property_add_str(oc, "sev-device",
1393                                   sev_common_get_sev_device,
1394                                   sev_common_set_sev_device);
1395     object_class_property_set_description(oc, "sev-device",
1396             "SEV device to use");
1397     object_class_property_add_bool(oc, "kernel-hashes",
1398                                    sev_common_get_kernel_hashes,
1399                                    sev_common_set_kernel_hashes);
1400     object_class_property_set_description(oc, "kernel-hashes",
1401             "add kernel hashes to guest firmware for measured Linux boot");
1402 }
1403 
1404 static void
1405 sev_common_instance_init(Object *obj)
1406 {
1407     SevCommonState *sev_common = SEV_COMMON(obj);
1408 
1409     sev_common->kvm_type = -1;
1410 
1411     sev_common->sev_device = g_strdup(DEFAULT_SEV_DEVICE);
1412 
1413     object_property_add_uint32_ptr(obj, "cbitpos", &sev_common->cbitpos,
1414                                    OBJ_PROP_FLAG_READWRITE);
1415     object_property_add_uint32_ptr(obj, "reduced-phys-bits",
1416                                    &sev_common->reduced_phys_bits,
1417                                    OBJ_PROP_FLAG_READWRITE);
1418 }
1419 
1420 /* sev guest info common to sev/sev-es/sev-snp */
1421 static const TypeInfo sev_common_info = {
1422     .parent = TYPE_X86_CONFIDENTIAL_GUEST,
1423     .name = TYPE_SEV_COMMON,
1424     .instance_size = sizeof(SevCommonState),
1425     .instance_init = sev_common_instance_init,
1426     .class_size = sizeof(SevCommonStateClass),
1427     .class_init = sev_common_class_init,
1428     .abstract = true,
1429     .interfaces = (InterfaceInfo[]) {
1430         { TYPE_USER_CREATABLE },
1431         { }
1432     }
1433 };
1434 
1435 static char *
1436 sev_guest_get_dh_cert_file(Object *obj, Error **errp)
1437 {
1438     return g_strdup(SEV_GUEST(obj)->dh_cert_file);
1439 }
1440 
1441 static void
1442 sev_guest_set_dh_cert_file(Object *obj, const char *value, Error **errp)
1443 {
1444     SEV_GUEST(obj)->dh_cert_file = g_strdup(value);
1445 }
1446 
1447 static char *
1448 sev_guest_get_session_file(Object *obj, Error **errp)
1449 {
1450     SevGuestState *sev_guest = SEV_GUEST(obj);
1451 
1452     return sev_guest->session_file ? g_strdup(sev_guest->session_file) : NULL;
1453 }
1454 
1455 static void
1456 sev_guest_set_session_file(Object *obj, const char *value, Error **errp)
1457 {
1458     SEV_GUEST(obj)->session_file = g_strdup(value);
1459 }
1460 
1461 static bool sev_guest_get_legacy_vm_type(Object *obj, Error **errp)
1462 {
1463     return SEV_GUEST(obj)->legacy_vm_type;
1464 }
1465 
1466 static void sev_guest_set_legacy_vm_type(Object *obj, bool value, Error **errp)
1467 {
1468     SEV_GUEST(obj)->legacy_vm_type = value;
1469 }
1470 
1471 static void
1472 sev_guest_class_init(ObjectClass *oc, void *data)
1473 {
1474     SevCommonStateClass *klass = SEV_COMMON_CLASS(oc);
1475 
1476     klass->launch_start = sev_launch_start;
1477     klass->launch_finish = sev_launch_finish;
1478 
1479     object_class_property_add_str(oc, "dh-cert-file",
1480                                   sev_guest_get_dh_cert_file,
1481                                   sev_guest_set_dh_cert_file);
1482     object_class_property_set_description(oc, "dh-cert-file",
1483             "guest owners DH certificate (encoded with base64)");
1484     object_class_property_add_str(oc, "session-file",
1485                                   sev_guest_get_session_file,
1486                                   sev_guest_set_session_file);
1487     object_class_property_set_description(oc, "session-file",
1488             "guest owners session parameters (encoded with base64)");
1489     object_class_property_add_bool(oc, "legacy-vm-type",
1490                                    sev_guest_get_legacy_vm_type,
1491                                    sev_guest_set_legacy_vm_type);
1492     object_class_property_set_description(oc, "legacy-vm-type",
1493             "use legacy VM type to maintain measurement compatibility with older QEMU or kernel versions.");
1494 }
1495 
1496 static void
1497 sev_guest_instance_init(Object *obj)
1498 {
1499     SevGuestState *sev_guest = SEV_GUEST(obj);
1500 
1501     sev_guest->policy = DEFAULT_GUEST_POLICY;
1502     object_property_add_uint32_ptr(obj, "handle", &sev_guest->handle,
1503                                    OBJ_PROP_FLAG_READWRITE);
1504     object_property_add_uint32_ptr(obj, "policy", &sev_guest->policy,
1505                                    OBJ_PROP_FLAG_READWRITE);
1506     object_apply_compat_props(obj);
1507 }
1508 
1509 /* guest info specific sev/sev-es */
1510 static const TypeInfo sev_guest_info = {
1511     .parent = TYPE_SEV_COMMON,
1512     .name = TYPE_SEV_GUEST,
1513     .instance_size = sizeof(SevGuestState),
1514     .instance_init = sev_guest_instance_init,
1515     .class_init = sev_guest_class_init,
1516 };
1517 
1518 static void
1519 sev_snp_guest_get_policy(Object *obj, Visitor *v, const char *name,
1520                          void *opaque, Error **errp)
1521 {
1522     visit_type_uint64(v, name,
1523                       (uint64_t *)&SEV_SNP_GUEST(obj)->kvm_start_conf.policy,
1524                       errp);
1525 }
1526 
1527 static void
1528 sev_snp_guest_set_policy(Object *obj, Visitor *v, const char *name,
1529                          void *opaque, Error **errp)
1530 {
1531     visit_type_uint64(v, name,
1532                       (uint64_t *)&SEV_SNP_GUEST(obj)->kvm_start_conf.policy,
1533                       errp);
1534 }
1535 
1536 static char *
1537 sev_snp_guest_get_guest_visible_workarounds(Object *obj, Error **errp)
1538 {
1539     return g_strdup(SEV_SNP_GUEST(obj)->guest_visible_workarounds);
1540 }
1541 
1542 static void
1543 sev_snp_guest_set_guest_visible_workarounds(Object *obj, const char *value,
1544                                             Error **errp)
1545 {
1546     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
1547     struct kvm_sev_snp_launch_start *start = &sev_snp_guest->kvm_start_conf;
1548     g_autofree guchar *blob;
1549     gsize len;
1550 
1551     g_free(sev_snp_guest->guest_visible_workarounds);
1552 
1553     /* store the base64 str so we don't need to re-encode in getter */
1554     sev_snp_guest->guest_visible_workarounds = g_strdup(value);
1555 
1556     blob = qbase64_decode(sev_snp_guest->guest_visible_workarounds,
1557                           -1, &len, errp);
1558     if (!blob) {
1559         return;
1560     }
1561 
1562     if (len != sizeof(start->gosvw)) {
1563         error_setg(errp, "parameter length of %lu exceeds max of %lu",
1564                    len, sizeof(start->gosvw));
1565         return;
1566     }
1567 
1568     memcpy(start->gosvw, blob, len);
1569 }
1570 
1571 static char *
1572 sev_snp_guest_get_id_block(Object *obj, Error **errp)
1573 {
1574     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
1575 
1576     return g_strdup(sev_snp_guest->id_block);
1577 }
1578 
1579 static void
1580 sev_snp_guest_set_id_block(Object *obj, const char *value, Error **errp)
1581 {
1582     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
1583     struct kvm_sev_snp_launch_finish *finish = &sev_snp_guest->kvm_finish_conf;
1584     gsize len;
1585 
1586     g_free(sev_snp_guest->id_block);
1587     g_free((guchar *)finish->id_block_uaddr);
1588 
1589     /* store the base64 str so we don't need to re-encode in getter */
1590     sev_snp_guest->id_block = g_strdup(value);
1591 
1592     finish->id_block_uaddr =
1593         (uint64_t)qbase64_decode(sev_snp_guest->id_block, -1, &len, errp);
1594 
1595     if (!finish->id_block_uaddr) {
1596         return;
1597     }
1598 
1599     if (len != KVM_SEV_SNP_ID_BLOCK_SIZE) {
1600         error_setg(errp, "parameter length of %lu not equal to %u",
1601                    len, KVM_SEV_SNP_ID_BLOCK_SIZE);
1602         return;
1603     }
1604 
1605     finish->id_block_en = (len) ? 1 : 0;
1606 }
1607 
1608 static char *
1609 sev_snp_guest_get_id_auth(Object *obj, Error **errp)
1610 {
1611     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
1612 
1613     return g_strdup(sev_snp_guest->id_auth);
1614 }
1615 
1616 static void
1617 sev_snp_guest_set_id_auth(Object *obj, const char *value, Error **errp)
1618 {
1619     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
1620     struct kvm_sev_snp_launch_finish *finish = &sev_snp_guest->kvm_finish_conf;
1621     gsize len;
1622 
1623     g_free(sev_snp_guest->id_auth);
1624     g_free((guchar *)finish->id_auth_uaddr);
1625 
1626     /* store the base64 str so we don't need to re-encode in getter */
1627     sev_snp_guest->id_auth = g_strdup(value);
1628 
1629     finish->id_auth_uaddr =
1630         (uint64_t)qbase64_decode(sev_snp_guest->id_auth, -1, &len, errp);
1631 
1632     if (!finish->id_auth_uaddr) {
1633         return;
1634     }
1635 
1636     if (len > KVM_SEV_SNP_ID_AUTH_SIZE) {
1637         error_setg(errp, "parameter length:ID_AUTH %lu exceeds max of %u",
1638                    len, KVM_SEV_SNP_ID_AUTH_SIZE);
1639         return;
1640     }
1641 }
1642 
1643 static bool
1644 sev_snp_guest_get_author_key_enabled(Object *obj, Error **errp)
1645 {
1646     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
1647 
1648     return !!sev_snp_guest->kvm_finish_conf.auth_key_en;
1649 }
1650 
1651 static void
1652 sev_snp_guest_set_author_key_enabled(Object *obj, bool value, Error **errp)
1653 {
1654     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
1655 
1656     sev_snp_guest->kvm_finish_conf.auth_key_en = value;
1657 }
1658 
1659 static bool
1660 sev_snp_guest_get_vcek_disabled(Object *obj, Error **errp)
1661 {
1662     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
1663 
1664     return !!sev_snp_guest->kvm_finish_conf.vcek_disabled;
1665 }
1666 
1667 static void
1668 sev_snp_guest_set_vcek_disabled(Object *obj, bool value, Error **errp)
1669 {
1670     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
1671 
1672     sev_snp_guest->kvm_finish_conf.vcek_disabled = value;
1673 }
1674 
1675 static char *
1676 sev_snp_guest_get_host_data(Object *obj, Error **errp)
1677 {
1678     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
1679 
1680     return g_strdup(sev_snp_guest->host_data);
1681 }
1682 
1683 static void
1684 sev_snp_guest_set_host_data(Object *obj, const char *value, Error **errp)
1685 {
1686     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
1687     struct kvm_sev_snp_launch_finish *finish = &sev_snp_guest->kvm_finish_conf;
1688     g_autofree guchar *blob;
1689     gsize len;
1690 
1691     g_free(sev_snp_guest->host_data);
1692 
1693     /* store the base64 str so we don't need to re-encode in getter */
1694     sev_snp_guest->host_data = g_strdup(value);
1695 
1696     blob = qbase64_decode(sev_snp_guest->host_data, -1, &len, errp);
1697 
1698     if (!blob) {
1699         return;
1700     }
1701 
1702     if (len != sizeof(finish->host_data)) {
1703         error_setg(errp, "parameter length of %lu not equal to %lu",
1704                    len, sizeof(finish->host_data));
1705         return;
1706     }
1707 
1708     memcpy(finish->host_data, blob, len);
1709 }
1710 
1711 static void
1712 sev_snp_guest_class_init(ObjectClass *oc, void *data)
1713 {
1714     object_class_property_add(oc, "policy", "uint64",
1715                               sev_snp_guest_get_policy,
1716                               sev_snp_guest_set_policy, NULL, NULL);
1717     object_class_property_add_str(oc, "guest-visible-workarounds",
1718                                   sev_snp_guest_get_guest_visible_workarounds,
1719                                   sev_snp_guest_set_guest_visible_workarounds);
1720     object_class_property_add_str(oc, "id-block",
1721                                   sev_snp_guest_get_id_block,
1722                                   sev_snp_guest_set_id_block);
1723     object_class_property_add_str(oc, "id-auth",
1724                                   sev_snp_guest_get_id_auth,
1725                                   sev_snp_guest_set_id_auth);
1726     object_class_property_add_bool(oc, "author-key-enabled",
1727                                    sev_snp_guest_get_author_key_enabled,
1728                                    sev_snp_guest_set_author_key_enabled);
1729     object_class_property_add_bool(oc, "vcek-required",
1730                                    sev_snp_guest_get_vcek_disabled,
1731                                    sev_snp_guest_set_vcek_disabled);
1732     object_class_property_add_str(oc, "host-data",
1733                                   sev_snp_guest_get_host_data,
1734                                   sev_snp_guest_set_host_data);
1735 }
1736 
1737 static void
1738 sev_snp_guest_instance_init(Object *obj)
1739 {
1740     SevSnpGuestState *sev_snp_guest = SEV_SNP_GUEST(obj);
1741 
1742     /* default init/start/finish params for kvm */
1743     sev_snp_guest->kvm_start_conf.policy = DEFAULT_SEV_SNP_POLICY;
1744 }
1745 
1746 /* guest info specific to sev-snp */
1747 static const TypeInfo sev_snp_guest_info = {
1748     .parent = TYPE_SEV_COMMON,
1749     .name = TYPE_SEV_SNP_GUEST,
1750     .instance_size = sizeof(SevSnpGuestState),
1751     .class_init = sev_snp_guest_class_init,
1752     .instance_init = sev_snp_guest_instance_init,
1753 };
1754 
1755 static void
1756 sev_register_types(void)
1757 {
1758     type_register_static(&sev_common_info);
1759     type_register_static(&sev_guest_info);
1760     type_register_static(&sev_snp_guest_info);
1761 }
1762 
1763 type_init(sev_register_types);
1764