xref: /openbmc/qemu/target/i386/sev.c (revision e3ae2bbf)
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 "crypto/hash.h"
27 #include "sysemu/kvm.h"
28 #include "sev.h"
29 #include "sysemu/sysemu.h"
30 #include "sysemu/runstate.h"
31 #include "trace.h"
32 #include "migration/blocker.h"
33 #include "qom/object.h"
34 #include "monitor/monitor.h"
35 #include "monitor/hmp-target.h"
36 #include "qapi/qapi-commands-misc-target.h"
37 #include "qapi/qmp/qerror.h"
38 #include "exec/confidential-guest-support.h"
39 #include "hw/i386/pc.h"
40 #include "exec/address-spaces.h"
41 
42 #define TYPE_SEV_GUEST "sev-guest"
43 OBJECT_DECLARE_SIMPLE_TYPE(SevGuestState, SEV_GUEST)
44 
45 
46 /**
47  * SevGuestState:
48  *
49  * The SevGuestState object is used for creating and managing a SEV
50  * guest.
51  *
52  * # $QEMU \
53  *         -object sev-guest,id=sev0 \
54  *         -machine ...,memory-encryption=sev0
55  */
56 struct SevGuestState {
57     ConfidentialGuestSupport parent_obj;
58 
59     /* configuration parameters */
60     char *sev_device;
61     uint32_t policy;
62     char *dh_cert_file;
63     char *session_file;
64     uint32_t cbitpos;
65     uint32_t reduced_phys_bits;
66     bool kernel_hashes;
67 
68     /* runtime state */
69     uint32_t handle;
70     uint8_t api_major;
71     uint8_t api_minor;
72     uint8_t build_id;
73     int sev_fd;
74     SevState state;
75     gchar *measurement;
76 
77     uint32_t reset_cs;
78     uint32_t reset_ip;
79     bool reset_data_valid;
80 };
81 
82 #define DEFAULT_GUEST_POLICY    0x1 /* disable debug */
83 #define DEFAULT_SEV_DEVICE      "/dev/sev"
84 
85 #define SEV_INFO_BLOCK_GUID     "00f771de-1a7e-4fcb-890e-68c77e2fb44e"
86 typedef struct __attribute__((__packed__)) SevInfoBlock {
87     /* SEV-ES Reset Vector Address */
88     uint32_t reset_addr;
89 } SevInfoBlock;
90 
91 #define SEV_HASH_TABLE_RV_GUID  "7255371f-3a3b-4b04-927b-1da6efa8d454"
92 typedef struct QEMU_PACKED SevHashTableDescriptor {
93     /* SEV hash table area guest address */
94     uint32_t base;
95     /* SEV hash table area size (in bytes) */
96     uint32_t size;
97 } SevHashTableDescriptor;
98 
99 /* hard code sha256 digest size */
100 #define HASH_SIZE 32
101 
102 typedef struct QEMU_PACKED SevHashTableEntry {
103     QemuUUID guid;
104     uint16_t len;
105     uint8_t hash[HASH_SIZE];
106 } SevHashTableEntry;
107 
108 typedef struct QEMU_PACKED SevHashTable {
109     QemuUUID guid;
110     uint16_t len;
111     SevHashTableEntry cmdline;
112     SevHashTableEntry initrd;
113     SevHashTableEntry kernel;
114 } SevHashTable;
115 
116 /*
117  * Data encrypted by sev_encrypt_flash() must be padded to a multiple of
118  * 16 bytes.
119  */
120 typedef struct QEMU_PACKED PaddedSevHashTable {
121     SevHashTable ht;
122     uint8_t padding[ROUND_UP(sizeof(SevHashTable), 16) - sizeof(SevHashTable)];
123 } PaddedSevHashTable;
124 
125 QEMU_BUILD_BUG_ON(sizeof(PaddedSevHashTable) % 16 != 0);
126 
127 static SevGuestState *sev_guest;
128 static Error *sev_mig_blocker;
129 
130 static const char *const sev_fw_errlist[] = {
131     [SEV_RET_SUCCESS]                = "",
132     [SEV_RET_INVALID_PLATFORM_STATE] = "Platform state is invalid",
133     [SEV_RET_INVALID_GUEST_STATE]    = "Guest state is invalid",
134     [SEV_RET_INAVLID_CONFIG]         = "Platform configuration is invalid",
135     [SEV_RET_INVALID_LEN]            = "Buffer too small",
136     [SEV_RET_ALREADY_OWNED]          = "Platform is already owned",
137     [SEV_RET_INVALID_CERTIFICATE]    = "Certificate is invalid",
138     [SEV_RET_POLICY_FAILURE]         = "Policy is not allowed",
139     [SEV_RET_INACTIVE]               = "Guest is not active",
140     [SEV_RET_INVALID_ADDRESS]        = "Invalid address",
141     [SEV_RET_BAD_SIGNATURE]          = "Bad signature",
142     [SEV_RET_BAD_MEASUREMENT]        = "Bad measurement",
143     [SEV_RET_ASID_OWNED]             = "ASID is already owned",
144     [SEV_RET_INVALID_ASID]           = "Invalid ASID",
145     [SEV_RET_WBINVD_REQUIRED]        = "WBINVD is required",
146     [SEV_RET_DFFLUSH_REQUIRED]       = "DF_FLUSH is required",
147     [SEV_RET_INVALID_GUEST]          = "Guest handle is invalid",
148     [SEV_RET_INVALID_COMMAND]        = "Invalid command",
149     [SEV_RET_ACTIVE]                 = "Guest is active",
150     [SEV_RET_HWSEV_RET_PLATFORM]     = "Hardware error",
151     [SEV_RET_HWSEV_RET_UNSAFE]       = "Hardware unsafe",
152     [SEV_RET_UNSUPPORTED]            = "Feature not supported",
153     [SEV_RET_INVALID_PARAM]          = "Invalid parameter",
154     [SEV_RET_RESOURCE_LIMIT]         = "Required firmware resource depleted",
155     [SEV_RET_SECURE_DATA_INVALID]    = "Part-specific integrity check failure",
156 };
157 
158 #define SEV_FW_MAX_ERROR      ARRAY_SIZE(sev_fw_errlist)
159 
160 static int
161 sev_ioctl(int fd, int cmd, void *data, int *error)
162 {
163     int r;
164     struct kvm_sev_cmd input;
165 
166     memset(&input, 0x0, sizeof(input));
167 
168     input.id = cmd;
169     input.sev_fd = fd;
170     input.data = (__u64)(unsigned long)data;
171 
172     r = kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_OP, &input);
173 
174     if (error) {
175         *error = input.error;
176     }
177 
178     return r;
179 }
180 
181 static int
182 sev_platform_ioctl(int fd, int cmd, void *data, int *error)
183 {
184     int r;
185     struct sev_issue_cmd arg;
186 
187     arg.cmd = cmd;
188     arg.data = (unsigned long)data;
189     r = ioctl(fd, SEV_ISSUE_CMD, &arg);
190     if (error) {
191         *error = arg.error;
192     }
193 
194     return r;
195 }
196 
197 static const char *
198 fw_error_to_str(int code)
199 {
200     if (code < 0 || code >= SEV_FW_MAX_ERROR) {
201         return "unknown error";
202     }
203 
204     return sev_fw_errlist[code];
205 }
206 
207 static bool
208 sev_check_state(const SevGuestState *sev, SevState state)
209 {
210     assert(sev);
211     return sev->state == state ? true : false;
212 }
213 
214 static void
215 sev_set_guest_state(SevGuestState *sev, SevState new_state)
216 {
217     assert(new_state < SEV_STATE__MAX);
218     assert(sev);
219 
220     trace_kvm_sev_change_state(SevState_str(sev->state),
221                                SevState_str(new_state));
222     sev->state = new_state;
223 }
224 
225 static void
226 sev_ram_block_added(RAMBlockNotifier *n, void *host, size_t size,
227                     size_t max_size)
228 {
229     int r;
230     struct kvm_enc_region range;
231     ram_addr_t offset;
232     MemoryRegion *mr;
233 
234     /*
235      * The RAM device presents a memory region that should be treated
236      * as IO region and should not be pinned.
237      */
238     mr = memory_region_from_host(host, &offset);
239     if (mr && memory_region_is_ram_device(mr)) {
240         return;
241     }
242 
243     range.addr = (__u64)(unsigned long)host;
244     range.size = max_size;
245 
246     trace_kvm_memcrypt_register_region(host, max_size);
247     r = kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_REG_REGION, &range);
248     if (r) {
249         error_report("%s: failed to register region (%p+%#zx) error '%s'",
250                      __func__, host, max_size, strerror(errno));
251         exit(1);
252     }
253 }
254 
255 static void
256 sev_ram_block_removed(RAMBlockNotifier *n, void *host, size_t size,
257                       size_t max_size)
258 {
259     int r;
260     struct kvm_enc_region range;
261     ram_addr_t offset;
262     MemoryRegion *mr;
263 
264     /*
265      * The RAM device presents a memory region that should be treated
266      * as IO region and should not have been pinned.
267      */
268     mr = memory_region_from_host(host, &offset);
269     if (mr && memory_region_is_ram_device(mr)) {
270         return;
271     }
272 
273     range.addr = (__u64)(unsigned long)host;
274     range.size = max_size;
275 
276     trace_kvm_memcrypt_unregister_region(host, max_size);
277     r = kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_UNREG_REGION, &range);
278     if (r) {
279         error_report("%s: failed to unregister region (%p+%#zx)",
280                      __func__, host, max_size);
281     }
282 }
283 
284 static struct RAMBlockNotifier sev_ram_notifier = {
285     .ram_block_added = sev_ram_block_added,
286     .ram_block_removed = sev_ram_block_removed,
287 };
288 
289 static void
290 sev_guest_finalize(Object *obj)
291 {
292 }
293 
294 static char *
295 sev_guest_get_session_file(Object *obj, Error **errp)
296 {
297     SevGuestState *s = SEV_GUEST(obj);
298 
299     return s->session_file ? g_strdup(s->session_file) : NULL;
300 }
301 
302 static void
303 sev_guest_set_session_file(Object *obj, const char *value, Error **errp)
304 {
305     SevGuestState *s = SEV_GUEST(obj);
306 
307     s->session_file = g_strdup(value);
308 }
309 
310 static char *
311 sev_guest_get_dh_cert_file(Object *obj, Error **errp)
312 {
313     SevGuestState *s = SEV_GUEST(obj);
314 
315     return g_strdup(s->dh_cert_file);
316 }
317 
318 static void
319 sev_guest_set_dh_cert_file(Object *obj, const char *value, Error **errp)
320 {
321     SevGuestState *s = SEV_GUEST(obj);
322 
323     s->dh_cert_file = g_strdup(value);
324 }
325 
326 static char *
327 sev_guest_get_sev_device(Object *obj, Error **errp)
328 {
329     SevGuestState *sev = SEV_GUEST(obj);
330 
331     return g_strdup(sev->sev_device);
332 }
333 
334 static void
335 sev_guest_set_sev_device(Object *obj, const char *value, Error **errp)
336 {
337     SevGuestState *sev = SEV_GUEST(obj);
338 
339     sev->sev_device = g_strdup(value);
340 }
341 
342 static bool sev_guest_get_kernel_hashes(Object *obj, Error **errp)
343 {
344     SevGuestState *sev = SEV_GUEST(obj);
345 
346     return sev->kernel_hashes;
347 }
348 
349 static void sev_guest_set_kernel_hashes(Object *obj, bool value, Error **errp)
350 {
351     SevGuestState *sev = SEV_GUEST(obj);
352 
353     sev->kernel_hashes = value;
354 }
355 
356 static void
357 sev_guest_class_init(ObjectClass *oc, void *data)
358 {
359     object_class_property_add_str(oc, "sev-device",
360                                   sev_guest_get_sev_device,
361                                   sev_guest_set_sev_device);
362     object_class_property_set_description(oc, "sev-device",
363             "SEV device to use");
364     object_class_property_add_str(oc, "dh-cert-file",
365                                   sev_guest_get_dh_cert_file,
366                                   sev_guest_set_dh_cert_file);
367     object_class_property_set_description(oc, "dh-cert-file",
368             "guest owners DH certificate (encoded with base64)");
369     object_class_property_add_str(oc, "session-file",
370                                   sev_guest_get_session_file,
371                                   sev_guest_set_session_file);
372     object_class_property_set_description(oc, "session-file",
373             "guest owners session parameters (encoded with base64)");
374     object_class_property_add_bool(oc, "kernel-hashes",
375                                    sev_guest_get_kernel_hashes,
376                                    sev_guest_set_kernel_hashes);
377     object_class_property_set_description(oc, "kernel-hashes",
378             "add kernel hashes to guest firmware for measured Linux boot");
379 }
380 
381 static void
382 sev_guest_instance_init(Object *obj)
383 {
384     SevGuestState *sev = SEV_GUEST(obj);
385 
386     sev->sev_device = g_strdup(DEFAULT_SEV_DEVICE);
387     sev->policy = DEFAULT_GUEST_POLICY;
388     object_property_add_uint32_ptr(obj, "policy", &sev->policy,
389                                    OBJ_PROP_FLAG_READWRITE);
390     object_property_add_uint32_ptr(obj, "handle", &sev->handle,
391                                    OBJ_PROP_FLAG_READWRITE);
392     object_property_add_uint32_ptr(obj, "cbitpos", &sev->cbitpos,
393                                    OBJ_PROP_FLAG_READWRITE);
394     object_property_add_uint32_ptr(obj, "reduced-phys-bits",
395                                    &sev->reduced_phys_bits,
396                                    OBJ_PROP_FLAG_READWRITE);
397 }
398 
399 /* sev guest info */
400 static const TypeInfo sev_guest_info = {
401     .parent = TYPE_CONFIDENTIAL_GUEST_SUPPORT,
402     .name = TYPE_SEV_GUEST,
403     .instance_size = sizeof(SevGuestState),
404     .instance_finalize = sev_guest_finalize,
405     .class_init = sev_guest_class_init,
406     .instance_init = sev_guest_instance_init,
407     .interfaces = (InterfaceInfo[]) {
408         { TYPE_USER_CREATABLE },
409         { }
410     }
411 };
412 
413 bool
414 sev_enabled(void)
415 {
416     return !!sev_guest;
417 }
418 
419 bool
420 sev_es_enabled(void)
421 {
422     return sev_enabled() && (sev_guest->policy & SEV_POLICY_ES);
423 }
424 
425 uint32_t
426 sev_get_cbit_position(void)
427 {
428     return sev_guest ? sev_guest->cbitpos : 0;
429 }
430 
431 uint32_t
432 sev_get_reduced_phys_bits(void)
433 {
434     return sev_guest ? sev_guest->reduced_phys_bits : 0;
435 }
436 
437 static SevInfo *sev_get_info(void)
438 {
439     SevInfo *info;
440 
441     info = g_new0(SevInfo, 1);
442     info->enabled = sev_enabled();
443 
444     if (info->enabled) {
445         info->api_major = sev_guest->api_major;
446         info->api_minor = sev_guest->api_minor;
447         info->build_id = sev_guest->build_id;
448         info->policy = sev_guest->policy;
449         info->state = sev_guest->state;
450         info->handle = sev_guest->handle;
451     }
452 
453     return info;
454 }
455 
456 SevInfo *qmp_query_sev(Error **errp)
457 {
458     SevInfo *info;
459 
460     info = sev_get_info();
461     if (!info) {
462         error_setg(errp, "SEV feature is not available");
463         return NULL;
464     }
465 
466     return info;
467 }
468 
469 void hmp_info_sev(Monitor *mon, const QDict *qdict)
470 {
471     SevInfo *info = sev_get_info();
472 
473     if (info && info->enabled) {
474         monitor_printf(mon, "handle: %d\n", info->handle);
475         monitor_printf(mon, "state: %s\n", SevState_str(info->state));
476         monitor_printf(mon, "build: %d\n", info->build_id);
477         monitor_printf(mon, "api version: %d.%d\n",
478                        info->api_major, info->api_minor);
479         monitor_printf(mon, "debug: %s\n",
480                        info->policy & SEV_POLICY_NODBG ? "off" : "on");
481         monitor_printf(mon, "key-sharing: %s\n",
482                        info->policy & SEV_POLICY_NOKS ? "off" : "on");
483     } else {
484         monitor_printf(mon, "SEV is not enabled\n");
485     }
486 
487     qapi_free_SevInfo(info);
488 }
489 
490 static int
491 sev_get_pdh_info(int fd, guchar **pdh, size_t *pdh_len, guchar **cert_chain,
492                  size_t *cert_chain_len, Error **errp)
493 {
494     guchar *pdh_data = NULL;
495     guchar *cert_chain_data = NULL;
496     struct sev_user_data_pdh_cert_export export = {};
497     int err, r;
498 
499     /* query the certificate length */
500     r = sev_platform_ioctl(fd, SEV_PDH_CERT_EXPORT, &export, &err);
501     if (r < 0) {
502         if (err != SEV_RET_INVALID_LEN) {
503             error_setg(errp, "SEV: Failed to export PDH cert"
504                              " ret=%d fw_err=%d (%s)",
505                        r, err, fw_error_to_str(err));
506             return 1;
507         }
508     }
509 
510     pdh_data = g_new(guchar, export.pdh_cert_len);
511     cert_chain_data = g_new(guchar, export.cert_chain_len);
512     export.pdh_cert_address = (unsigned long)pdh_data;
513     export.cert_chain_address = (unsigned long)cert_chain_data;
514 
515     r = sev_platform_ioctl(fd, SEV_PDH_CERT_EXPORT, &export, &err);
516     if (r < 0) {
517         error_setg(errp, "SEV: Failed to export PDH cert ret=%d fw_err=%d (%s)",
518                    r, err, fw_error_to_str(err));
519         goto e_free;
520     }
521 
522     *pdh = pdh_data;
523     *pdh_len = export.pdh_cert_len;
524     *cert_chain = cert_chain_data;
525     *cert_chain_len = export.cert_chain_len;
526     return 0;
527 
528 e_free:
529     g_free(pdh_data);
530     g_free(cert_chain_data);
531     return 1;
532 }
533 
534 static SevCapability *sev_get_capabilities(Error **errp)
535 {
536     SevCapability *cap = NULL;
537     guchar *pdh_data = NULL;
538     guchar *cert_chain_data = NULL;
539     size_t pdh_len = 0, cert_chain_len = 0;
540     uint32_t ebx;
541     int fd;
542 
543     if (!kvm_enabled()) {
544         error_setg(errp, "KVM not enabled");
545         return NULL;
546     }
547     if (kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_OP, NULL) < 0) {
548         error_setg(errp, "SEV is not enabled in KVM");
549         return NULL;
550     }
551 
552     fd = open(DEFAULT_SEV_DEVICE, O_RDWR);
553     if (fd < 0) {
554         error_setg_errno(errp, errno, "SEV: Failed to open %s",
555                          DEFAULT_SEV_DEVICE);
556         return NULL;
557     }
558 
559     if (sev_get_pdh_info(fd, &pdh_data, &pdh_len,
560                          &cert_chain_data, &cert_chain_len, errp)) {
561         goto out;
562     }
563 
564     cap = g_new0(SevCapability, 1);
565     cap->pdh = g_base64_encode(pdh_data, pdh_len);
566     cap->cert_chain = g_base64_encode(cert_chain_data, cert_chain_len);
567 
568     host_cpuid(0x8000001F, 0, NULL, &ebx, NULL, NULL);
569     cap->cbitpos = ebx & 0x3f;
570 
571     /*
572      * When SEV feature is enabled, we loose one bit in guest physical
573      * addressing.
574      */
575     cap->reduced_phys_bits = 1;
576 
577 out:
578     g_free(pdh_data);
579     g_free(cert_chain_data);
580     close(fd);
581     return cap;
582 }
583 
584 SevCapability *qmp_query_sev_capabilities(Error **errp)
585 {
586     return sev_get_capabilities(errp);
587 }
588 
589 static SevAttestationReport *sev_get_attestation_report(const char *mnonce,
590                                                         Error **errp)
591 {
592     struct kvm_sev_attestation_report input = {};
593     SevAttestationReport *report = NULL;
594     SevGuestState *sev = sev_guest;
595     g_autofree guchar *data = NULL;
596     g_autofree guchar *buf = NULL;
597     gsize len;
598     int err = 0, ret;
599 
600     if (!sev_enabled()) {
601         error_setg(errp, "SEV is not enabled");
602         return NULL;
603     }
604 
605     /* lets decode the mnonce string */
606     buf = g_base64_decode(mnonce, &len);
607     if (!buf) {
608         error_setg(errp, "SEV: failed to decode mnonce input");
609         return NULL;
610     }
611 
612     /* verify the input mnonce length */
613     if (len != sizeof(input.mnonce)) {
614         error_setg(errp, "SEV: mnonce must be %zu bytes (got %" G_GSIZE_FORMAT ")",
615                 sizeof(input.mnonce), len);
616         return NULL;
617     }
618 
619     /* Query the report length */
620     ret = sev_ioctl(sev->sev_fd, KVM_SEV_GET_ATTESTATION_REPORT,
621             &input, &err);
622     if (ret < 0) {
623         if (err != SEV_RET_INVALID_LEN) {
624             error_setg(errp, "SEV: Failed to query the attestation report"
625                              " length ret=%d fw_err=%d (%s)",
626                        ret, err, fw_error_to_str(err));
627             return NULL;
628         }
629     }
630 
631     data = g_malloc(input.len);
632     input.uaddr = (unsigned long)data;
633     memcpy(input.mnonce, buf, sizeof(input.mnonce));
634 
635     /* Query the report */
636     ret = sev_ioctl(sev->sev_fd, KVM_SEV_GET_ATTESTATION_REPORT,
637             &input, &err);
638     if (ret) {
639         error_setg_errno(errp, errno, "SEV: Failed to get attestation report"
640                 " ret=%d fw_err=%d (%s)", ret, err, fw_error_to_str(err));
641         return NULL;
642     }
643 
644     report = g_new0(SevAttestationReport, 1);
645     report->data = g_base64_encode(data, input.len);
646 
647     trace_kvm_sev_attestation_report(mnonce, report->data);
648 
649     return report;
650 }
651 
652 SevAttestationReport *qmp_query_sev_attestation_report(const char *mnonce,
653                                                        Error **errp)
654 {
655     return sev_get_attestation_report(mnonce, errp);
656 }
657 
658 static int
659 sev_read_file_base64(const char *filename, guchar **data, gsize *len)
660 {
661     gsize sz;
662     g_autofree gchar *base64 = NULL;
663     GError *error = NULL;
664 
665     if (!g_file_get_contents(filename, &base64, &sz, &error)) {
666         error_report("SEV: Failed to read '%s' (%s)", filename, error->message);
667         g_error_free(error);
668         return -1;
669     }
670 
671     *data = g_base64_decode(base64, len);
672     return 0;
673 }
674 
675 static int
676 sev_launch_start(SevGuestState *sev)
677 {
678     gsize sz;
679     int ret = 1;
680     int fw_error, rc;
681     struct kvm_sev_launch_start start = {
682         .handle = sev->handle, .policy = sev->policy
683     };
684     guchar *session = NULL, *dh_cert = NULL;
685 
686     if (sev->session_file) {
687         if (sev_read_file_base64(sev->session_file, &session, &sz) < 0) {
688             goto out;
689         }
690         start.session_uaddr = (unsigned long)session;
691         start.session_len = sz;
692     }
693 
694     if (sev->dh_cert_file) {
695         if (sev_read_file_base64(sev->dh_cert_file, &dh_cert, &sz) < 0) {
696             goto out;
697         }
698         start.dh_uaddr = (unsigned long)dh_cert;
699         start.dh_len = sz;
700     }
701 
702     trace_kvm_sev_launch_start(start.policy, session, dh_cert);
703     rc = sev_ioctl(sev->sev_fd, KVM_SEV_LAUNCH_START, &start, &fw_error);
704     if (rc < 0) {
705         error_report("%s: LAUNCH_START ret=%d fw_error=%d '%s'",
706                 __func__, ret, fw_error, fw_error_to_str(fw_error));
707         goto out;
708     }
709 
710     sev_set_guest_state(sev, SEV_STATE_LAUNCH_UPDATE);
711     sev->handle = start.handle;
712     ret = 0;
713 
714 out:
715     g_free(session);
716     g_free(dh_cert);
717     return ret;
718 }
719 
720 static int
721 sev_launch_update_data(SevGuestState *sev, uint8_t *addr, uint64_t len)
722 {
723     int ret, fw_error;
724     struct kvm_sev_launch_update_data update;
725 
726     if (!addr || !len) {
727         return 1;
728     }
729 
730     update.uaddr = (__u64)(unsigned long)addr;
731     update.len = len;
732     trace_kvm_sev_launch_update_data(addr, len);
733     ret = sev_ioctl(sev->sev_fd, KVM_SEV_LAUNCH_UPDATE_DATA,
734                     &update, &fw_error);
735     if (ret) {
736         error_report("%s: LAUNCH_UPDATE ret=%d fw_error=%d '%s'",
737                 __func__, ret, fw_error, fw_error_to_str(fw_error));
738     }
739 
740     return ret;
741 }
742 
743 static int
744 sev_launch_update_vmsa(SevGuestState *sev)
745 {
746     int ret, fw_error;
747 
748     ret = sev_ioctl(sev->sev_fd, KVM_SEV_LAUNCH_UPDATE_VMSA, NULL, &fw_error);
749     if (ret) {
750         error_report("%s: LAUNCH_UPDATE_VMSA ret=%d fw_error=%d '%s'",
751                 __func__, ret, fw_error, fw_error_to_str(fw_error));
752     }
753 
754     return ret;
755 }
756 
757 static void
758 sev_launch_get_measure(Notifier *notifier, void *unused)
759 {
760     SevGuestState *sev = sev_guest;
761     int ret, error;
762     g_autofree guchar *data = NULL;
763     struct kvm_sev_launch_measure measurement = {};
764 
765     if (!sev_check_state(sev, SEV_STATE_LAUNCH_UPDATE)) {
766         return;
767     }
768 
769     if (sev_es_enabled()) {
770         /* measure all the VM save areas before getting launch_measure */
771         ret = sev_launch_update_vmsa(sev);
772         if (ret) {
773             exit(1);
774         }
775     }
776 
777     /* query the measurement blob length */
778     ret = sev_ioctl(sev->sev_fd, KVM_SEV_LAUNCH_MEASURE,
779                     &measurement, &error);
780     if (!measurement.len) {
781         error_report("%s: LAUNCH_MEASURE ret=%d fw_error=%d '%s'",
782                      __func__, ret, error, fw_error_to_str(errno));
783         return;
784     }
785 
786     data = g_new0(guchar, measurement.len);
787     measurement.uaddr = (unsigned long)data;
788 
789     /* get the measurement blob */
790     ret = sev_ioctl(sev->sev_fd, KVM_SEV_LAUNCH_MEASURE,
791                     &measurement, &error);
792     if (ret) {
793         error_report("%s: LAUNCH_MEASURE ret=%d fw_error=%d '%s'",
794                      __func__, ret, error, fw_error_to_str(errno));
795         return;
796     }
797 
798     sev_set_guest_state(sev, SEV_STATE_LAUNCH_SECRET);
799 
800     /* encode the measurement value and emit the event */
801     sev->measurement = g_base64_encode(data, measurement.len);
802     trace_kvm_sev_launch_measurement(sev->measurement);
803 }
804 
805 static char *sev_get_launch_measurement(void)
806 {
807     if (sev_guest &&
808         sev_guest->state >= SEV_STATE_LAUNCH_SECRET) {
809         return g_strdup(sev_guest->measurement);
810     }
811 
812     return NULL;
813 }
814 
815 SevLaunchMeasureInfo *qmp_query_sev_launch_measure(Error **errp)
816 {
817     char *data;
818     SevLaunchMeasureInfo *info;
819 
820     data = sev_get_launch_measurement();
821     if (!data) {
822         error_setg(errp, "SEV launch measurement is not available");
823         return NULL;
824     }
825 
826     info = g_malloc0(sizeof(*info));
827     info->data = data;
828 
829     return info;
830 }
831 
832 static Notifier sev_machine_done_notify = {
833     .notify = sev_launch_get_measure,
834 };
835 
836 static void
837 sev_launch_finish(SevGuestState *sev)
838 {
839     int ret, error;
840 
841     trace_kvm_sev_launch_finish();
842     ret = sev_ioctl(sev->sev_fd, KVM_SEV_LAUNCH_FINISH, 0, &error);
843     if (ret) {
844         error_report("%s: LAUNCH_FINISH ret=%d fw_error=%d '%s'",
845                      __func__, ret, error, fw_error_to_str(error));
846         exit(1);
847     }
848 
849     sev_set_guest_state(sev, SEV_STATE_RUNNING);
850 
851     /* add migration blocker */
852     error_setg(&sev_mig_blocker,
853                "SEV: Migration is not implemented");
854     migrate_add_blocker(sev_mig_blocker, &error_fatal);
855 }
856 
857 static void
858 sev_vm_state_change(void *opaque, bool running, RunState state)
859 {
860     SevGuestState *sev = opaque;
861 
862     if (running) {
863         if (!sev_check_state(sev, SEV_STATE_RUNNING)) {
864             sev_launch_finish(sev);
865         }
866     }
867 }
868 
869 int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
870 {
871     SevGuestState *sev
872         = (SevGuestState *)object_dynamic_cast(OBJECT(cgs), TYPE_SEV_GUEST);
873     char *devname;
874     int ret, fw_error, cmd;
875     uint32_t ebx;
876     uint32_t host_cbitpos;
877     struct sev_user_data_status status = {};
878 
879     if (!sev) {
880         return 0;
881     }
882 
883     ret = ram_block_discard_disable(true);
884     if (ret) {
885         error_report("%s: cannot disable RAM discard", __func__);
886         return -1;
887     }
888 
889     sev_guest = sev;
890     sev->state = SEV_STATE_UNINIT;
891 
892     host_cpuid(0x8000001F, 0, NULL, &ebx, NULL, NULL);
893     host_cbitpos = ebx & 0x3f;
894 
895     if (host_cbitpos != sev->cbitpos) {
896         error_setg(errp, "%s: cbitpos check failed, host '%d' requested '%d'",
897                    __func__, host_cbitpos, sev->cbitpos);
898         goto err;
899     }
900 
901     if (sev->reduced_phys_bits < 1) {
902         error_setg(errp, "%s: reduced_phys_bits check failed, it should be >=1,"
903                    " requested '%d'", __func__, sev->reduced_phys_bits);
904         goto err;
905     }
906 
907     devname = object_property_get_str(OBJECT(sev), "sev-device", NULL);
908     sev->sev_fd = open(devname, O_RDWR);
909     if (sev->sev_fd < 0) {
910         error_setg(errp, "%s: Failed to open %s '%s'", __func__,
911                    devname, strerror(errno));
912         g_free(devname);
913         goto err;
914     }
915     g_free(devname);
916 
917     ret = sev_platform_ioctl(sev->sev_fd, SEV_PLATFORM_STATUS, &status,
918                              &fw_error);
919     if (ret) {
920         error_setg(errp, "%s: failed to get platform status ret=%d "
921                    "fw_error='%d: %s'", __func__, ret, fw_error,
922                    fw_error_to_str(fw_error));
923         goto err;
924     }
925     sev->build_id = status.build;
926     sev->api_major = status.api_major;
927     sev->api_minor = status.api_minor;
928 
929     if (sev_es_enabled()) {
930         if (!kvm_kernel_irqchip_allowed()) {
931             error_report("%s: SEV-ES guests require in-kernel irqchip support",
932                          __func__);
933             goto err;
934         }
935 
936         if (!(status.flags & SEV_STATUS_FLAGS_CONFIG_ES)) {
937             error_report("%s: guest policy requires SEV-ES, but "
938                          "host SEV-ES support unavailable",
939                          __func__);
940             goto err;
941         }
942         cmd = KVM_SEV_ES_INIT;
943     } else {
944         cmd = KVM_SEV_INIT;
945     }
946 
947     trace_kvm_sev_init();
948     ret = sev_ioctl(sev->sev_fd, cmd, NULL, &fw_error);
949     if (ret) {
950         error_setg(errp, "%s: failed to initialize ret=%d fw_error=%d '%s'",
951                    __func__, ret, fw_error, fw_error_to_str(fw_error));
952         goto err;
953     }
954 
955     ret = sev_launch_start(sev);
956     if (ret) {
957         error_setg(errp, "%s: failed to create encryption context", __func__);
958         goto err;
959     }
960 
961     ram_block_notifier_add(&sev_ram_notifier);
962     qemu_add_machine_init_done_notifier(&sev_machine_done_notify);
963     qemu_add_vm_change_state_handler(sev_vm_state_change, sev);
964 
965     cgs->ready = true;
966 
967     return 0;
968 err:
969     sev_guest = NULL;
970     ram_block_discard_disable(false);
971     return -1;
972 }
973 
974 int
975 sev_encrypt_flash(uint8_t *ptr, uint64_t len, Error **errp)
976 {
977     if (!sev_guest) {
978         return 0;
979     }
980 
981     /* if SEV is in update state then encrypt the data else do nothing */
982     if (sev_check_state(sev_guest, SEV_STATE_LAUNCH_UPDATE)) {
983         int ret = sev_launch_update_data(sev_guest, ptr, len);
984         if (ret < 0) {
985             error_setg(errp, "SEV: Failed to encrypt pflash rom");
986             return ret;
987         }
988     }
989 
990     return 0;
991 }
992 
993 int sev_inject_launch_secret(const char *packet_hdr, const char *secret,
994                              uint64_t gpa, Error **errp)
995 {
996     struct kvm_sev_launch_secret input;
997     g_autofree guchar *data = NULL, *hdr = NULL;
998     int error, ret = 1;
999     void *hva;
1000     gsize hdr_sz = 0, data_sz = 0;
1001     MemoryRegion *mr = NULL;
1002 
1003     if (!sev_guest) {
1004         error_setg(errp, "SEV not enabled for guest");
1005         return 1;
1006     }
1007 
1008     /* secret can be injected only in this state */
1009     if (!sev_check_state(sev_guest, SEV_STATE_LAUNCH_SECRET)) {
1010         error_setg(errp, "SEV: Not in correct state. (LSECRET) %x",
1011                      sev_guest->state);
1012         return 1;
1013     }
1014 
1015     hdr = g_base64_decode(packet_hdr, &hdr_sz);
1016     if (!hdr || !hdr_sz) {
1017         error_setg(errp, "SEV: Failed to decode sequence header");
1018         return 1;
1019     }
1020 
1021     data = g_base64_decode(secret, &data_sz);
1022     if (!data || !data_sz) {
1023         error_setg(errp, "SEV: Failed to decode data");
1024         return 1;
1025     }
1026 
1027     hva = gpa2hva(&mr, gpa, data_sz, errp);
1028     if (!hva) {
1029         error_prepend(errp, "SEV: Failed to calculate guest address: ");
1030         return 1;
1031     }
1032 
1033     input.hdr_uaddr = (uint64_t)(unsigned long)hdr;
1034     input.hdr_len = hdr_sz;
1035 
1036     input.trans_uaddr = (uint64_t)(unsigned long)data;
1037     input.trans_len = data_sz;
1038 
1039     input.guest_uaddr = (uint64_t)(unsigned long)hva;
1040     input.guest_len = data_sz;
1041 
1042     trace_kvm_sev_launch_secret(gpa, input.guest_uaddr,
1043                                 input.trans_uaddr, input.trans_len);
1044 
1045     ret = sev_ioctl(sev_guest->sev_fd, KVM_SEV_LAUNCH_SECRET,
1046                     &input, &error);
1047     if (ret) {
1048         error_setg(errp, "SEV: failed to inject secret ret=%d fw_error=%d '%s'",
1049                      ret, error, fw_error_to_str(error));
1050         return ret;
1051     }
1052 
1053     return 0;
1054 }
1055 
1056 #define SEV_SECRET_GUID "4c2eb361-7d9b-4cc3-8081-127c90d3d294"
1057 struct sev_secret_area {
1058     uint32_t base;
1059     uint32_t size;
1060 };
1061 
1062 void qmp_sev_inject_launch_secret(const char *packet_hdr,
1063                                   const char *secret,
1064                                   bool has_gpa, uint64_t gpa,
1065                                   Error **errp)
1066 {
1067     if (!sev_enabled()) {
1068         error_setg(errp, "SEV not enabled for guest");
1069         return;
1070     }
1071     if (!has_gpa) {
1072         uint8_t *data;
1073         struct sev_secret_area *area;
1074 
1075         if (!pc_system_ovmf_table_find(SEV_SECRET_GUID, &data, NULL)) {
1076             error_setg(errp, "SEV: no secret area found in OVMF,"
1077                        " gpa must be specified.");
1078             return;
1079         }
1080         area = (struct sev_secret_area *)data;
1081         gpa = area->base;
1082     }
1083 
1084     sev_inject_launch_secret(packet_hdr, secret, gpa, errp);
1085 }
1086 
1087 static int
1088 sev_es_parse_reset_block(SevInfoBlock *info, uint32_t *addr)
1089 {
1090     if (!info->reset_addr) {
1091         error_report("SEV-ES reset address is zero");
1092         return 1;
1093     }
1094 
1095     *addr = info->reset_addr;
1096 
1097     return 0;
1098 }
1099 
1100 static int
1101 sev_es_find_reset_vector(void *flash_ptr, uint64_t flash_size,
1102                          uint32_t *addr)
1103 {
1104     QemuUUID info_guid, *guid;
1105     SevInfoBlock *info;
1106     uint8_t *data;
1107     uint16_t *len;
1108 
1109     /*
1110      * Initialize the address to zero. An address of zero with a successful
1111      * return code indicates that SEV-ES is not active.
1112      */
1113     *addr = 0;
1114 
1115     /*
1116      * Extract the AP reset vector for SEV-ES guests by locating the SEV GUID.
1117      * The SEV GUID is located on its own (original implementation) or within
1118      * the Firmware GUID Table (new implementation), either of which are
1119      * located 32 bytes from the end of the flash.
1120      *
1121      * Check the Firmware GUID Table first.
1122      */
1123     if (pc_system_ovmf_table_find(SEV_INFO_BLOCK_GUID, &data, NULL)) {
1124         return sev_es_parse_reset_block((SevInfoBlock *)data, addr);
1125     }
1126 
1127     /*
1128      * SEV info block not found in the Firmware GUID Table (or there isn't
1129      * a Firmware GUID Table), fall back to the original implementation.
1130      */
1131     data = flash_ptr + flash_size - 0x20;
1132 
1133     qemu_uuid_parse(SEV_INFO_BLOCK_GUID, &info_guid);
1134     info_guid = qemu_uuid_bswap(info_guid); /* GUIDs are LE */
1135 
1136     guid = (QemuUUID *)(data - sizeof(info_guid));
1137     if (!qemu_uuid_is_equal(guid, &info_guid)) {
1138         error_report("SEV information block/Firmware GUID Table block not found in pflash rom");
1139         return 1;
1140     }
1141 
1142     len = (uint16_t *)((uint8_t *)guid - sizeof(*len));
1143     info = (SevInfoBlock *)(data - le16_to_cpu(*len));
1144 
1145     return sev_es_parse_reset_block(info, addr);
1146 }
1147 
1148 void sev_es_set_reset_vector(CPUState *cpu)
1149 {
1150     X86CPU *x86;
1151     CPUX86State *env;
1152 
1153     /* Only update if we have valid reset information */
1154     if (!sev_guest || !sev_guest->reset_data_valid) {
1155         return;
1156     }
1157 
1158     /* Do not update the BSP reset state */
1159     if (cpu->cpu_index == 0) {
1160         return;
1161     }
1162 
1163     x86 = X86_CPU(cpu);
1164     env = &x86->env;
1165 
1166     cpu_x86_load_seg_cache(env, R_CS, 0xf000, sev_guest->reset_cs, 0xffff,
1167                            DESC_P_MASK | DESC_S_MASK | DESC_CS_MASK |
1168                            DESC_R_MASK | DESC_A_MASK);
1169 
1170     env->eip = sev_guest->reset_ip;
1171 }
1172 
1173 int sev_es_save_reset_vector(void *flash_ptr, uint64_t flash_size)
1174 {
1175     CPUState *cpu;
1176     uint32_t addr;
1177     int ret;
1178 
1179     if (!sev_es_enabled()) {
1180         return 0;
1181     }
1182 
1183     addr = 0;
1184     ret = sev_es_find_reset_vector(flash_ptr, flash_size,
1185                                    &addr);
1186     if (ret) {
1187         return ret;
1188     }
1189 
1190     if (addr) {
1191         sev_guest->reset_cs = addr & 0xffff0000;
1192         sev_guest->reset_ip = addr & 0x0000ffff;
1193         sev_guest->reset_data_valid = true;
1194 
1195         CPU_FOREACH(cpu) {
1196             sev_es_set_reset_vector(cpu);
1197         }
1198     }
1199 
1200     return 0;
1201 }
1202 
1203 static const QemuUUID sev_hash_table_header_guid = {
1204     .data = UUID_LE(0x9438d606, 0x4f22, 0x4cc9, 0xb4, 0x79, 0xa7, 0x93,
1205                     0xd4, 0x11, 0xfd, 0x21)
1206 };
1207 
1208 static const QemuUUID sev_kernel_entry_guid = {
1209     .data = UUID_LE(0x4de79437, 0xabd2, 0x427f, 0xb8, 0x35, 0xd5, 0xb1,
1210                     0x72, 0xd2, 0x04, 0x5b)
1211 };
1212 static const QemuUUID sev_initrd_entry_guid = {
1213     .data = UUID_LE(0x44baf731, 0x3a2f, 0x4bd7, 0x9a, 0xf1, 0x41, 0xe2,
1214                     0x91, 0x69, 0x78, 0x1d)
1215 };
1216 static const QemuUUID sev_cmdline_entry_guid = {
1217     .data = UUID_LE(0x97d02dd8, 0xbd20, 0x4c94, 0xaa, 0x78, 0xe7, 0x71,
1218                     0x4d, 0x36, 0xab, 0x2a)
1219 };
1220 
1221 /*
1222  * Add the hashes of the linux kernel/initrd/cmdline to an encrypted guest page
1223  * which is included in SEV's initial memory measurement.
1224  */
1225 bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp)
1226 {
1227     uint8_t *data;
1228     SevHashTableDescriptor *area;
1229     SevHashTable *ht;
1230     PaddedSevHashTable *padded_ht;
1231     uint8_t cmdline_hash[HASH_SIZE];
1232     uint8_t initrd_hash[HASH_SIZE];
1233     uint8_t kernel_hash[HASH_SIZE];
1234     uint8_t *hashp;
1235     size_t hash_len = HASH_SIZE;
1236     hwaddr mapped_len = sizeof(*padded_ht);
1237     MemTxAttrs attrs = { 0 };
1238     bool ret = true;
1239 
1240     /*
1241      * Only add the kernel hashes if the sev-guest configuration explicitly
1242      * stated kernel-hashes=on.
1243      */
1244     if (!sev_guest->kernel_hashes) {
1245         return false;
1246     }
1247 
1248     if (!pc_system_ovmf_table_find(SEV_HASH_TABLE_RV_GUID, &data, NULL)) {
1249         error_setg(errp, "SEV: kernel specified but guest firmware "
1250                          "has no hashes table GUID");
1251         return false;
1252     }
1253     area = (SevHashTableDescriptor *)data;
1254     if (!area->base || area->size < sizeof(PaddedSevHashTable)) {
1255         error_setg(errp, "SEV: guest firmware hashes table area is invalid "
1256                          "(base=0x%x size=0x%x)", area->base, area->size);
1257         return false;
1258     }
1259 
1260     /*
1261      * Calculate hash of kernel command-line with the terminating null byte. If
1262      * the user doesn't supply a command-line via -append, the 1-byte "\0" will
1263      * be used.
1264      */
1265     hashp = cmdline_hash;
1266     if (qcrypto_hash_bytes(QCRYPTO_HASH_ALG_SHA256, ctx->cmdline_data,
1267                            ctx->cmdline_size, &hashp, &hash_len, errp) < 0) {
1268         return false;
1269     }
1270     assert(hash_len == HASH_SIZE);
1271 
1272     /*
1273      * Calculate hash of initrd. If the user doesn't supply an initrd via
1274      * -initrd, an empty buffer will be used (ctx->initrd_size == 0).
1275      */
1276     hashp = initrd_hash;
1277     if (qcrypto_hash_bytes(QCRYPTO_HASH_ALG_SHA256, ctx->initrd_data,
1278                            ctx->initrd_size, &hashp, &hash_len, errp) < 0) {
1279         return false;
1280     }
1281     assert(hash_len == HASH_SIZE);
1282 
1283     /* Calculate hash of the kernel */
1284     hashp = kernel_hash;
1285     struct iovec iov[2] = {
1286         { .iov_base = ctx->setup_data, .iov_len = ctx->setup_size },
1287         { .iov_base = ctx->kernel_data, .iov_len = ctx->kernel_size }
1288     };
1289     if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256, iov, ARRAY_SIZE(iov),
1290                             &hashp, &hash_len, errp) < 0) {
1291         return false;
1292     }
1293     assert(hash_len == HASH_SIZE);
1294 
1295     /*
1296      * Populate the hashes table in the guest's memory at the OVMF-designated
1297      * area for the SEV hashes table
1298      */
1299     padded_ht = address_space_map(&address_space_memory, area->base,
1300                                   &mapped_len, true, attrs);
1301     if (!padded_ht || mapped_len != sizeof(*padded_ht)) {
1302         error_setg(errp, "SEV: cannot map hashes table guest memory area");
1303         return false;
1304     }
1305     ht = &padded_ht->ht;
1306 
1307     ht->guid = sev_hash_table_header_guid;
1308     ht->len = sizeof(*ht);
1309 
1310     ht->cmdline.guid = sev_cmdline_entry_guid;
1311     ht->cmdline.len = sizeof(ht->cmdline);
1312     memcpy(ht->cmdline.hash, cmdline_hash, sizeof(ht->cmdline.hash));
1313 
1314     ht->initrd.guid = sev_initrd_entry_guid;
1315     ht->initrd.len = sizeof(ht->initrd);
1316     memcpy(ht->initrd.hash, initrd_hash, sizeof(ht->initrd.hash));
1317 
1318     ht->kernel.guid = sev_kernel_entry_guid;
1319     ht->kernel.len = sizeof(ht->kernel);
1320     memcpy(ht->kernel.hash, kernel_hash, sizeof(ht->kernel.hash));
1321 
1322     /* zero the excess data so the measurement can be reliably calculated */
1323     memset(padded_ht->padding, 0, sizeof(padded_ht->padding));
1324 
1325     if (sev_encrypt_flash((uint8_t *)padded_ht, sizeof(*padded_ht), errp) < 0) {
1326         ret = false;
1327     }
1328 
1329     address_space_unmap(&address_space_memory, padded_ht,
1330                         mapped_len, true, mapped_len);
1331 
1332     return ret;
1333 }
1334 
1335 static void
1336 sev_register_types(void)
1337 {
1338     type_register_static(&sev_guest_info);
1339 }
1340 
1341 type_init(sev_register_types);
1342