xref: /linux/arch/x86/kvm/vmx/sgx.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*  Copyright(c) 2021 Intel Corporation. */
3 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
4 
5 #include <asm/cpuid/api.h>
6 #include <asm/msr.h>
7 #include <asm/sgx.h>
8 
9 #include "x86.h"
10 #include "regs.h"
11 #include "nested.h"
12 #include "sgx.h"
13 #include "vmx.h"
14 
15 bool __read_mostly enable_sgx = 1;
16 module_param_named(sgx, enable_sgx, bool, 0444);
17 
18 /* Initial value of guest's virtual SGX_LEPUBKEYHASHn MSRs */
19 static u64 sgx_pubkey_hash[4] __ro_after_init;
20 
21 /*
22  * ENCLS's memory operands use a fixed segment (DS) and a fixed
23  * address size based on the mode.  Related prefixes are ignored.
24  */
25 static int sgx_get_encls_gva(struct kvm_vcpu *vcpu, unsigned long offset,
26 			     int size, int alignment, gva_t *gva)
27 {
28 	struct kvm_segment s;
29 	bool fault;
30 
31 	/* Skip vmcs.GUEST_DS retrieval for 64-bit mode to avoid VMREADs. */
32 	*gva = offset;
33 	if (!is_64_bit_mode(vcpu)) {
34 		vmx_get_segment(vcpu, &s, VCPU_SREG_DS);
35 		*gva += s.base;
36 	}
37 
38 	if (!IS_ALIGNED(*gva, alignment)) {
39 		fault = true;
40 	} else if (likely(is_64_bit_mode(vcpu))) {
41 		*gva = vmx_get_untagged_addr(vcpu, *gva, 0);
42 		fault = is_noncanonical_address(*gva, vcpu, 0);
43 	} else {
44 		*gva &= 0xffffffff;
45 		fault = (s.unusable) ||
46 			(s.type != 2 && s.type != 3) ||
47 			(*gva > s.limit) ||
48 			((s.base != 0 || s.limit != 0xffffffff) &&
49 			(((u64)*gva + size - 1) > s.limit + 1));
50 	}
51 	if (fault)
52 		kvm_inject_gp(vcpu, 0);
53 	return fault ? -EINVAL : 0;
54 }
55 
56 static void sgx_handle_emulation_failure(struct kvm_vcpu *vcpu, u64 addr,
57 					 unsigned int size)
58 {
59 	uint64_t data[2] = { addr, size };
60 
61 	__kvm_prepare_emulation_failure_exit(vcpu, data, ARRAY_SIZE(data));
62 }
63 
64 static int sgx_read_hva(struct kvm_vcpu *vcpu, unsigned long hva, void *data,
65 			unsigned int size)
66 {
67 	if (__copy_from_user(data, (void __user *)hva, size)) {
68 		sgx_handle_emulation_failure(vcpu, hva, size);
69 		return -EFAULT;
70 	}
71 
72 	return 0;
73 }
74 
75 static int sgx_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t gva, bool write,
76 			  gpa_t *gpa)
77 {
78 	struct x86_exception ex;
79 
80 	if (write)
81 		*gpa = kvm_mmu_gva_to_gpa_write(vcpu, gva, &ex);
82 	else
83 		*gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, &ex);
84 
85 	if (*gpa == INVALID_GPA) {
86 		kvm_inject_emulated_page_fault(vcpu, &ex);
87 		return -EFAULT;
88 	}
89 
90 	return 0;
91 }
92 
93 static int sgx_gpa_to_hva(struct kvm_vcpu *vcpu, gpa_t gpa, unsigned long *hva)
94 {
95 	*hva = kvm_vcpu_gfn_to_hva(vcpu, PFN_DOWN(gpa));
96 	if (kvm_is_error_hva(*hva)) {
97 		sgx_handle_emulation_failure(vcpu, gpa, 1);
98 		return -EFAULT;
99 	}
100 
101 	*hva |= gpa & ~PAGE_MASK;
102 
103 	return 0;
104 }
105 
106 static int sgx_inject_fault(struct kvm_vcpu *vcpu, gva_t gva, int trapnr)
107 {
108 	struct x86_exception ex;
109 
110 	/*
111 	 * A non-EPCM #PF indicates a bad userspace HVA.  This *should* check
112 	 * for PFEC.SGX and not assume any #PF on SGX2 originated in the EPC,
113 	 * but the error code isn't (yet) plumbed through the ENCLS helpers.
114 	 */
115 	if (trapnr == PF_VECTOR && !boot_cpu_has(X86_FEATURE_SGX2)) {
116 		kvm_prepare_emulation_failure_exit(vcpu);
117 		return 0;
118 	}
119 
120 	/*
121 	 * If the guest thinks it's running on SGX2 hardware, inject an SGX
122 	 * #PF if the fault matches an EPCM fault signature (#GP on SGX1,
123 	 * #PF on SGX2).  The assumption is that EPCM faults are much more
124 	 * likely than a bad userspace address.
125 	 */
126 	if ((trapnr == PF_VECTOR || !boot_cpu_has(X86_FEATURE_SGX2)) &&
127 	    guest_cpu_cap_has(vcpu, X86_FEATURE_SGX2)) {
128 		memset(&ex, 0, sizeof(ex));
129 		ex.vector = PF_VECTOR;
130 		ex.error_code = PFERR_PRESENT_MASK | PFERR_WRITE_MASK |
131 				PFERR_SGX_MASK;
132 		ex.address = gva;
133 		ex.error_code_valid = true;
134 		ex.nested_page_fault = false;
135 		kvm_inject_emulated_page_fault(vcpu, &ex);
136 	} else {
137 		kvm_inject_gp(vcpu, 0);
138 	}
139 	return 1;
140 }
141 
142 static int __handle_encls_ecreate(struct kvm_vcpu *vcpu,
143 				  struct sgx_pageinfo *pageinfo,
144 				  unsigned long secs_hva,
145 				  gva_t secs_gva)
146 {
147 	struct sgx_secs *contents = (struct sgx_secs *)pageinfo->contents;
148 	struct kvm_cpuid_entry2 *sgx_12_0, *sgx_12_1;
149 	u64 attributes, xfrm, size;
150 	u32 miscselect;
151 	u8 max_size_log2;
152 	int trapnr, ret;
153 
154 	sgx_12_0 = kvm_find_cpuid_entry_index(vcpu, 0x12, 0);
155 	sgx_12_1 = kvm_find_cpuid_entry_index(vcpu, 0x12, 1);
156 	if (!sgx_12_0 || !sgx_12_1) {
157 		kvm_prepare_emulation_failure_exit(vcpu);
158 		return 0;
159 	}
160 
161 	miscselect = contents->miscselect;
162 	attributes = contents->attributes;
163 	xfrm = contents->xfrm;
164 	size = contents->size;
165 
166 	/* Enforce restriction of access to the PROVISIONKEY. */
167 	if (!vcpu->kvm->arch.sgx_provisioning_allowed &&
168 	    (attributes & SGX_ATTR_PROVISIONKEY)) {
169 		if (sgx_12_1->eax & SGX_ATTR_PROVISIONKEY)
170 			pr_warn_once("SGX PROVISIONKEY advertised but not allowed\n");
171 		kvm_inject_gp(vcpu, 0);
172 		return 1;
173 	}
174 
175 	/*
176 	 * Enforce CPUID restrictions on MISCSELECT, ATTRIBUTES and XFRM.  Note
177 	 * that the allowed XFRM (XFeature Request Mask) isn't strictly bound
178 	 * by the supported XCR0.  FP+SSE *must* be set in XFRM, even if XSAVE
179 	 * is unsupported, i.e. even if XCR0 itself is completely unsupported.
180 	 */
181 	if ((u32)miscselect & ~sgx_12_0->ebx ||
182 	    (u32)attributes & ~sgx_12_1->eax ||
183 	    (u32)(attributes >> 32) & ~sgx_12_1->ebx ||
184 	    (u32)xfrm & ~sgx_12_1->ecx ||
185 	    (u32)(xfrm >> 32) & ~sgx_12_1->edx ||
186 	    xfrm & ~(vcpu->arch.guest_supported_xcr0 | XFEATURE_MASK_FPSSE) ||
187 	    (xfrm & XFEATURE_MASK_FPSSE) != XFEATURE_MASK_FPSSE) {
188 		kvm_inject_gp(vcpu, 0);
189 		return 1;
190 	}
191 
192 	/* Enforce CPUID restriction on max enclave size. */
193 	max_size_log2 = (attributes & SGX_ATTR_MODE64BIT) ? sgx_12_0->edx >> 8 :
194 							    sgx_12_0->edx;
195 	if (size >= BIT_ULL(max_size_log2)) {
196 		kvm_inject_gp(vcpu, 0);
197 		return 1;
198 	}
199 
200 	/*
201 	 * sgx_virt_ecreate() returns:
202 	 *  1) 0:	ECREATE was successful
203 	 *  2) -EFAULT:	ECREATE was run but faulted, and trapnr was set to the
204 	 *		exception number.
205 	 *  3) -EINVAL:	access_ok() on @secs_hva failed. This should never
206 	 *		happen as KVM checks host addresses at memslot creation.
207 	 *		sgx_virt_ecreate() has already warned in this case.
208 	 */
209 	ret = sgx_virt_ecreate(pageinfo, (void __user *)secs_hva, &trapnr);
210 	if (!ret)
211 		return kvm_skip_emulated_instruction(vcpu);
212 	if (ret == -EFAULT)
213 		return sgx_inject_fault(vcpu, secs_gva, trapnr);
214 
215 	return ret;
216 }
217 
218 static int handle_encls_ecreate(struct kvm_vcpu *vcpu)
219 {
220 	gva_t pageinfo_gva, secs_gva;
221 	gva_t metadata_gva, contents_gva;
222 	gpa_t metadata_gpa, contents_gpa, secs_gpa;
223 	unsigned long metadata_hva, contents_hva, secs_hva;
224 	struct sgx_pageinfo pageinfo;
225 	struct sgx_secs *contents;
226 	struct x86_exception ex;
227 	int r;
228 
229 	if (sgx_get_encls_gva(vcpu, kvm_rbx_read(vcpu), 32, 32, &pageinfo_gva) ||
230 	    sgx_get_encls_gva(vcpu, kvm_rcx_read(vcpu), 4096, 4096, &secs_gva))
231 		return 1;
232 
233 	/*
234 	 * Copy the PAGEINFO to local memory, its pointers need to be
235 	 * translated, i.e. we need to do a deep copy/translate.
236 	 */
237 	r = kvm_read_guest_virt(vcpu, pageinfo_gva, &pageinfo,
238 				sizeof(pageinfo), &ex);
239 	if (r == X86EMUL_PROPAGATE_FAULT) {
240 		kvm_inject_emulated_page_fault(vcpu, &ex);
241 		return 1;
242 	} else if (r != X86EMUL_CONTINUE) {
243 		sgx_handle_emulation_failure(vcpu, pageinfo_gva,
244 					     sizeof(pageinfo));
245 		return 0;
246 	}
247 
248 	if (sgx_get_encls_gva(vcpu, pageinfo.metadata, 64, 64, &metadata_gva) ||
249 	    sgx_get_encls_gva(vcpu, pageinfo.contents, 4096, 4096,
250 			      &contents_gva))
251 		return 1;
252 
253 	/*
254 	 * Translate the SECINFO, SOURCE and SECS pointers from GVA to GPA.
255 	 * Resume the guest on failure to inject a #PF.
256 	 */
257 	if (sgx_gva_to_gpa(vcpu, metadata_gva, false, &metadata_gpa) ||
258 	    sgx_gva_to_gpa(vcpu, contents_gva, false, &contents_gpa) ||
259 	    sgx_gva_to_gpa(vcpu, secs_gva, true, &secs_gpa))
260 		return 1;
261 
262 	/*
263 	 * ...and then to HVA.  The order of accesses isn't architectural, i.e.
264 	 * KVM doesn't have to fully process one address at a time.  Exit to
265 	 * userspace if a GPA is invalid.
266 	 */
267 	if (sgx_gpa_to_hva(vcpu, metadata_gpa, &metadata_hva) ||
268 	    sgx_gpa_to_hva(vcpu, contents_gpa, &contents_hva) ||
269 	    sgx_gpa_to_hva(vcpu, secs_gpa, &secs_hva))
270 		return 0;
271 
272 	/*
273 	 * Copy contents into kernel memory to prevent TOCTOU attack. E.g. the
274 	 * guest could do ECREATE w/ SECS.SGX_ATTR_PROVISIONKEY=0, and
275 	 * simultaneously set SGX_ATTR_PROVISIONKEY to bypass the check to
276 	 * enforce restriction of access to the PROVISIONKEY.
277 	 */
278 	contents = (struct sgx_secs *)__get_free_page(GFP_KERNEL);
279 	if (!contents)
280 		return -ENOMEM;
281 
282 	/* Exit to userspace if copying from a host userspace address fails. */
283 	if (sgx_read_hva(vcpu, contents_hva, (void *)contents, PAGE_SIZE)) {
284 		free_page((unsigned long)contents);
285 		return 0;
286 	}
287 
288 	pageinfo.metadata = metadata_hva;
289 	pageinfo.contents = (u64)contents;
290 
291 	r = __handle_encls_ecreate(vcpu, &pageinfo, secs_hva, secs_gva);
292 
293 	free_page((unsigned long)contents);
294 
295 	return r;
296 }
297 
298 static int handle_encls_einit(struct kvm_vcpu *vcpu)
299 {
300 	unsigned long sig_hva, secs_hva, token_hva, rflags;
301 	struct vcpu_vmx *vmx = to_vmx(vcpu);
302 	gva_t sig_gva, secs_gva, token_gva;
303 	gpa_t sig_gpa, secs_gpa, token_gpa;
304 	int ret, trapnr;
305 
306 	if (sgx_get_encls_gva(vcpu, kvm_rbx_read(vcpu), 1808, 4096, &sig_gva) ||
307 	    sgx_get_encls_gva(vcpu, kvm_rcx_read(vcpu), 4096, 4096, &secs_gva) ||
308 	    sgx_get_encls_gva(vcpu, kvm_rdx_read(vcpu), 304, 512, &token_gva))
309 		return 1;
310 
311 	/*
312 	 * Translate the SIGSTRUCT, SECS and TOKEN pointers from GVA to GPA.
313 	 * Resume the guest on failure to inject a #PF.
314 	 */
315 	if (sgx_gva_to_gpa(vcpu, sig_gva, false, &sig_gpa) ||
316 	    sgx_gva_to_gpa(vcpu, secs_gva, true, &secs_gpa) ||
317 	    sgx_gva_to_gpa(vcpu, token_gva, false, &token_gpa))
318 		return 1;
319 
320 	/*
321 	 * ...and then to HVA.  The order of accesses isn't architectural, i.e.
322 	 * KVM doesn't have to fully process one address at a time.  Exit to
323 	 * userspace if a GPA is invalid.  Note, all structures are aligned and
324 	 * cannot split pages.
325 	 */
326 	if (sgx_gpa_to_hva(vcpu, sig_gpa, &sig_hva) ||
327 	    sgx_gpa_to_hva(vcpu, secs_gpa, &secs_hva) ||
328 	    sgx_gpa_to_hva(vcpu, token_gpa, &token_hva))
329 		return 0;
330 
331 	ret = sgx_virt_einit((void __user *)sig_hva, (void __user *)token_hva,
332 			     (void __user *)secs_hva,
333 			     vmx->msr_ia32_sgxlepubkeyhash, &trapnr);
334 
335 	if (ret == -EFAULT)
336 		return sgx_inject_fault(vcpu, secs_gva, trapnr);
337 
338 	/*
339 	 * sgx_virt_einit() returns -EINVAL when access_ok() fails on @sig_hva,
340 	 * @token_hva or @secs_hva. This should never happen as KVM checks host
341 	 * addresses at memslot creation. sgx_virt_einit() has already warned
342 	 * in this case, so just return.
343 	 */
344 	if (ret < 0)
345 		return ret;
346 
347 	rflags = vmx_get_rflags(vcpu) & ~(X86_EFLAGS_CF | X86_EFLAGS_PF |
348 					  X86_EFLAGS_AF | X86_EFLAGS_SF |
349 					  X86_EFLAGS_OF);
350 	if (ret)
351 		rflags |= X86_EFLAGS_ZF;
352 	else
353 		rflags &= ~X86_EFLAGS_ZF;
354 	vmx_set_rflags(vcpu, rflags);
355 
356 	kvm_eax_write(vcpu, ret);
357 	return kvm_skip_emulated_instruction(vcpu);
358 }
359 
360 static inline bool encls_leaf_enabled_in_guest(struct kvm_vcpu *vcpu, u32 leaf)
361 {
362 	/*
363 	 * ENCLS generates a #UD if SGX1 isn't supported, i.e. this point will
364 	 * be reached if and only if the SGX1 leafs are enabled.
365 	 */
366 	if (leaf >= ECREATE && leaf <= ETRACK)
367 		return true;
368 
369 	if (leaf >= EAUG && leaf <= EMODT)
370 		return guest_cpu_cap_has(vcpu, X86_FEATURE_SGX2);
371 
372 	return false;
373 }
374 
375 static inline bool sgx_enabled_in_guest_bios(struct kvm_vcpu *vcpu)
376 {
377 	const u64 bits = FEAT_CTL_SGX_ENABLED | FEAT_CTL_LOCKED;
378 
379 	return (to_vmx(vcpu)->msr_ia32_feature_control & bits) == bits;
380 }
381 
382 int handle_encls(struct kvm_vcpu *vcpu)
383 {
384 	u32 leaf = kvm_eax_read(vcpu);
385 
386 	if (!enable_sgx || !guest_cpu_cap_has(vcpu, X86_FEATURE_SGX) ||
387 	    !guest_cpu_cap_has(vcpu, X86_FEATURE_SGX1)) {
388 		kvm_queue_exception(vcpu, UD_VECTOR);
389 	} else if (!encls_leaf_enabled_in_guest(vcpu, leaf) ||
390 		   !sgx_enabled_in_guest_bios(vcpu) || !is_paging(vcpu)) {
391 		kvm_inject_gp(vcpu, 0);
392 	} else {
393 		if (leaf == ECREATE)
394 			return handle_encls_ecreate(vcpu);
395 		if (leaf == EINIT)
396 			return handle_encls_einit(vcpu);
397 		WARN_ONCE(1, "unexpected exit on ENCLS[%u]", leaf);
398 		vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
399 		vcpu->run->hw.hardware_exit_reason = EXIT_REASON_ENCLS;
400 		return 0;
401 	}
402 	return 1;
403 }
404 
405 void setup_default_sgx_lepubkeyhash(void)
406 {
407 	/*
408 	 * Use Intel's default value for Skylake hardware if Launch Control is
409 	 * not supported, i.e. Intel's hash is hardcoded into silicon, or if
410 	 * Launch Control is supported and enabled, i.e. mimic the reset value
411 	 * and let the guest write the MSRs at will.  If Launch Control is
412 	 * supported but disabled, then use the current MSR values as the hash
413 	 * MSRs exist but are read-only (locked and not writable).
414 	 */
415 	if (!enable_sgx || boot_cpu_has(X86_FEATURE_SGX_LC) ||
416 	    rdmsrq_safe(MSR_IA32_SGXLEPUBKEYHASH0, &sgx_pubkey_hash[0])) {
417 		sgx_pubkey_hash[0] = 0xa6053e051270b7acULL;
418 		sgx_pubkey_hash[1] = 0x6cfbe8ba8b3b413dULL;
419 		sgx_pubkey_hash[2] = 0xc4916d99f2b3735dULL;
420 		sgx_pubkey_hash[3] = 0xd4f8c05909f9bb3bULL;
421 	} else {
422 		/* MSR_IA32_SGXLEPUBKEYHASH0 is read above */
423 		rdmsrq(MSR_IA32_SGXLEPUBKEYHASH1, sgx_pubkey_hash[1]);
424 		rdmsrq(MSR_IA32_SGXLEPUBKEYHASH2, sgx_pubkey_hash[2]);
425 		rdmsrq(MSR_IA32_SGXLEPUBKEYHASH3, sgx_pubkey_hash[3]);
426 	}
427 }
428 
429 void vcpu_setup_sgx_lepubkeyhash(struct kvm_vcpu *vcpu)
430 {
431 	struct vcpu_vmx *vmx = to_vmx(vcpu);
432 
433 	memcpy(vmx->msr_ia32_sgxlepubkeyhash, sgx_pubkey_hash,
434 	       sizeof(sgx_pubkey_hash));
435 }
436 
437 /*
438  * ECREATE must be intercepted to enforce MISCSELECT, ATTRIBUTES and XFRM
439  * restrictions if the guest's allowed-1 settings diverge from hardware.
440  */
441 static bool sgx_intercept_encls_ecreate(struct kvm_vcpu *vcpu)
442 {
443 	struct kvm_cpuid_entry2 *guest_cpuid;
444 	u32 eax, ebx, ecx, edx;
445 
446 	if (!vcpu->kvm->arch.sgx_provisioning_allowed)
447 		return true;
448 
449 	guest_cpuid = kvm_find_cpuid_entry_index(vcpu, 0x12, 0);
450 	if (!guest_cpuid)
451 		return true;
452 
453 	cpuid_count(0x12, 0, &eax, &ebx, &ecx, &edx);
454 	if (guest_cpuid->ebx != ebx || guest_cpuid->edx != edx)
455 		return true;
456 
457 	guest_cpuid = kvm_find_cpuid_entry_index(vcpu, 0x12, 1);
458 	if (!guest_cpuid)
459 		return true;
460 
461 	cpuid_count(0x12, 1, &eax, &ebx, &ecx, &edx);
462 	if (guest_cpuid->eax != eax || guest_cpuid->ebx != ebx ||
463 	    guest_cpuid->ecx != ecx || guest_cpuid->edx != edx)
464 		return true;
465 
466 	return false;
467 }
468 
469 void vmx_write_encls_bitmap(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
470 {
471 	/*
472 	 * There is no software enable bit for SGX that is virtualized by
473 	 * hardware, e.g. there's no CR4.SGXE, so when SGX is disabled in the
474 	 * guest (either by the host or by the guest's BIOS) but enabled in the
475 	 * host, trap all ENCLS leafs and inject #UD/#GP as needed to emulate
476 	 * the expected system behavior for ENCLS.
477 	 */
478 	u64 bitmap = -1ull;
479 
480 	/* Nothing to do if hardware doesn't support SGX */
481 	if (!cpu_has_vmx_encls_vmexit())
482 		return;
483 
484 	if (guest_cpu_cap_has(vcpu, X86_FEATURE_SGX) &&
485 	    sgx_enabled_in_guest_bios(vcpu)) {
486 		if (guest_cpu_cap_has(vcpu, X86_FEATURE_SGX1)) {
487 			bitmap &= ~GENMASK_ULL(ETRACK, ECREATE);
488 			if (sgx_intercept_encls_ecreate(vcpu))
489 				bitmap |= (1 << ECREATE);
490 		}
491 
492 		if (guest_cpu_cap_has(vcpu, X86_FEATURE_SGX2))
493 			bitmap &= ~GENMASK_ULL(EMODT, EAUG);
494 
495 		/*
496 		 * Trap and execute EINIT if launch control is enabled in the
497 		 * host using the guest's values for launch control MSRs, even
498 		 * if the guest's values are fixed to hardware default values.
499 		 * The MSRs are not loaded/saved on VM-Enter/VM-Exit as writing
500 		 * the MSRs is extraordinarily expensive.
501 		 */
502 		if (boot_cpu_has(X86_FEATURE_SGX_LC))
503 			bitmap |= (1 << EINIT);
504 
505 		if (!vmcs12 && is_guest_mode(vcpu))
506 			vmcs12 = get_vmcs12(vcpu);
507 		if (vmcs12 && nested_cpu_has_encls_exit(vmcs12))
508 			bitmap |= vmcs12->encls_exiting_bitmap;
509 	}
510 	vmcs_write64(ENCLS_EXITING_BITMAP, bitmap);
511 }
512