]> git.proxmox.com Git - mirror_qemu.git/blame - target/i386/sev.c
migration: simplify blockers
[mirror_qemu.git] / target / i386 / sev.c
CommitLineData
a9b4942f
BS
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
b7d89466
MA
14#include "qemu/osdep.h"
15
d8575c6c
BS
16#include <linux/kvm.h>
17#include <linux/psp-sev.h>
18
19#include <sys/ioctl.h>
20
a9b4942f
BS
21#include "qapi/error.h"
22#include "qom/object_interfaces.h"
23#include "qemu/base64.h"
0b8fa32f 24#include "qemu/module.h"
b2f73a07 25#include "qemu/uuid.h"
cc37d98b 26#include "qemu/error-report.h"
cff03145 27#include "crypto/hash.h"
a9b4942f 28#include "sysemu/kvm.h"
93777de3 29#include "sev.h"
a9b4942f 30#include "sysemu/sysemu.h"
54d31236 31#include "sysemu/runstate.h"
d8575c6c 32#include "trace.h"
8fa4466d 33#include "migration/blocker.h"
db1015e9 34#include "qom/object.h"
c7f7e697 35#include "monitor/monitor.h"
cd35beb4 36#include "monitor/hmp-target.h"
3208de1c 37#include "qapi/qapi-commands-misc-target.h"
f91f9f25 38#include "exec/confidential-guest-support.h"
b2f73a07 39#include "hw/i386/pc.h"
58603ba2 40#include "exec/address-spaces.h"
a9b4942f 41
d2d8a198 42#define TYPE_SEV_GUEST "sev-guest"
8063396b 43OBJECT_DECLARE_SIMPLE_TYPE(SevGuestState, SEV_GUEST)
a86ab19d 44
a86ab19d
DG
45
46/**
d2d8a198 47 * SevGuestState:
a86ab19d 48 *
d2d8a198
DG
49 * The SevGuestState object is used for creating and managing a SEV
50 * guest.
a86ab19d
DG
51 *
52 * # $QEMU \
53 * -object sev-guest,id=sev0 \
54 * -machine ...,memory-encryption=sev0
55 */
d2d8a198 56struct SevGuestState {
f91f9f25 57 ConfidentialGuestSupport parent_obj;
a86ab19d 58
75a877e3 59 /* configuration parameters */
a86ab19d
DG
60 char *sev_device;
61 uint32_t policy;
a86ab19d
DG
62 char *dh_cert_file;
63 char *session_file;
64 uint32_t cbitpos;
65 uint32_t reduced_phys_bits;
55cdf566 66 bool kernel_hashes;
a86ab19d 67
75a877e3 68 /* runtime state */
cf504cd6 69 uint32_t handle;
421522eb
DG
70 uint8_t api_major;
71 uint8_t api_minor;
72 uint8_t build_id;
421522eb
DG
73 int sev_fd;
74 SevState state;
75 gchar *measurement;
b2f73a07
PB
76
77 uint32_t reset_cs;
78 uint32_t reset_ip;
79 bool reset_data_valid;
a86ab19d
DG
80};
81
a9b4942f
BS
82#define DEFAULT_GUEST_POLICY 0x1 /* disable debug */
83#define DEFAULT_SEV_DEVICE "/dev/sev"
84
b2f73a07
PB
85#define SEV_INFO_BLOCK_GUID "00f771de-1a7e-4fcb-890e-68c77e2fb44e"
86typedef struct __attribute__((__packed__)) SevInfoBlock {
87 /* SEV-ES Reset Vector Address */
88 uint32_t reset_addr;
89} SevInfoBlock;
90
cff03145
DM
91#define SEV_HASH_TABLE_RV_GUID "7255371f-3a3b-4b04-927b-1da6efa8d454"
92typedef 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
102typedef struct QEMU_PACKED SevHashTableEntry {
103 QemuUUID guid;
104 uint16_t len;
105 uint8_t hash[HASH_SIZE];
106} SevHashTableEntry;
107
108typedef struct QEMU_PACKED SevHashTable {
109 QemuUUID guid;
110 uint16_t len;
111 SevHashTableEntry cmdline;
112 SevHashTableEntry initrd;
113 SevHashTableEntry kernel;
cff03145
DM
114} SevHashTable;
115
ddcc0d89
DM
116/*
117 * Data encrypted by sev_encrypt_flash() must be padded to a multiple of
118 * 16 bytes.
119 */
120typedef struct QEMU_PACKED PaddedSevHashTable {
121 SevHashTable ht;
122 uint8_t padding[ROUND_UP(sizeof(SevHashTable), 16) - sizeof(SevHashTable)];
123} PaddedSevHashTable;
124
125QEMU_BUILD_BUG_ON(sizeof(PaddedSevHashTable) % 16 != 0);
126
8673dee3 127static SevGuestState *sev_guest;
8fa4466d 128static Error *sev_mig_blocker;
d8575c6c
BS
129
130static const char *const sev_fw_errlist[] = {
5811b936
CK
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",
d47b8550
CK
154 [SEV_RET_RESOURCE_LIMIT] = "Required firmware resource depleted",
155 [SEV_RET_SECURE_DATA_INVALID] = "Part-specific integrity check failure",
d8575c6c
BS
156};
157
158#define SEV_FW_MAX_ERROR ARRAY_SIZE(sev_fw_errlist)
159
160static int
161sev_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
181static int
182sev_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
197static const char *
198fw_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
b738d630 207static bool
8673dee3 208sev_check_state(const SevGuestState *sev, SevState state)
b738d630 209{
8673dee3 210 assert(sev);
421522eb 211 return sev->state == state ? true : false;
b738d630
BS
212}
213
620fd55c 214static void
8673dee3 215sev_set_guest_state(SevGuestState *sev, SevState new_state)
620fd55c
BS
216{
217 assert(new_state < SEV_STATE__MAX);
8673dee3 218 assert(sev);
620fd55c 219
421522eb 220 trace_kvm_sev_change_state(SevState_str(sev->state),
620fd55c 221 SevState_str(new_state));
421522eb 222 sev->state = new_state;
620fd55c
BS
223}
224
2b308e44 225static void
8f44304c
DH
226sev_ram_block_added(RAMBlockNotifier *n, void *host, size_t size,
227 size_t max_size)
2b308e44
BS
228{
229 int r;
230 struct kvm_enc_region range;
cedc0ad5
BS
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 }
2b308e44
BS
242
243 range.addr = (__u64)(unsigned long)host;
8f44304c 244 range.size = max_size;
2b308e44 245
8f44304c 246 trace_kvm_memcrypt_register_region(host, max_size);
2b308e44
BS
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'",
8f44304c 250 __func__, host, max_size, strerror(errno));
2b308e44
BS
251 exit(1);
252 }
253}
254
255static void
8f44304c
DH
256sev_ram_block_removed(RAMBlockNotifier *n, void *host, size_t size,
257 size_t max_size)
2b308e44
BS
258{
259 int r;
260 struct kvm_enc_region range;
56e2ec94
AW
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 }
2b308e44
BS
272
273 range.addr = (__u64)(unsigned long)host;
8f44304c 274 range.size = max_size;
2b308e44 275
8f44304c 276 trace_kvm_memcrypt_unregister_region(host, max_size);
2b308e44
BS
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)",
8f44304c 280 __func__, host, max_size);
2b308e44
BS
281 }
282}
283
284static struct RAMBlockNotifier sev_ram_notifier = {
285 .ram_block_added = sev_ram_block_added,
286 .ram_block_removed = sev_ram_block_removed,
287};
288
a9b4942f 289static void
d2d8a198 290sev_guest_finalize(Object *obj)
a9b4942f
BS
291{
292}
293
294static char *
d2d8a198 295sev_guest_get_session_file(Object *obj, Error **errp)
a9b4942f 296{
d2d8a198 297 SevGuestState *s = SEV_GUEST(obj);
a9b4942f
BS
298
299 return s->session_file ? g_strdup(s->session_file) : NULL;
300}
301
302static void
d2d8a198 303sev_guest_set_session_file(Object *obj, const char *value, Error **errp)
a9b4942f 304{
d2d8a198 305 SevGuestState *s = SEV_GUEST(obj);
a9b4942f
BS
306
307 s->session_file = g_strdup(value);
308}
309
310static char *
d2d8a198 311sev_guest_get_dh_cert_file(Object *obj, Error **errp)
a9b4942f 312{
d2d8a198 313 SevGuestState *s = SEV_GUEST(obj);
a9b4942f
BS
314
315 return g_strdup(s->dh_cert_file);
316}
317
318static void
d2d8a198 319sev_guest_set_dh_cert_file(Object *obj, const char *value, Error **errp)
a9b4942f 320{
d2d8a198 321 SevGuestState *s = SEV_GUEST(obj);
a9b4942f
BS
322
323 s->dh_cert_file = g_strdup(value);
324}
325
326static char *
d2d8a198 327sev_guest_get_sev_device(Object *obj, Error **errp)
a9b4942f 328{
d2d8a198 329 SevGuestState *sev = SEV_GUEST(obj);
a9b4942f
BS
330
331 return g_strdup(sev->sev_device);
332}
333
334static void
d2d8a198 335sev_guest_set_sev_device(Object *obj, const char *value, Error **errp)
a9b4942f 336{
d2d8a198 337 SevGuestState *sev = SEV_GUEST(obj);
a9b4942f
BS
338
339 sev->sev_device = g_strdup(value);
340}
341
55cdf566
DM
342static 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
349static 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
a9b4942f 356static void
d2d8a198 357sev_guest_class_init(ObjectClass *oc, void *data)
a9b4942f
BS
358{
359 object_class_property_add_str(oc, "sev-device",
d2d8a198
DG
360 sev_guest_get_sev_device,
361 sev_guest_set_sev_device);
a9b4942f 362 object_class_property_set_description(oc, "sev-device",
7eecec7d 363 "SEV device to use");
a9b4942f 364 object_class_property_add_str(oc, "dh-cert-file",
d2d8a198
DG
365 sev_guest_get_dh_cert_file,
366 sev_guest_set_dh_cert_file);
a9b4942f 367 object_class_property_set_description(oc, "dh-cert-file",
7eecec7d 368 "guest owners DH certificate (encoded with base64)");
a9b4942f 369 object_class_property_add_str(oc, "session-file",
d2d8a198
DG
370 sev_guest_get_session_file,
371 sev_guest_set_session_file);
a9b4942f 372 object_class_property_set_description(oc, "session-file",
7eecec7d 373 "guest owners session parameters (encoded with base64)");
55cdf566
DM
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");
a9b4942f
BS
379}
380
a9b4942f 381static void
d2d8a198 382sev_guest_instance_init(Object *obj)
a9b4942f 383{
d2d8a198 384 SevGuestState *sev = SEV_GUEST(obj);
a9b4942f
BS
385
386 sev->sev_device = g_strdup(DEFAULT_SEV_DEVICE);
387 sev->policy = DEFAULT_GUEST_POLICY;
64a7b8de 388 object_property_add_uint32_ptr(obj, "policy", &sev->policy,
d2623129 389 OBJ_PROP_FLAG_READWRITE);
64a7b8de 390 object_property_add_uint32_ptr(obj, "handle", &sev->handle,
d2623129 391 OBJ_PROP_FLAG_READWRITE);
64a7b8de 392 object_property_add_uint32_ptr(obj, "cbitpos", &sev->cbitpos,
d2623129 393 OBJ_PROP_FLAG_READWRITE);
64a7b8de
FF
394 object_property_add_uint32_ptr(obj, "reduced-phys-bits",
395 &sev->reduced_phys_bits,
d2623129 396 OBJ_PROP_FLAG_READWRITE);
a9b4942f
BS
397}
398
399/* sev guest info */
d2d8a198 400static const TypeInfo sev_guest_info = {
f91f9f25 401 .parent = TYPE_CONFIDENTIAL_GUEST_SUPPORT,
d2d8a198
DG
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,
a9b4942f
BS
407 .interfaces = (InterfaceInfo[]) {
408 { TYPE_USER_CREATABLE },
409 { }
410 }
411};
412
d8575c6c
BS
413bool
414sev_enabled(void)
415{
8673dee3 416 return !!sev_guest;
d8575c6c
BS
417}
418
6b98e96f
TL
419bool
420sev_es_enabled(void)
421{
027b524d 422 return sev_enabled() && (sev_guest->policy & SEV_POLICY_ES);
6b98e96f
TL
423}
424
d8575c6c
BS
425uint32_t
426sev_get_cbit_position(void)
427{
a06d2bad 428 return sev_guest ? sev_guest->cbitpos : 0;
d8575c6c
BS
429}
430
431uint32_t
432sev_get_reduced_phys_bits(void)
433{
a06d2bad 434 return sev_guest ? sev_guest->reduced_phys_bits : 0;
d8575c6c
BS
435}
436
aa395018 437static SevInfo *sev_get_info(void)
d8575c6c
BS
438{
439 SevInfo *info;
440
441 info = g_new0(SevInfo, 1);
8673dee3 442 info->enabled = sev_enabled();
d8575c6c
BS
443
444 if (info->enabled) {
421522eb
DG
445 info->api_major = sev_guest->api_major;
446 info->api_minor = sev_guest->api_minor;
447 info->build_id = sev_guest->build_id;
0bd15277 448 info->policy = sev_guest->policy;
421522eb 449 info->state = sev_guest->state;
cf504cd6 450 info->handle = sev_guest->handle;
d8575c6c
BS
451 }
452
453 return info;
454}
455
aa395018
PMD
456SevInfo *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
469void 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
9f750794
BS
490static int
491sev_get_pdh_info(int fd, guchar **pdh, size_t *pdh_len, guchar **cert_chain,
e4f62785 492 size_t *cert_chain_len, Error **errp)
9f750794 493{
bf3175b4
PB
494 guchar *pdh_data = NULL;
495 guchar *cert_chain_data = NULL;
9f750794
BS
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) {
2c7233eb
PMD
503 error_setg(errp, "SEV: Failed to export PDH cert"
504 " ret=%d fw_err=%d (%s)",
e4f62785 505 r, err, fw_error_to_str(err));
9f750794
BS
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) {
2c7233eb 517 error_setg(errp, "SEV: Failed to export PDH cert ret=%d fw_err=%d (%s)",
e4f62785 518 r, err, fw_error_to_str(err));
9f750794
BS
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
528e_free:
529 g_free(pdh_data);
530 g_free(cert_chain_data);
531 return 1;
532}
533
811b4ec7
DM
534static int sev_get_cpu0_id(int fd, guchar **id, size_t *id_len, Error **errp)
535{
536 guchar *id_data;
537 struct sev_user_data_get_id2 get_id2 = {};
538 int err, r;
539
540 /* query the ID length */
541 r = sev_platform_ioctl(fd, SEV_GET_ID2, &get_id2, &err);
542 if (r < 0 && err != SEV_RET_INVALID_LEN) {
543 error_setg(errp, "SEV: Failed to get ID ret=%d fw_err=%d (%s)",
544 r, err, fw_error_to_str(err));
545 return 1;
546 }
547
548 id_data = g_new(guchar, get_id2.length);
549 get_id2.address = (unsigned long)id_data;
550
551 r = sev_platform_ioctl(fd, SEV_GET_ID2, &get_id2, &err);
552 if (r < 0) {
553 error_setg(errp, "SEV: Failed to get ID ret=%d fw_err=%d (%s)",
554 r, err, fw_error_to_str(err));
555 goto err;
556 }
557
558 *id = id_data;
559 *id_len = get_id2.length;
560 return 0;
561
562err:
563 g_free(id_data);
564 return 1;
565}
566
8371df29 567static SevCapability *sev_get_capabilities(Error **errp)
9f750794 568{
bf3175b4
PB
569 SevCapability *cap = NULL;
570 guchar *pdh_data = NULL;
571 guchar *cert_chain_data = NULL;
811b4ec7
DM
572 guchar *cpu0_id_data = NULL;
573 size_t pdh_len = 0, cert_chain_len = 0, cpu0_id_len = 0;
9f750794
BS
574 uint32_t ebx;
575 int fd;
576
1b38750c
PB
577 if (!kvm_enabled()) {
578 error_setg(errp, "KVM not enabled");
579 return NULL;
580 }
581 if (kvm_vm_ioctl(kvm_state, KVM_MEMORY_ENCRYPT_OP, NULL) < 0) {
582 error_setg(errp, "SEV is not enabled in KVM");
583 return NULL;
584 }
585
9f750794
BS
586 fd = open(DEFAULT_SEV_DEVICE, O_RDWR);
587 if (fd < 0) {
2c7233eb 588 error_setg_errno(errp, errno, "SEV: Failed to open %s",
e4f62785 589 DEFAULT_SEV_DEVICE);
9f750794
BS
590 return NULL;
591 }
592
593 if (sev_get_pdh_info(fd, &pdh_data, &pdh_len,
e4f62785 594 &cert_chain_data, &cert_chain_len, errp)) {
bf3175b4 595 goto out;
9f750794
BS
596 }
597
811b4ec7
DM
598 if (sev_get_cpu0_id(fd, &cpu0_id_data, &cpu0_id_len, errp)) {
599 goto out;
600 }
601
9f750794
BS
602 cap = g_new0(SevCapability, 1);
603 cap->pdh = g_base64_encode(pdh_data, pdh_len);
604 cap->cert_chain = g_base64_encode(cert_chain_data, cert_chain_len);
811b4ec7 605 cap->cpu0_id = g_base64_encode(cpu0_id_data, cpu0_id_len);
9f750794
BS
606
607 host_cpuid(0x8000001F, 0, NULL, &ebx, NULL, NULL);
608 cap->cbitpos = ebx & 0x3f;
609
610 /*
611 * When SEV feature is enabled, we loose one bit in guest physical
612 * addressing.
613 */
614 cap->reduced_phys_bits = 1;
615
bf3175b4 616out:
811b4ec7 617 g_free(cpu0_id_data);
9f750794
BS
618 g_free(pdh_data);
619 g_free(cert_chain_data);
9f750794
BS
620 close(fd);
621 return cap;
622}
623
8371df29
PMD
624SevCapability *qmp_query_sev_capabilities(Error **errp)
625{
626 return sev_get_capabilities(errp);
627}
628
3208de1c
PMD
629static SevAttestationReport *sev_get_attestation_report(const char *mnonce,
630 Error **errp)
3ea1a802
BS
631{
632 struct kvm_sev_attestation_report input = {};
633 SevAttestationReport *report = NULL;
634 SevGuestState *sev = sev_guest;
ed84ae72
DDAG
635 g_autofree guchar *data = NULL;
636 g_autofree guchar *buf = NULL;
3ea1a802
BS
637 gsize len;
638 int err = 0, ret;
639
640 if (!sev_enabled()) {
641 error_setg(errp, "SEV is not enabled");
642 return NULL;
643 }
644
645 /* lets decode the mnonce string */
646 buf = g_base64_decode(mnonce, &len);
647 if (!buf) {
648 error_setg(errp, "SEV: failed to decode mnonce input");
649 return NULL;
650 }
651
652 /* verify the input mnonce length */
653 if (len != sizeof(input.mnonce)) {
654 error_setg(errp, "SEV: mnonce must be %zu bytes (got %" G_GSIZE_FORMAT ")",
655 sizeof(input.mnonce), len);
3ea1a802
BS
656 return NULL;
657 }
658
659 /* Query the report length */
660 ret = sev_ioctl(sev->sev_fd, KVM_SEV_GET_ATTESTATION_REPORT,
661 &input, &err);
662 if (ret < 0) {
663 if (err != SEV_RET_INVALID_LEN) {
2c7233eb
PMD
664 error_setg(errp, "SEV: Failed to query the attestation report"
665 " length ret=%d fw_err=%d (%s)",
666 ret, err, fw_error_to_str(err));
3ea1a802
BS
667 return NULL;
668 }
669 }
670
671 data = g_malloc(input.len);
672 input.uaddr = (unsigned long)data;
673 memcpy(input.mnonce, buf, sizeof(input.mnonce));
674
675 /* Query the report */
676 ret = sev_ioctl(sev->sev_fd, KVM_SEV_GET_ATTESTATION_REPORT,
677 &input, &err);
678 if (ret) {
2c7233eb 679 error_setg_errno(errp, errno, "SEV: Failed to get attestation report"
3ea1a802 680 " ret=%d fw_err=%d (%s)", ret, err, fw_error_to_str(err));
ed84ae72 681 return NULL;
3ea1a802
BS
682 }
683
684 report = g_new0(SevAttestationReport, 1);
685 report->data = g_base64_encode(data, input.len);
686
687 trace_kvm_sev_attestation_report(mnonce, report->data);
688
3ea1a802
BS
689 return report;
690}
691
3208de1c
PMD
692SevAttestationReport *qmp_query_sev_attestation_report(const char *mnonce,
693 Error **errp)
694{
695 return sev_get_attestation_report(mnonce, errp);
696}
697
620fd55c
BS
698static int
699sev_read_file_base64(const char *filename, guchar **data, gsize *len)
700{
701 gsize sz;
523a3d95 702 g_autofree gchar *base64 = NULL;
620fd55c
BS
703 GError *error = NULL;
704
705 if (!g_file_get_contents(filename, &base64, &sz, &error)) {
2c7233eb 706 error_report("SEV: Failed to read '%s' (%s)", filename, error->message);
efacd5b8 707 g_error_free(error);
620fd55c
BS
708 return -1;
709 }
710
711 *data = g_base64_decode(base64, len);
712 return 0;
713}
714
715static int
75a877e3 716sev_launch_start(SevGuestState *sev)
620fd55c
BS
717{
718 gsize sz;
719 int ret = 1;
bf3175b4 720 int fw_error, rc;
eb8257a2
DM
721 struct kvm_sev_launch_start start = {
722 .handle = sev->handle, .policy = sev->policy
723 };
620fd55c
BS
724 guchar *session = NULL, *dh_cert = NULL;
725
620fd55c
BS
726 if (sev->session_file) {
727 if (sev_read_file_base64(sev->session_file, &session, &sz) < 0) {
bf3175b4 728 goto out;
620fd55c 729 }
eb8257a2
DM
730 start.session_uaddr = (unsigned long)session;
731 start.session_len = sz;
620fd55c
BS
732 }
733
734 if (sev->dh_cert_file) {
735 if (sev_read_file_base64(sev->dh_cert_file, &dh_cert, &sz) < 0) {
bf3175b4 736 goto out;
620fd55c 737 }
eb8257a2
DM
738 start.dh_uaddr = (unsigned long)dh_cert;
739 start.dh_len = sz;
620fd55c
BS
740 }
741
eb8257a2
DM
742 trace_kvm_sev_launch_start(start.policy, session, dh_cert);
743 rc = sev_ioctl(sev->sev_fd, KVM_SEV_LAUNCH_START, &start, &fw_error);
bf3175b4 744 if (rc < 0) {
620fd55c
BS
745 error_report("%s: LAUNCH_START ret=%d fw_error=%d '%s'",
746 __func__, ret, fw_error, fw_error_to_str(fw_error));
bf3175b4 747 goto out;
620fd55c
BS
748 }
749
8673dee3 750 sev_set_guest_state(sev, SEV_STATE_LAUNCH_UPDATE);
eb8257a2 751 sev->handle = start.handle;
bf3175b4 752 ret = 0;
620fd55c 753
bf3175b4 754out:
620fd55c
BS
755 g_free(session);
756 g_free(dh_cert);
bf3175b4 757 return ret;
620fd55c
BS
758}
759
b738d630 760static int
8673dee3 761sev_launch_update_data(SevGuestState *sev, uint8_t *addr, uint64_t len)
b738d630
BS
762{
763 int ret, fw_error;
764 struct kvm_sev_launch_update_data update;
765
766 if (!addr || !len) {
767 return 1;
768 }
769
770 update.uaddr = (__u64)(unsigned long)addr;
771 update.len = len;
772 trace_kvm_sev_launch_update_data(addr, len);
421522eb 773 ret = sev_ioctl(sev->sev_fd, KVM_SEV_LAUNCH_UPDATE_DATA,
b738d630
BS
774 &update, &fw_error);
775 if (ret) {
776 error_report("%s: LAUNCH_UPDATE ret=%d fw_error=%d '%s'",
777 __func__, ret, fw_error, fw_error_to_str(fw_error));
778 }
779
780 return ret;
781}
782
6b98e96f
TL
783static int
784sev_launch_update_vmsa(SevGuestState *sev)
785{
786 int ret, fw_error;
787
788 ret = sev_ioctl(sev->sev_fd, KVM_SEV_LAUNCH_UPDATE_VMSA, NULL, &fw_error);
789 if (ret) {
790 error_report("%s: LAUNCH_UPDATE_VMSA ret=%d fw_error=%d '%s'",
791 __func__, ret, fw_error, fw_error_to_str(fw_error));
792 }
793
794 return ret;
795}
796
c6c89c97
BS
797static void
798sev_launch_get_measure(Notifier *notifier, void *unused)
799{
8673dee3 800 SevGuestState *sev = sev_guest;
c6c89c97 801 int ret, error;
2f573c41 802 g_autofree guchar *data = NULL;
59e42d88 803 struct kvm_sev_launch_measure measurement = {};
c6c89c97 804
8673dee3 805 if (!sev_check_state(sev, SEV_STATE_LAUNCH_UPDATE)) {
c6c89c97
BS
806 return;
807 }
808
6b98e96f
TL
809 if (sev_es_enabled()) {
810 /* measure all the VM save areas before getting launch_measure */
811 ret = sev_launch_update_vmsa(sev);
812 if (ret) {
813 exit(1);
814 }
815 }
816
c6c89c97 817 /* query the measurement blob length */
421522eb 818 ret = sev_ioctl(sev->sev_fd, KVM_SEV_LAUNCH_MEASURE,
59e42d88
DM
819 &measurement, &error);
820 if (!measurement.len) {
c6c89c97
BS
821 error_report("%s: LAUNCH_MEASURE ret=%d fw_error=%d '%s'",
822 __func__, ret, error, fw_error_to_str(errno));
2f573c41 823 return;
c6c89c97
BS
824 }
825
59e42d88
DM
826 data = g_new0(guchar, measurement.len);
827 measurement.uaddr = (unsigned long)data;
c6c89c97
BS
828
829 /* get the measurement blob */
421522eb 830 ret = sev_ioctl(sev->sev_fd, KVM_SEV_LAUNCH_MEASURE,
59e42d88 831 &measurement, &error);
c6c89c97
BS
832 if (ret) {
833 error_report("%s: LAUNCH_MEASURE ret=%d fw_error=%d '%s'",
834 __func__, ret, error, fw_error_to_str(errno));
2f573c41 835 return;
c6c89c97
BS
836 }
837
8673dee3 838 sev_set_guest_state(sev, SEV_STATE_LAUNCH_SECRET);
c6c89c97
BS
839
840 /* encode the measurement value and emit the event */
59e42d88 841 sev->measurement = g_base64_encode(data, measurement.len);
421522eb 842 trace_kvm_sev_launch_measurement(sev->measurement);
c6c89c97
BS
843}
844
0875a703 845static char *sev_get_launch_measurement(void)
c6c89c97 846{
8673dee3 847 if (sev_guest &&
421522eb
DG
848 sev_guest->state >= SEV_STATE_LAUNCH_SECRET) {
849 return g_strdup(sev_guest->measurement);
c6c89c97
BS
850 }
851
852 return NULL;
853}
854
0875a703
PMD
855SevLaunchMeasureInfo *qmp_query_sev_launch_measure(Error **errp)
856{
857 char *data;
858 SevLaunchMeasureInfo *info;
859
860 data = sev_get_launch_measurement();
861 if (!data) {
862 error_setg(errp, "SEV launch measurement is not available");
863 return NULL;
864 }
865
866 info = g_malloc0(sizeof(*info));
867 info->data = data;
868
869 return info;
870}
871
c6c89c97
BS
872static Notifier sev_machine_done_notify = {
873 .notify = sev_launch_get_measure,
874};
875
5dd0df7e 876static void
8673dee3 877sev_launch_finish(SevGuestState *sev)
5dd0df7e
BS
878{
879 int ret, error;
880
881 trace_kvm_sev_launch_finish();
421522eb 882 ret = sev_ioctl(sev->sev_fd, KVM_SEV_LAUNCH_FINISH, 0, &error);
5dd0df7e
BS
883 if (ret) {
884 error_report("%s: LAUNCH_FINISH ret=%d fw_error=%d '%s'",
885 __func__, ret, error, fw_error_to_str(error));
886 exit(1);
887 }
888
8673dee3 889 sev_set_guest_state(sev, SEV_STATE_RUNNING);
8fa4466d
BS
890
891 /* add migration blocker */
892 error_setg(&sev_mig_blocker,
893 "SEV: Migration is not implemented");
c8a7fc51 894 migrate_add_blocker(&sev_mig_blocker, &error_fatal);
5dd0df7e
BS
895}
896
897static void
538f0497 898sev_vm_state_change(void *opaque, bool running, RunState state)
5dd0df7e 899{
8673dee3 900 SevGuestState *sev = opaque;
5dd0df7e
BS
901
902 if (running) {
8673dee3
DG
903 if (!sev_check_state(sev, SEV_STATE_RUNNING)) {
904 sev_launch_finish(sev);
5dd0df7e
BS
905 }
906 }
907}
908
c9f5aaa6 909int sev_kvm_init(ConfidentialGuestSupport *cgs, Error **errp)
d8575c6c 910{
ec78e2cd
DG
911 SevGuestState *sev
912 = (SevGuestState *)object_dynamic_cast(OBJECT(cgs), TYPE_SEV_GUEST);
d8575c6c 913 char *devname;
6b98e96f 914 int ret, fw_error, cmd;
d8575c6c
BS
915 uint32_t ebx;
916 uint32_t host_cbitpos;
917 struct sev_user_data_status status = {};
918
ec78e2cd
DG
919 if (!sev) {
920 return 0;
921 }
922
fee3f3ba
DH
923 ret = ram_block_discard_disable(true);
924 if (ret) {
925 error_report("%s: cannot disable RAM discard", __func__);
aacdb844 926 return -1;
fee3f3ba
DH
927 }
928
8673dee3 929 sev_guest = sev;
421522eb 930 sev->state = SEV_STATE_UNINIT;
d8575c6c
BS
931
932 host_cpuid(0x8000001F, 0, NULL, &ebx, NULL, NULL);
933 host_cbitpos = ebx & 0x3f;
934
8168fed9
TL
935 /*
936 * The cbitpos value will be placed in bit positions 5:0 of the EBX
937 * register of CPUID 0x8000001F. No need to verify the range as the
938 * comparison against the host value accomplishes that.
939 */
a06d2bad 940 if (host_cbitpos != sev->cbitpos) {
c9f5aaa6
DG
941 error_setg(errp, "%s: cbitpos check failed, host '%d' requested '%d'",
942 __func__, host_cbitpos, sev->cbitpos);
d8575c6c
BS
943 goto err;
944 }
945
8168fed9
TL
946 /*
947 * The reduced-phys-bits value will be placed in bit positions 11:6 of
948 * the EBX register of CPUID 0x8000001F, so verify the supplied value
949 * is in the range of 1 to 63.
950 */
951 if (sev->reduced_phys_bits < 1 || sev->reduced_phys_bits > 63) {
952 error_setg(errp, "%s: reduced_phys_bits check failed,"
953 " it should be in the range of 1 to 63, requested '%d'",
954 __func__, sev->reduced_phys_bits);
d8575c6c
BS
955 goto err;
956 }
957
75a877e3 958 devname = object_property_get_str(OBJECT(sev), "sev-device", NULL);
421522eb
DG
959 sev->sev_fd = open(devname, O_RDWR);
960 if (sev->sev_fd < 0) {
c9f5aaa6
DG
961 error_setg(errp, "%s: Failed to open %s '%s'", __func__,
962 devname, strerror(errno));
963 g_free(devname);
5d7bc72a
GK
964 goto err;
965 }
c9f5aaa6 966 g_free(devname);
d8575c6c 967
421522eb 968 ret = sev_platform_ioctl(sev->sev_fd, SEV_PLATFORM_STATUS, &status,
d8575c6c
BS
969 &fw_error);
970 if (ret) {
c9f5aaa6
DG
971 error_setg(errp, "%s: failed to get platform status ret=%d "
972 "fw_error='%d: %s'", __func__, ret, fw_error,
973 fw_error_to_str(fw_error));
d8575c6c
BS
974 goto err;
975 }
421522eb
DG
976 sev->build_id = status.build;
977 sev->api_major = status.api_major;
978 sev->api_minor = status.api_minor;
d8575c6c 979
6b98e96f 980 if (sev_es_enabled()) {
9681f867
TL
981 if (!kvm_kernel_irqchip_allowed()) {
982 error_report("%s: SEV-ES guests require in-kernel irqchip support",
983 __func__);
984 goto err;
985 }
986
6b98e96f
TL
987 if (!(status.flags & SEV_STATUS_FLAGS_CONFIG_ES)) {
988 error_report("%s: guest policy requires SEV-ES, but "
989 "host SEV-ES support unavailable",
990 __func__);
991 goto err;
992 }
993 cmd = KVM_SEV_ES_INIT;
994 } else {
995 cmd = KVM_SEV_INIT;
996 }
997
d8575c6c 998 trace_kvm_sev_init();
6b98e96f 999 ret = sev_ioctl(sev->sev_fd, cmd, NULL, &fw_error);
d8575c6c 1000 if (ret) {
c9f5aaa6
DG
1001 error_setg(errp, "%s: failed to initialize ret=%d fw_error=%d '%s'",
1002 __func__, ret, fw_error, fw_error_to_str(fw_error));
d8575c6c
BS
1003 goto err;
1004 }
1005
75a877e3 1006 ret = sev_launch_start(sev);
620fd55c 1007 if (ret) {
c9f5aaa6 1008 error_setg(errp, "%s: failed to create encryption context", __func__);
620fd55c
BS
1009 goto err;
1010 }
1011
2b308e44 1012 ram_block_notifier_add(&sev_ram_notifier);
c6c89c97 1013 qemu_add_machine_init_done_notifier(&sev_machine_done_notify);
8673dee3 1014 qemu_add_vm_change_state_handler(sev_vm_state_change, sev);
2b308e44 1015
abc27d42
DG
1016 cgs->ready = true;
1017
aacdb844 1018 return 0;
d8575c6c 1019err:
8673dee3 1020 sev_guest = NULL;
fee3f3ba 1021 ram_block_discard_disable(false);
aacdb844 1022 return -1;
d8575c6c
BS
1023}
1024
b738d630 1025int
aacdb844 1026sev_encrypt_flash(uint8_t *ptr, uint64_t len, Error **errp)
b738d630 1027{
aacdb844
DG
1028 if (!sev_guest) {
1029 return 0;
1030 }
b738d630
BS
1031
1032 /* if SEV is in update state then encrypt the data else do nothing */
aacdb844
DG
1033 if (sev_check_state(sev_guest, SEV_STATE_LAUNCH_UPDATE)) {
1034 int ret = sev_launch_update_data(sev_guest, ptr, len);
1035 if (ret < 0) {
2c7233eb 1036 error_setg(errp, "SEV: Failed to encrypt pflash rom");
aacdb844
DG
1037 return ret;
1038 }
b738d630
BS
1039 }
1040
1041 return 0;
1042}
1043
c7f7e697
TFF
1044int sev_inject_launch_secret(const char *packet_hdr, const char *secret,
1045 uint64_t gpa, Error **errp)
1046{
1047 struct kvm_sev_launch_secret input;
1048 g_autofree guchar *data = NULL, *hdr = NULL;
1049 int error, ret = 1;
1050 void *hva;
1051 gsize hdr_sz = 0, data_sz = 0;
1052 MemoryRegion *mr = NULL;
1053
1054 if (!sev_guest) {
2c7233eb 1055 error_setg(errp, "SEV not enabled for guest");
c7f7e697
TFF
1056 return 1;
1057 }
1058
1059 /* secret can be injected only in this state */
1060 if (!sev_check_state(sev_guest, SEV_STATE_LAUNCH_SECRET)) {
1061 error_setg(errp, "SEV: Not in correct state. (LSECRET) %x",
1062 sev_guest->state);
1063 return 1;
1064 }
1065
1066 hdr = g_base64_decode(packet_hdr, &hdr_sz);
1067 if (!hdr || !hdr_sz) {
1068 error_setg(errp, "SEV: Failed to decode sequence header");
1069 return 1;
1070 }
1071
1072 data = g_base64_decode(secret, &data_sz);
1073 if (!data || !data_sz) {
1074 error_setg(errp, "SEV: Failed to decode data");
1075 return 1;
1076 }
1077
1078 hva = gpa2hva(&mr, gpa, data_sz, errp);
1079 if (!hva) {
1080 error_prepend(errp, "SEV: Failed to calculate guest address: ");
1081 return 1;
1082 }
1083
1084 input.hdr_uaddr = (uint64_t)(unsigned long)hdr;
1085 input.hdr_len = hdr_sz;
1086
1087 input.trans_uaddr = (uint64_t)(unsigned long)data;
1088 input.trans_len = data_sz;
1089
1090 input.guest_uaddr = (uint64_t)(unsigned long)hva;
1091 input.guest_len = data_sz;
1092
1093 trace_kvm_sev_launch_secret(gpa, input.guest_uaddr,
1094 input.trans_uaddr, input.trans_len);
1095
1096 ret = sev_ioctl(sev_guest->sev_fd, KVM_SEV_LAUNCH_SECRET,
1097 &input, &error);
1098 if (ret) {
1099 error_setg(errp, "SEV: failed to inject secret ret=%d fw_error=%d '%s'",
1100 ret, error, fw_error_to_str(error));
1101 return ret;
1102 }
1103
1104 return 0;
1105}
1106
11a6ed0e
PMD
1107#define SEV_SECRET_GUID "4c2eb361-7d9b-4cc3-8081-127c90d3d294"
1108struct sev_secret_area {
1109 uint32_t base;
1110 uint32_t size;
1111};
1112
1113void qmp_sev_inject_launch_secret(const char *packet_hdr,
1114 const char *secret,
1115 bool has_gpa, uint64_t gpa,
1116 Error **errp)
1117{
1118 if (!sev_enabled()) {
1119 error_setg(errp, "SEV not enabled for guest");
1120 return;
1121 }
1122 if (!has_gpa) {
1123 uint8_t *data;
1124 struct sev_secret_area *area;
1125
1126 if (!pc_system_ovmf_table_find(SEV_SECRET_GUID, &data, NULL)) {
1127 error_setg(errp, "SEV: no secret area found in OVMF,"
1128 " gpa must be specified.");
1129 return;
1130 }
1131 area = (struct sev_secret_area *)data;
1132 gpa = area->base;
1133 }
1134
1135 sev_inject_launch_secret(packet_hdr, secret, gpa, errp);
1136}
1137
b2f73a07
PB
1138static int
1139sev_es_parse_reset_block(SevInfoBlock *info, uint32_t *addr)
1140{
1141 if (!info->reset_addr) {
1142 error_report("SEV-ES reset address is zero");
1143 return 1;
1144 }
1145
1146 *addr = info->reset_addr;
1147
1148 return 0;
1149}
1150
1151static int
1152sev_es_find_reset_vector(void *flash_ptr, uint64_t flash_size,
1153 uint32_t *addr)
1154{
1155 QemuUUID info_guid, *guid;
1156 SevInfoBlock *info;
1157 uint8_t *data;
1158 uint16_t *len;
1159
1160 /*
1161 * Initialize the address to zero. An address of zero with a successful
1162 * return code indicates that SEV-ES is not active.
1163 */
1164 *addr = 0;
1165
1166 /*
1167 * Extract the AP reset vector for SEV-ES guests by locating the SEV GUID.
1168 * The SEV GUID is located on its own (original implementation) or within
1169 * the Firmware GUID Table (new implementation), either of which are
1170 * located 32 bytes from the end of the flash.
1171 *
1172 * Check the Firmware GUID Table first.
1173 */
1174 if (pc_system_ovmf_table_find(SEV_INFO_BLOCK_GUID, &data, NULL)) {
1175 return sev_es_parse_reset_block((SevInfoBlock *)data, addr);
1176 }
1177
1178 /*
1179 * SEV info block not found in the Firmware GUID Table (or there isn't
1180 * a Firmware GUID Table), fall back to the original implementation.
1181 */
1182 data = flash_ptr + flash_size - 0x20;
1183
1184 qemu_uuid_parse(SEV_INFO_BLOCK_GUID, &info_guid);
1185 info_guid = qemu_uuid_bswap(info_guid); /* GUIDs are LE */
1186
1187 guid = (QemuUUID *)(data - sizeof(info_guid));
1188 if (!qemu_uuid_is_equal(guid, &info_guid)) {
1189 error_report("SEV information block/Firmware GUID Table block not found in pflash rom");
1190 return 1;
1191 }
1192
1193 len = (uint16_t *)((uint8_t *)guid - sizeof(*len));
1194 info = (SevInfoBlock *)(data - le16_to_cpu(*len));
1195
1196 return sev_es_parse_reset_block(info, addr);
1197}
1198
1199void sev_es_set_reset_vector(CPUState *cpu)
1200{
1201 X86CPU *x86;
1202 CPUX86State *env;
1203
1204 /* Only update if we have valid reset information */
1205 if (!sev_guest || !sev_guest->reset_data_valid) {
1206 return;
1207 }
1208
1209 /* Do not update the BSP reset state */
1210 if (cpu->cpu_index == 0) {
1211 return;
1212 }
1213
1214 x86 = X86_CPU(cpu);
1215 env = &x86->env;
1216
1217 cpu_x86_load_seg_cache(env, R_CS, 0xf000, sev_guest->reset_cs, 0xffff,
1218 DESC_P_MASK | DESC_S_MASK | DESC_CS_MASK |
1219 DESC_R_MASK | DESC_A_MASK);
1220
1221 env->eip = sev_guest->reset_ip;
1222}
1223
1224int sev_es_save_reset_vector(void *flash_ptr, uint64_t flash_size)
1225{
1226 CPUState *cpu;
1227 uint32_t addr;
1228 int ret;
1229
1230 if (!sev_es_enabled()) {
1231 return 0;
1232 }
1233
1234 addr = 0;
1235 ret = sev_es_find_reset_vector(flash_ptr, flash_size,
1236 &addr);
1237 if (ret) {
1238 return ret;
1239 }
1240
1241 if (addr) {
1242 sev_guest->reset_cs = addr & 0xffff0000;
1243 sev_guest->reset_ip = addr & 0x0000ffff;
1244 sev_guest->reset_data_valid = true;
1245
1246 CPU_FOREACH(cpu) {
1247 sev_es_set_reset_vector(cpu);
1248 }
1249 }
1250
1251 return 0;
1252}
1253
cff03145
DM
1254static const QemuUUID sev_hash_table_header_guid = {
1255 .data = UUID_LE(0x9438d606, 0x4f22, 0x4cc9, 0xb4, 0x79, 0xa7, 0x93,
1256 0xd4, 0x11, 0xfd, 0x21)
1257};
1258
1259static const QemuUUID sev_kernel_entry_guid = {
1260 .data = UUID_LE(0x4de79437, 0xabd2, 0x427f, 0xb8, 0x35, 0xd5, 0xb1,
1261 0x72, 0xd2, 0x04, 0x5b)
1262};
1263static const QemuUUID sev_initrd_entry_guid = {
1264 .data = UUID_LE(0x44baf731, 0x3a2f, 0x4bd7, 0x9a, 0xf1, 0x41, 0xe2,
1265 0x91, 0x69, 0x78, 0x1d)
1266};
1267static const QemuUUID sev_cmdline_entry_guid = {
1268 .data = UUID_LE(0x97d02dd8, 0xbd20, 0x4c94, 0xaa, 0x78, 0xe7, 0x71,
1269 0x4d, 0x36, 0xab, 0x2a)
1270};
1271
1272/*
1273 * Add the hashes of the linux kernel/initrd/cmdline to an encrypted guest page
1274 * which is included in SEV's initial memory measurement.
1275 */
1276bool sev_add_kernel_loader_hashes(SevKernelLoaderContext *ctx, Error **errp)
1277{
1278 uint8_t *data;
1279 SevHashTableDescriptor *area;
1280 SevHashTable *ht;
ddcc0d89 1281 PaddedSevHashTable *padded_ht;
cff03145
DM
1282 uint8_t cmdline_hash[HASH_SIZE];
1283 uint8_t initrd_hash[HASH_SIZE];
1284 uint8_t kernel_hash[HASH_SIZE];
1285 uint8_t *hashp;
1286 size_t hash_len = HASH_SIZE;
58603ba2
DM
1287 hwaddr mapped_len = sizeof(*padded_ht);
1288 MemTxAttrs attrs = { 0 };
1289 bool ret = true;
cff03145 1290
9dbe0c93
DM
1291 /*
1292 * Only add the kernel hashes if the sev-guest configuration explicitly
1293 * stated kernel-hashes=on.
1294 */
1295 if (!sev_guest->kernel_hashes) {
1296 return false;
1297 }
1298
cff03145 1299 if (!pc_system_ovmf_table_find(SEV_HASH_TABLE_RV_GUID, &data, NULL)) {
5a0294a2
DM
1300 error_setg(errp, "SEV: kernel specified but guest firmware "
1301 "has no hashes table GUID");
cff03145
DM
1302 return false;
1303 }
1304 area = (SevHashTableDescriptor *)data;
ddcc0d89 1305 if (!area->base || area->size < sizeof(PaddedSevHashTable)) {
a0190bf1
DM
1306 error_setg(errp, "SEV: guest firmware hashes table area is invalid "
1307 "(base=0x%x size=0x%x)", area->base, area->size);
1308 return false;
1309 }
cff03145
DM
1310
1311 /*
1312 * Calculate hash of kernel command-line with the terminating null byte. If
1313 * the user doesn't supply a command-line via -append, the 1-byte "\0" will
1314 * be used.
1315 */
1316 hashp = cmdline_hash;
1317 if (qcrypto_hash_bytes(QCRYPTO_HASH_ALG_SHA256, ctx->cmdline_data,
1318 ctx->cmdline_size, &hashp, &hash_len, errp) < 0) {
1319 return false;
1320 }
1321 assert(hash_len == HASH_SIZE);
1322
1323 /*
1324 * Calculate hash of initrd. If the user doesn't supply an initrd via
1325 * -initrd, an empty buffer will be used (ctx->initrd_size == 0).
1326 */
1327 hashp = initrd_hash;
1328 if (qcrypto_hash_bytes(QCRYPTO_HASH_ALG_SHA256, ctx->initrd_data,
1329 ctx->initrd_size, &hashp, &hash_len, errp) < 0) {
1330 return false;
1331 }
1332 assert(hash_len == HASH_SIZE);
1333
1334 /* Calculate hash of the kernel */
1335 hashp = kernel_hash;
1336 struct iovec iov[2] = {
1337 { .iov_base = ctx->setup_data, .iov_len = ctx->setup_size },
1338 { .iov_base = ctx->kernel_data, .iov_len = ctx->kernel_size }
1339 };
1340 if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256, iov, ARRAY_SIZE(iov),
1341 &hashp, &hash_len, errp) < 0) {
1342 return false;
1343 }
1344 assert(hash_len == HASH_SIZE);
1345
1346 /*
1347 * Populate the hashes table in the guest's memory at the OVMF-designated
1348 * area for the SEV hashes table
1349 */
58603ba2
DM
1350 padded_ht = address_space_map(&address_space_memory, area->base,
1351 &mapped_len, true, attrs);
1352 if (!padded_ht || mapped_len != sizeof(*padded_ht)) {
1353 error_setg(errp, "SEV: cannot map hashes table guest memory area");
1354 return false;
1355 }
ddcc0d89 1356 ht = &padded_ht->ht;
cff03145
DM
1357
1358 ht->guid = sev_hash_table_header_guid;
1359 ht->len = sizeof(*ht);
1360
1361 ht->cmdline.guid = sev_cmdline_entry_guid;
1362 ht->cmdline.len = sizeof(ht->cmdline);
1363 memcpy(ht->cmdline.hash, cmdline_hash, sizeof(ht->cmdline.hash));
1364
1365 ht->initrd.guid = sev_initrd_entry_guid;
1366 ht->initrd.len = sizeof(ht->initrd);
1367 memcpy(ht->initrd.hash, initrd_hash, sizeof(ht->initrd.hash));
1368
1369 ht->kernel.guid = sev_kernel_entry_guid;
1370 ht->kernel.len = sizeof(ht->kernel);
1371 memcpy(ht->kernel.hash, kernel_hash, sizeof(ht->kernel.hash));
1372
ddcc0d89
DM
1373 /* zero the excess data so the measurement can be reliably calculated */
1374 memset(padded_ht->padding, 0, sizeof(padded_ht->padding));
cff03145 1375
ddcc0d89 1376 if (sev_encrypt_flash((uint8_t *)padded_ht, sizeof(*padded_ht), errp) < 0) {
58603ba2 1377 ret = false;
cff03145
DM
1378 }
1379
58603ba2
DM
1380 address_space_unmap(&address_space_memory, padded_ht,
1381 mapped_len, true, mapped_len);
1382
1383 return ret;
cff03145
DM
1384}
1385
a9b4942f
BS
1386static void
1387sev_register_types(void)
1388{
d2d8a198 1389 type_register_static(&sev_guest_info);
a9b4942f
BS
1390}
1391
1392type_init(sev_register_types);