Skip to contentSkip to conversation

KVM: nVMX: Don't flush shadow VMCS12 to guest memory during vCPU teardown

PATCH In review Jim Mattson 4 participants 15 messages Sep 8 – Oct 1

Subsystems (5)
Stable branch x86 KVM Kselftest +1 more subsystems
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 KVM: nVMX: Don't flush shadow VMCS12 to guest memory during vCPU teardown

When a vCPU is destroyed while L2 is active, KVM synthesizes a nested VM-Exit, which flushes the cached shadow VMCS12 back to guest memory:

vmx_vcpu_free()
|-> nested_vmx_free_vcpu()

      |-> vmx_leave_nested()
          |-> nested_vmx_vmexit(vcpu, -1, 0, 0)
              |-> nested_flush_cached_shadow_vmcs12()
                  |-> kvm_write_guest_cached()
                      |-> __copy_to_user(ghc->hva, ...)

During process exit, do_exit() calls exit_mm() before closing file descriptors, so vCPU destruction runs with current->mm == NULL on a borrowed lazy TLB active_mm. If the borrowed address space has a writable mapping at ghc->hva, __copy_to_user() corrupts an unrelated task's memory.

Skip the flush when KVM synthesizes a VM-exit with vm_exit_reason == -1 (e.g. during vCPU teardown or SMM entry). In these paths, KVM forces the vCPU out of guest mode internally--no architectural VM-exit is delivered to L1.

Fixes 61ada7488ffd ("KVM: nVMX: Cache shadow vmcs12 on VMEntry and flush to memory on VMExit")
---
 arch/x86/kvm/vmx/nested.c | 29 ++++++++++++++++++-----------
 1 file changed, 18 insertions(+), 11 deletions(-)
arch/x86/kvm/vmx/nested.c +18 -11
index 151873407abd..33dc8a07019f 100644
@@ -5121,21 +5121,28 @@ void __nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 vm_exit_reason,
 	if (likely(!vmx->fail)) {
 		sync_vmcs02_to_vmcs12(vcpu, vmcs12);
 
-		if (vm_exit_reason != -1)
+		if (vm_exit_reason != -1) {
 			prepare_vmcs12(vcpu, vmcs12, vm_exit_reason,
 				       exit_intr_info, exit_qualification,
 				       exit_insn_len);
 
-		/*
-		 * Must happen outside of sync_vmcs02_to_vmcs12() as it will
-		 * also be used to capture vmcs12 cache as part of
-		 * capturing nVMX state for snapshot (migration).
-		 *
-		 * Otherwise, this flush will dirty guest memory at a
-		 * point it is already assumed by user-space to be
-		 * immutable.
-		 */
-		nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
+			/*
+			 * Must happen outside of sync_vmcs02_to_vmcs12() as it will
+			 * also be used to capture vmcs12 cache as part of
+			 * capturing nVMX state for snapshot (migration).
+			 *
+			 * Otherwise, this flush will dirty guest memory at a
+			 * point it is already assumed by user-space to be
+			 * immutable.
+			 *
+			 * Do not flush when vm_exit_reason == -1 (e.g. forced exit
+			 * on vCPU teardown or SMM entry). On teardown, KVM may run
+			 * with current->mm == NULL on a borrowed lazy TLB mm,
+			 * where writing guest memory would corrupt an unrelated
+			 * task. Nothing can observe the flush in that case anyway.
+			 */
+			nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
+		}
 	} else {
 		/*
 		 * The only expected VM-instruction error is "VM entry with

base-commit: 28924df2a08f440c73991b83028032c901de2ae4

Signature · 1 line
2.55.0.979.g7e5102b832-goog
#1 lore raw
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

Pre-existing issues:
- [Critical] Live migration during SMM with an active nested guest overwrites L2 state (e.g. RIP/RSP) with stale data from the hardware shadow VMCS.
- [High] Live migration during SMM with nested shadow VMCS enabled causes a Triple Fault on the destination.
- [High] During vCPU teardown, __nested_vmx_vmexit() unconditionally loads L1 host state, triggering a cross-process memory read via load_pdptrs() with a borrowed active_mm. --

commit 15d3183acc0011b1c1063bab25d832a346f7a45c
Author: Jim Mattson <[email protected]>

KVM: nVMX: Don't flush shadow VMCS12 to guest memory during vCPU teardown

When a vCPU is destroyed while L2 is active, KVM synthesizes a nested VM-Exit. During this process exit, the vCPU destruction runs with a borrowed lazy TLB active_mm, so skipping the shadow VMCS12 flush prevents __copy_to_user() from corrupting an unrelated task's memory.

Quoted 34 lines
arch/x86/kvm/vmx/nested.c +11 -11
index 151873407abd3..33dc8a07019f8 100644
@@ -5121,21 +5121,28 @@ void __nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 vm_exit_reason,
 	if (likely(!vmx->fail)) {
 		sync_vmcs02_to_vmcs12(vcpu, vmcs12);
 
-		if (vm_exit_reason != -1)
+		if (vm_exit_reason != -1) {
 			prepare_vmcs12(vcpu, vmcs12, vm_exit_reason,
 				       exit_intr_info, exit_qualification,
 				       exit_insn_len);
 
-		/*
-		 * Must happen outside of sync_vmcs02_to_vmcs12() as it will
-		 * also be used to capture vmcs12 cache as part of
-		 * capturing nVMX state for snapshot (migration).
-		 *
-		 * Otherwise, this flush will dirty guest memory at a
-		 * point it is already assumed by user-space to be
-		 * immutable.
-		 */
-		nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
+			/*
+			 * Must happen outside of sync_vmcs02_to_vmcs12() as it will
+			 * also be used to capture vmcs12 cache as part of
+			 * capturing nVMX state for snapshot (migration).
+			 *
+			 * Otherwise, this flush will dirty guest memory at a
+			 * point it is already assumed by user-space to be
+			 * immutable.
+			 *
+			 * Do not flush when vm_exit_reason == -1 (e.g. forced exit

arch/x86/kvm/vmx/nested.c void __nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 vm_exit_reason, · line 5148

Quoted 10 lines
arch/x86/kvm/vmx/nested.c +7 -0
+			 * on vCPU teardown or SMM entry). On teardown, KVM may run
+			 * with current->mm == NULL on a borrowed lazy TLB mm,
+			 * where writing guest memory would corrupt an unrelated
+			 * task. Nothing can observe the flush in that case anyway.
+			 */
+			nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
+		}
 	} else {
 		/*
 		 * The only expected VM-instruction error is "VM entry with

[Severity: High]
This is a pre-existing issue, but since this patch handles vCPU teardown with a borrowed active_mm, does the later call to load_vmcs12_host_state() in __nested_vmx_vmexit() have a similar issue?

During vCPU teardown, __nested_vmx_vmexit() unconditionally loads L1 host state:

arch/x86/kvm/vmx/nested.c:__nested_vmx_vmexit() {
    ...
    load_vmcs12_host_state(vcpu, vmcs12);
    ...
}

If the L1 host state uses PAE paging, nested_vmx_load_cr3() triggers the PDPTR load:

arch/x86/kvm/vmx/nested.c:nested_vmx_load_cr3() {
    ...
    if (reload_pdptrs && !nested_ept && is_pae_paging(vcpu) &&
        CC(!load_pdptrs(vcpu, cr3))) {
    ...
}

This executes a memory read using copy_from_user() in the context of the borrowed active_mm:

arch/x86/kvm/regs.c:load_pdptrs() {
    ...
    ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(real_gpa), pdpte,
                                   cr3 & GENMASK(11, 5), sizeof(pdpte));
    ...
}

Could this cross-process memory read cause destructive side-effects if it hits a memory-mapped I/O (MMIO) region in the unrelated task?

[Severity: Critical]
This is a pre-existing issue, but does skipping the shadow VMCS12 flush on SMM entry (where vm_exit_reason == -1) cause data corruption during live migration?

In __nested_vmx_vmexit(), need_vmcs12_to_shadow_sync is prevented from being set on SMM entry because of the vm_exit_reason check:

arch/x86/kvm/vmx/nested.c:__nested_vmx_vmexit() {
    ...
    if ((vm_exit_reason != -1) &&
        (enable_shadow_vmcs || nested_vmx_is_evmptr12_valid(vmx)))
        vmx->nested.need_vmcs12_to_shadow_sync = true;
    ...
}

If live migration is initiated while in SMM, vmx_get_nested_state() treats the hardware shadow VMCS as authoritative:

arch/x86/kvm/vmx/nested.c:vmx_get_nested_state() {
    ...
    else if (enable_shadow_vmcs)
        copy_shadow_to_vmcs12(vmx);
    ...
}

Since need_vmcs12_to_shadow_sync was not set, doesn't this overwrite the correctly synced vmcs12 with stale data from the hardware shadow VMCS, resulting in guest state rollback (e.g., RIP/RSP)?

[Severity: High]
This isn't a bug introduced by this patch, but is there a Triple Fault risk during live migration in SMM with nested shadow VMCS enabled?

Because is_guest_mode is false in SMM, the shadow_vmcs12 is omitted from the migration stream:

arch/x86/kvm/vmx/nested.c:vmx_get_nested_state() {
    ...
    if (is_guest_mode(vcpu) &&
        nested_cpu_has_shadow_vmcs(vmcs12) &&
        vmcs12->vmcs_link_pointer != INVALID_GPA)
        kvm_state.size += sizeof(user_vmx_nested_state->shadow_vmcs12);
    ...
}

On the destination, vmx_set_nested_state() skips restoring shadow_vmcs12 and returns early:

arch/x86/kvm/vmx/nested.c:vmx_set_nested_state() {
    ...
    if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
        return 0;
    ...
}

When the guest leaves SMM, vmx_leave_smm() checks the revision ID of the zeroed shadow_vmcs12:

arch/x86/kvm/vmx/vmx.c:vmx_leave_smm() {
    ...
    /* Triple fault if the state is invalid.  */
    if (nested_vmx_check_restored_vmcs12(vcpu) < 0)
        return 1;
    ...
}

Could this zeroed buffer fail the revision ID check and induce a Triple Fault?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#2 lore raw
In reply to Jim Mattson
Quoted 17 lines · Jim Mattson

When a vCPU is destroyed while L2 is active, KVM synthesizes a nested VM-Exit, which flushes the cached shadow VMCS12 back to guest memory:

vmx_vcpu_free()
|-> nested_vmx_free_vcpu()

      |-> vmx_leave_nested()
          |-> nested_vmx_vmexit(vcpu, -1, 0, 0)
              |-> nested_flush_cached_shadow_vmcs12()
                  |-> kvm_write_guest_cached()
                      |-> __copy_to_user(ghc->hva, ...)

During process exit, do_exit() calls exit_mm() before closing file descriptors, so vCPU destruction runs with current->mm == NULL on a borrowed lazy TLB active_mm. If the borrowed address space has a writable mapping at ghc->hva, __copy_to_user() corrupts an unrelated task's memory.

Quoted 8 lines

Skip the flush when KVM synthesizes a VM-exit with vm_exit_reason == -1 (e.g. during vCPU teardown or SMM entry). In these paths, KVM forces the vCPU out of guest mode internally--no architectural VM-exit is delivered to L1.

Fixes 61ada7488ffd ("KVM: nVMX: Cache shadow vmcs12 on VMEntry and flush to memory on VMExit")

Hi Jim,

This patch looks good for a stable backport, but I feel this kind of bug could easily happen again with the current API.

One simple thing that would have prevented this would be to:
1. Change kvm_write_guest_cached() (and related) to take the vcpu instead of the kvm, and
2. Check that vcpu->mm == current->mm before doing the uaccess.

This wouldn't be as suitable for a backport, but I think it's better for preventing similar classes of bugs. I'm sure you (and Paolo/Sean/others) will have better ideas. What do you think?

Thank you very much for debugging this. :)

#3 lore raw
Quoted 33 lines · James Houghton
Quoted 17 lines · Jim Mattson

When a vCPU is destroyed while L2 is active, KVM synthesizes a nested VM-Exit, which flushes the cached shadow VMCS12 back to guest memory:

vmx_vcpu_free()
|-> nested_vmx_free_vcpu()

      |-> vmx_leave_nested()
          |-> nested_vmx_vmexit(vcpu, -1, 0, 0)
              |-> nested_flush_cached_shadow_vmcs12()
                  |-> kvm_write_guest_cached()
                      |-> __copy_to_user(ghc->hva, ...)

During process exit, do_exit() calls exit_mm() before closing file descriptors, so vCPU destruction runs with current->mm == NULL on a borrowed lazy TLB active_mm. If the borrowed address space has a writable mapping at ghc->hva, __copy_to_user() corrupts an unrelated task's memory.

Quoted 8 lines

Skip the flush when KVM synthesizes a VM-exit with vm_exit_reason == -1 (e.g. during vCPU teardown or SMM entry). In these paths, KVM forces the vCPU out of guest mode internally--no architectural VM-exit is delivered to L1.

Fixes 61ada7488ffd ("KVM: nVMX: Cache shadow vmcs12 on VMEntry and flush to memory on VMExit")

Hi Jim,

This patch looks good for a stable backport, but I feel this kind of bug could easily happen again with the current API.

Quoted 8 lines

One simple thing that would have prevented this would be to:
1. Change kvm_write_guest_cached() (and related) to take the vcpu instead of the kvm, and
2. Check that vcpu->mm == current->mm before doing the uaccess.

This wouldn't be as suitable for a backport, but I think it's better for preventing similar classes of bugs. I'm sure you (and Paolo/Sean/others) will have better ideas. What do you think?

There seems to be some awareness of this issue within KVM, so that may not be necessary. Also, as Sashiko points out, we have issues with reads as well as writes. I don't know how many choke points we'd have to test.

AFAICT (with AI assistance), all of the current problems are rooted in the following call to nested_vmx_vmexit():

void vmx_leave_nested(struct kvm_vcpu *vcpu)

{
        if (is_guest_mode(vcpu)) {
                vcpu->arch.nested_run_pending = 0;
                nested_vmx_vmexit(vcpu, -1, 0, 0);
        }
        free_nested(vcpu);
}

On the SVM side, there is no comparable faux VM-exit. Instead of calling nested_svm_vmexit(), the teardown of SVM nested state is an open-coded sequence. Maybe something like that would work better for VMX?

#4 lore raw
Quoted 33 lines · Jim Mattson
Quoted 5 lines · James Houghton

Hi Jim,

This patch looks good for a stable backport, but I feel this kind of bug could easily happen again with the current API.

Quoted 8 lines

One simple thing that would have prevented this would be to:
1. Change kvm_write_guest_cached() (and related) to take the vcpu instead of the kvm, and
2. Check that vcpu->mm == current->mm before doing the uaccess.

This wouldn't be as suitable for a backport, but I think it's better for preventing similar classes of bugs. I'm sure you (and Paolo/Sean/others) will have better ideas. What do you think?

There seems to be some awareness of this issue within KVM, so that may not be necessary. Also, as Sashiko points out, we have issues with reads as well as writes. I don't know how many choke points we'd have to test.

AFAICT (with AI assistance), all of the current problems are rooted in the following call to nested_vmx_vmexit():

void vmx_leave_nested(struct kvm_vcpu *vcpu)

{
        if (is_guest_mode(vcpu)) {
                vcpu->arch.nested_run_pending = 0;
                nested_vmx_vmexit(vcpu, -1, 0, 0);
        }
        free_nested(vcpu);
}
Quoted 4 lines

On the SVM side, there is no comparable faux VM-exit. Instead of calling nested_svm_vmexit(), the teardown of SVM nested state is an open-coded sequence. Maybe something like that would work better for VMX?

Maybe, but I don't think I'd feel any better about it (because the change is still KVM/x86-specific).

Thinking harder about this, I think it is always invalid to call copy_to_user() if current->mm is NULL. The riscv implementation[1] seems to require current->mm to be non-NULL. So I'd be much happier with a check in __access_ok() that current->mm != NULL, but I'm not 100% sure that is okay.

I'm also trying to think a little bit harder about the exact mechanism that causes the memory corruption. I think for active_mm (and therefore the loaded page tables/CR3) to be different than the mm we destroyed in exit_mm(), there must have been a context switch to the victim user process and then back to the dying process after exit_mm(). Right?

[1] See arch/riscv/include/asm/uaccess.h

#5 lore raw
In reply to Jim Mattson
Quoted 31 lines · Jim Mattson
Quoted 30 lines · James Houghton
Quoted 17 lines · Jim Mattson

When a vCPU is destroyed while L2 is active, KVM synthesizes a nested VM-Exit, which flushes the cached shadow VMCS12 back to guest memory:

vmx_vcpu_free()
|-> nested_vmx_free_vcpu()

      |-> vmx_leave_nested()
          |-> nested_vmx_vmexit(vcpu, -1, 0, 0)
              |-> nested_flush_cached_shadow_vmcs12()
                  |-> kvm_write_guest_cached()
                      |-> __copy_to_user(ghc->hva, ...)

During process exit, do_exit() calls exit_mm() before closing file descriptors, so vCPU destruction runs with current->mm == NULL on a borrowed lazy TLB active_mm. If the borrowed address space has a writable mapping at ghc->hva, __copy_to_user() corrupts an unrelated task's memory.

Quoted 8 lines

Skip the flush when KVM synthesizes a VM-exit with vm_exit_reason == -1 (e.g. during vCPU teardown or SMM entry). In these paths, KVM forces the vCPU out of guest mode internally--no architectural VM-exit is delivered to L1.

Fixes 61ada7488ffd ("KVM: nVMX: Cache shadow vmcs12 on VMEntry and flush to memory on VMExit")

Hi Jim,

Quoted 7 lines
Quoted 7 lines

This patch looks good for a stable backport, but I feel this kind of bug could easily happen again with the current API.

One simple thing that would have prevented this would be to:
1. Change kvm_write_guest_cached() (and related) to take the vcpu instead of the kvm, and
2. Check that vcpu->mm == current->mm before doing the uaccess.

The mm pointer is store in "kvm", not in "kvm_vcpu", i.e. this sort of hardening shouldn't require modifying the callsites.

Quoted 21 lines
Quoted 3 lines

This wouldn't be as suitable for a backport, but I think it's better for preventing similar classes of bugs. I'm sure you (and Paolo/Sean/others) will have better ideas. What do you think?

There seems to be some awareness of this issue within KVM, so that may not be necessary. Also, as Sashiko points out, we have issues with reads as well as writes. I don't know how many choke points we'd have to test.

AFAICT (with AI assistance), all of the current problems are rooted in the following call to nested_vmx_vmexit():

void vmx_leave_nested(struct kvm_vcpu *vcpu)

{
        if (is_guest_mode(vcpu)) {
                vcpu->arch.nested_run_pending = 0;
                nested_vmx_vmexit(vcpu, -1, 0, 0);
        }
        free_nested(vcpu);
}
Quoted 4 lines

On the SVM side, there is no comparable faux VM-exit. Instead of calling nested_svm_vmexit(), the teardown of SVM nested state is an open-coded sequence. Maybe something like that would work better for VMX?

Yes, vmx_leave_nested()'s use of nested_vmx_vmexit() is an endless source of pain and needs to be rewritten.

However, the bigger flaw is that the memslots are still valid when the VM is being destroyed. The hardening James suggested above really should be hardening, not the primary mechanism for ensuring correctness.

Manually freeing each memslot one-by-one isn't a great option, because the latency introduced by each synchronize_srcu_expedited() call would be rather absurd. But once KVM unregisters its mmu_notifier, i.e. once kvm_mmu_notifier_release() and thus kvm_flush_shadow_all() runs, all indirect references to memslots need to be gone. And by "indirect references" I mean code in KVM that relies on a memslot existing and being reachable, e.g. x86's rmaps and shadow page accounting.

KVM is infuriatingly close to enforcing that already, as only kvm_arch_destroy_vm() and kvm_destroy_devices() run between unregistering the mmu_notifier and freeing all memslot metadata.

	mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
	/*
	 * At this point, pending calls to invalidate_range_start()
	 * have completed but no more MMU notifiers will run, so
	 * mn_active_invalidate_count may remain unbalanced.
	 * No threads can be waiting in kvm_swap_active_memslots() as the
	 * last reference on KVM has been dropped, but freeing
	 * memslots would deadlock without this manual intervention.
	 *
	 * If the count isn't unbalanced, i.e. KVM did NOT unregister its MMU
	 * notifier between a start() and end(), then there shouldn't be any
	 * in-progress invalidations.
	 */
	WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait));
	if (kvm->mn_active_invalidate_count)
		kvm->mn_active_invalidate_count = 0;
	else
		WARN_ON(kvm->mmu_invalidate_in_progress);
	kvm_arch_destroy_vm(kvm);
	kvm_destroy_devices(kvm);
	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
		kvm_free_memslots(kvm, &kvm->__memslots[i][0]);
		kvm_free_memslots(kvm, &kvm->__memslots[i][1]);  <=== KVM will be very sad after this

	}

Destroying memslots before kvm_destroy_devices() is a-ok, all implementations do nothing more than kvm_io_bus_unregister_dev() (a nop at this point in the VM's lifecycle, as buses are already destroyed), and free of memory.

Unfortunately, kvm_arch_destroy_vm() is practically infeasible to audit. But, we don't need to audit that code, we just need to audit kvm_arch_flush_shadow_memslot(), because if there are memslot references that are dropped by flush_shadow_memslot() but not flush_shadow_all(), then KVM is already buggy and vulnerable.

*sigh*

And of course PPC is a disaster and does literally nothing on flush_shadow_all(). Doubly hilarious, the worst offender seems to be kvmhv_release_all_nested(). As a quick and dirty fix, I think we can simply iterate over memslots and manually flush each one?

Which, amazingly, appears to be safe even though kvmppc_uvmem_drop_pages() takes mmap_lock, as exit_mmap()'s call to mmu_notifier_release() is (thanfully) super obviously done without hold mmap_lock.

	/* mm's last user has gone, and its about to be pulled down */
	mmu_notifier_release(mm);

	mmap_read_lock(mm);
powerpc/include/asm/kvm_host.h +0 -1
index 2d139c807577..1c8d9d7360e9 100644
@@ -903,7 +903,6 @@ struct kvm_vcpu_arch {
 #define __KVM_HAVE_CREATE_DEVICE
 
 static inline void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen) {}
-static inline void kvm_arch_flush_shadow_all(struct kvm *kvm) {}
 static inline void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu) {}
 static inline void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu) {}
 
powerpc/kvm/powerpc.c +11 -0
index 9194cf492d1c..2b88fb9e9bc4 100644
@@ -764,6 +764,17 @@ void kvm_arch_commit_memory_region(struct kvm *kvm,
 	kvmppc_core_commit_memory_region(kvm, old, new, change);
 }
 
+void kvm_arch_flush_shadow_all(struct kvm *kvm)
+{
+	struct kvm_memory_slot *memslot;
+	struct kvm_memslots *slots;
+	int bkt;
+
+	slots = kvm_memslots(kvm);
+	kvm_for_each_memslot(memslot, bkt, slots)
+		kvmppc_core_flush_memslot(kvm, slot);
+}
+
 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
 				   struct kvm_memory_slot *slot)
 {

If the above works for PPC, then KVM can nuke memslots before calling into kvm_arch_destroy_vm(). x86's asinine memslot deletion in kvm_arch_destroy_vm() needs to be addressed, but that code exists purely to do vm_munmap(), and can and should be moved to kvm_arch_free_memslot().

All that said, I'm not sure this aggressive fix is the right thing to send to stable@. For that, James' suggestion of hardening KVM's usage of __copy_{to,from}_user() seems like the best blend of being comprehensive without being overly invasive/risky.

So, as an immediate set of changes, what if we do this over ~5 patches, with patches 1 and 2 tagged for stable@?

1. Add kvm_copy_{to,from}_user{,_inatomic)() and return -EFAULT if current->mm

     is not kvm->mm.

2. Hack-a-fix PPC's kvm_arch_flush_shadow_all().
3. Do x86's vm_munmap() in kvm_arch_free_memslot().
4. Nuke memslots before calling kvm_arch_destroy_vm().
5. Change the current->mm checks in kvm_copy_{to,from}_user{,_inatomic)() to WARN_ON_ONCE() on failure.

And then in the near-ish future, take things a step further and do:

6. Fix the vmx_leave_nested() trainwreck.
7. Harden the common kvm_{read,write}_guest family of APIs even further by adding an early WARN_ON_ONCE() on current->mm != kvm->mm, i.e. to detect bad KVM behavior as additional defense-in-depth.

The diff for #3 and #4 (lightly tested on x86):

arch/x86/kvm/x86.c +14 -22
index 4b3681796c75..f05ba2d1364d 100644
@@ -9925,7 +9925,7 @@ int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
  * @size > 0 to install a new slot, while @size == 0 to uninstall a
  * slot.  The return code can be one of the following:
  *
- *   HVA:           on success (uninstall will return a bogus HVA)
+ *   HVA:           on success (uninstall will return a NULL HVA)
  *   -errno:        on error
  *
  * The caller should always use IS_ERR() to check the return value
@@ -9938,10 +9938,10 @@ int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
 void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
 				      u32 size)
 {
-	int i, r;
-	unsigned long hva, old_npages;
 	struct kvm_memslots *slots = kvm_memslots(kvm);
 	struct kvm_memory_slot *slot;
+	unsigned long hva;
+	int i, r;
 
 	lockdep_assert_held(&kvm->slots_lock);
 
@@ -9965,8 +9965,7 @@ void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
 		if (!slot || !slot->npages)
 			return NULL;
 
-		old_npages = slot->npages;
-		hva = slot->userspace_addr;
+		hva = 0;
 	}
 
 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
@@ -9982,9 +9981,6 @@ void __user * __x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa,
 			return ERR_PTR_USR(r);
 	}
 
-	if (!size)
-		vm_munmap(hva, old_npages * PAGE_SIZE);
-
 	return (void __user *)hva;
 }
 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__x86_set_memory_region);
@@ -10013,20 +10009,6 @@ void kvm_arch_pre_destroy_vm(struct kvm *kvm)
 
 void kvm_arch_destroy_vm(struct kvm *kvm)
 {
-	if (current->mm == kvm->mm) {
-		/*
-		 * Free memory regions allocated on behalf of userspace,
-		 * unless the memory map has changed due to process exit
-		 * or fd copying.
-		 */
-		mutex_lock(&kvm->slots_lock);
-		__x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
-					0, 0);
-		__x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
-					0, 0);
-		__x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
-		mutex_unlock(&kvm->slots_lock);
-	}
 	if (kvm->arch.created_mediated_pmu)
 		perf_release_mediated_pmu();
 	kvm_destroy_vcpus(kvm);
@@ -10066,6 +10048,16 @@ void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
 	}
 
 	kvm_page_track_free_memslot(slot);
+
+	/*
+	 * Free memory regions allocated on behalf of userspace, unless the
+	 * memory map has changed due to process exit or fd copying.  Leak the
+	 * mapping on failure, e.g. if the task is killed, worst case scenario,
+	 * the page(s) will be reclaimed when the process exits.
+	 */
+	if (current->mm == kvm->mm && slot->id >= KVM_USER_MEM_SLOTS &&
+	    !WARN_ON_ONCE(!slot->npages))
+		vm_munmap(slot->userspace_addr, slot->npages * PAGE_SIZE);
 }
 
 int memslot_rmap_alloc(struct kvm_memory_slot *slot, unsigned long npages)
include/linux/kvm_host.h +1 -0
index 03bfc92864b6..bed48f70b2d8 100644
@@ -1693,6 +1693,7 @@ int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu);
 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu);
 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu);
 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu);
+void kvm_arch_destroy_memslots(struct kvm *kvm);
 void kvm_arch_pre_destroy_vm(struct kvm *kvm);
 void kvm_arch_create_vm_debugfs(struct kvm *kvm);
 
virt/kvm/kvm_main.c +28 -14

69 lines not on this page · raw message

#6 lore raw
Quoted 36 lines · Sean Christopherson
Quoted 34 lines · Jim Mattson
Quoted 33 lines · James Houghton
Quoted 17 lines · Jim Mattson

When a vCPU is destroyed while L2 is active, KVM synthesizes a nested VM-Exit, which flushes the cached shadow VMCS12 back to guest memory:

vmx_vcpu_free()
|-> nested_vmx_free_vcpu()

      |-> vmx_leave_nested()
          |-> nested_vmx_vmexit(vcpu, -1, 0, 0)
              |-> nested_flush_cached_shadow_vmcs12()
                  |-> kvm_write_guest_cached()
                      |-> __copy_to_user(ghc->hva, ...)

During process exit, do_exit() calls exit_mm() before closing file descriptors, so vCPU destruction runs with current->mm == NULL on a borrowed lazy TLB active_mm. If the borrowed address space has a writable mapping at ghc->hva, __copy_to_user() corrupts an unrelated task's memory.

Quoted 8 lines

Skip the flush when KVM synthesizes a VM-exit with vm_exit_reason == -1 (e.g. during vCPU teardown or SMM entry). In these paths, KVM forces the vCPU out of guest mode internally--no architectural VM-exit is delivered to L1.

Fixes 61ada7488ffd ("KVM: nVMX: Cache shadow vmcs12 on VMEntry and flush to memory on VMExit")

Hi Jim,

This patch looks good for a stable backport, but I feel this kind of bug could easily happen again with the current API.

Quoted 7 lines
Quoted 4 lines
Quoted 4 lines

One simple thing that would have prevented this would be to:
1. Change kvm_write_guest_cached() (and related) to take the vcpu instead of the kvm, and
2. Check that vcpu->mm == current->mm before doing the uaccess.

The mm pointer is store in "kvm", not in "kvm_vcpu", i.e. this sort of hardening shouldn't require modifying the callsites.

Yeahhh, I noticed this a few minutes after I sent that email, heh. :(

Quoted 135 lines
Quoted 21 lines
Quoted 3 lines

This wouldn't be as suitable for a backport, but I think it's better for preventing similar classes of bugs. I'm sure you (and Paolo/Sean/others) will have better ideas. What do you think?

There seems to be some awareness of this issue within KVM, so that may not be necessary. Also, as Sashiko points out, we have issues with reads as well as writes. I don't know how many choke points we'd have to test.

AFAICT (with AI assistance), all of the current problems are rooted in the following call to nested_vmx_vmexit():

void vmx_leave_nested(struct kvm_vcpu *vcpu)

{
        if (is_guest_mode(vcpu)) {
                vcpu->arch.nested_run_pending = 0;
                nested_vmx_vmexit(vcpu, -1, 0, 0);
        }
        free_nested(vcpu);
}
Quoted 4 lines

On the SVM side, there is no comparable faux VM-exit. Instead of calling nested_svm_vmexit(), the teardown of SVM nested state is an open-coded sequence. Maybe something like that would work better for VMX?

Yes, vmx_leave_nested()'s use of nested_vmx_vmexit() is an endless source of pain and needs to be rewritten.

However, the bigger flaw is that the memslots are still valid when the VM is being destroyed. The hardening James suggested above really should be hardening, not the primary mechanism for ensuring correctness.

Manually freeing each memslot one-by-one isn't a great option, because the latency introduced by each synchronize_srcu_expedited() call would be rather absurd. But once KVM unregisters its mmu_notifier, i.e. once kvm_mmu_notifier_release() and thus kvm_flush_shadow_all() runs, all indirect references to memslots need to be gone. And by "indirect references" I mean code in KVM that relies on a memslot existing and being reachable, e.g. x86's rmaps and shadow page accounting.

KVM is infuriatingly close to enforcing that already, as only kvm_arch_destroy_vm() and kvm_destroy_devices() run between unregistering the mmu_notifier and freeing all memslot metadata.

        mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
        /*
         * At this point, pending calls to invalidate_range_start()
         * have completed but no more MMU notifiers will run, so
         * mn_active_invalidate_count may remain unbalanced.
         * No threads can be waiting in kvm_swap_active_memslots() as the
         * last reference on KVM has been dropped, but freeing
         * memslots would deadlock without this manual intervention.
         *
         * If the count isn't unbalanced, i.e. KVM did NOT unregister its MMU
         * notifier between a start() and end(), then there shouldn't be any
         * in-progress invalidations.
         */
        WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait));
        if (kvm->mn_active_invalidate_count)
                kvm->mn_active_invalidate_count = 0;
        else
                WARN_ON(kvm->mmu_invalidate_in_progress);
        kvm_arch_destroy_vm(kvm);
        kvm_destroy_devices(kvm);
        for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
                kvm_free_memslots(kvm, &kvm->__memslots[i][0]);
                kvm_free_memslots(kvm, &kvm->__memslots[i][1]);  <=== KVM will be very sad after this

        }

Destroying memslots before kvm_destroy_devices() is a-ok, all implementations do nothing more than kvm_io_bus_unregister_dev() (a nop at this point in the VM's lifecycle, as buses are already destroyed), and free of memory.

Unfortunately, kvm_arch_destroy_vm() is practically infeasible to audit. But, we don't need to audit that code, we just need to audit kvm_arch_flush_shadow_memslot(), because if there are memslot references that are dropped by flush_shadow_memslot() but not flush_shadow_all(), then KVM is already buggy and vulnerable.

*sigh*

And of course PPC is a disaster and does literally nothing on flush_shadow_all(). Doubly hilarious, the worst offender seems to be kvmhv_release_all_nested(). As a quick and dirty fix, I think we can simply iterate over memslots and manually flush each one?

Which, amazingly, appears to be safe even though kvmppc_uvmem_drop_pages() takes mmap_lock, as exit_mmap()'s call to mmu_notifier_release() is (thanfully) super obviously done without hold mmap_lock.

        /* mm's last user has gone, and its about to be pulled down */
        mmu_notifier_release(mm);

        mmap_read_lock(mm);
powerpc/include/asm/kvm_host.h +0 -1
index 2d139c807577..1c8d9d7360e9 100644
@@ -903,7 +903,6 @@ struct kvm_vcpu_arch {
 #define __KVM_HAVE_CREATE_DEVICE
 
 static inline void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen) {}
-static inline void kvm_arch_flush_shadow_all(struct kvm *kvm) {}
 static inline void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu) {}
 static inline void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu) {}
 
powerpc/kvm/powerpc.c +11 -0
index 9194cf492d1c..2b88fb9e9bc4 100644
@@ -764,6 +764,17 @@ void kvm_arch_commit_memory_region(struct kvm *kvm,
        kvmppc_core_commit_memory_region(kvm, old, new, change);
 }
 
+void kvm_arch_flush_shadow_all(struct kvm *kvm)
+{
+       struct kvm_memory_slot *memslot;
+       struct kvm_memslots *slots;
+       int bkt;
+
+       slots = kvm_memslots(kvm);
+       kvm_for_each_memslot(memslot, bkt, slots)
+               kvmppc_core_flush_memslot(kvm, slot);
+}
+
 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
                                   struct kvm_memory_slot *slot)
 {

If the above works for PPC, then KVM can nuke memslots before calling into kvm_arch_destroy_vm(). x86's asinine memslot deletion in kvm_arch_destroy_vm() needs to be addressed, but that code exists purely to do vm_munmap(), and can and should be moved to kvm_arch_free_memslot().

Quoted 4 lines

All that said, I'm not sure this aggressive fix is the right thing to send to stable@. For that, James' suggestion of hardening KVM's usage of __copy_{to,from}_user() seems like the best blend of being comprehensive without being overly invasive/risky.

This seems kind of nightmareish to backport; there are a lot of copy_*_user() callsites that will need updating. Maybe I have a different idea of the diff you're suggesting.

I wish we could just change the uaccess primitives, like {,__}access_ok(), to check that current->mm is not NULL (and WARN and return -EFAULT if it is NULL). That diff is also not trivial to backport; many arch implementations would need updating. I have half a mind to send an RFC patch to linux-mm@ to see what they think. :)

Quoted 5 lines

So, as an immediate set of changes, what if we do this over ~5 patches, with patches 1 and 2 tagged for stable@?

1. Add kvm_copy_{to,from}_user{,_inatomic)() and return -EFAULT if current->mm

     is not kvm->mm.

SGTM. This is not mutually exclusive with the generic uaccess changes I'm suggesting above. If this is actually reasonably backportable, sure let's backport it.

Quoted 6 lines

2. Hack-a-fix PPC's kvm_arch_flush_shadow_all().
3. Do x86's vm_munmap() in kvm_arch_free_memslot().
4. Nuke memslots before calling kvm_arch_destroy_vm().
5. Change the current->mm checks in kvm_copy_{to,from}_user{,_inatomic)() to WARN_ON_ONCE() on failure.

Quoted 6 lines

And then in the near-ish future, take things a step further and do:

6. Fix the vmx_leave_nested() trainwreck.
7. Harden the common kvm_{read,write}_guest family of APIs even further by adding an early WARN_ON_ONCE() on current->mm != kvm->mm, i.e. to detect bad KVM behavior as additional defense-in-depth.

This all SGTM, thanks Sean.

#7 lore raw
Quoted 6 lines · James Houghton
Quoted 5 lines · Sean Christopherson

If the above works for PPC, then KVM can nuke memslots before calling into kvm_arch_destroy_vm(). x86's asinine memslot deletion in kvm_arch_destroy_vm() needs to be addressed, but that code exists purely to do vm_munmap(), and can and should be moved to kvm_arch_free_memslot().

Quoted 8 lines
Quoted 4 lines

All that said, I'm not sure this aggressive fix is the right thing to send to stable@. For that, James' suggestion of hardening KVM's usage of __copy_{to,from}_user() seems like the best blend of being comprehensive without being overly invasive/risky.

This seems kind of nightmareish to backport; there are a lot of copy_*_user() callsites that will need updating. Maybe I have a different idea of the diff you're suggesting.

Nah, it's not many, because it's only the __copy_{to,from}_user{,inatomic}() usage that needs handling. Everything else is strictly scoped to an ioctl, where (a) current->mm can't be NULL and (b) KVM doesn't make any assumption about the address space.

At a glance, it's 11 total: 5 in virt/kvm, 4 in vmx.c, and 2 in PPC's book3s_64_mmu_radix.c. Well, plus 4 more to also harden {,__}kvm_{get,put}_guest().

And even if that number were doubled or tripled, the backports would still be relatively easy. The overwhelming majority won't conflict, and the few that do should be trivial to resolve (more than likely, simply drop the change).

Quoted 3 lines

I wish we could just change the uaccess primitives, like {,__}access_ok(), to check that current->mm is not NULL (and WARN and return -EFAULT if it is NULL).

That wouldn't help at all in this case, because the access_ok() check is done when memslots are modified. Which is the crux of KVM's problems: KVM decouples the initial checks from the accesses, relying on kvm->mm to

And even if we hardened all of the uaccess helpers, we'd _still_ have problems, because it's not just a NULL current->mm that's problematic. The last reference to a VM file, i.e. to struct kvm, can be put by a different _process_. I.e. KVM still needs to guard against reading/writing guest memory using a valid, non-NULL current->mm that isn't kvm->mm. That can't be genericized in the uaccess APIs, because the rule that only a specific address space can be used is very much unique to KVM.

Quoted 28 lines

That diff is also not trivial to backport; many arch implementations would need updating. I have half a mind to send an RFC patch to linux-mm@ to see what they think. :)

Quoted 5 lines

So, as an immediate set of changes, what if we do this over ~5 patches, with patches 1 and 2 tagged for stable@?

1. Add kvm_copy_{to,from}_user{,_inatomic)() and return -EFAULT if current->mm

     is not kvm->mm.

SGTM. This is not mutually exclusive with the generic uaccess changes I'm suggesting above. If this is actually reasonably backportable, sure let's backport it.

Quoted 6 lines

2. Hack-a-fix PPC's kvm_arch_flush_shadow_all().
3. Do x86's vm_munmap() in kvm_arch_free_memslot().
4. Nuke memslots before calling kvm_arch_destroy_vm().
5. Change the current->mm checks in kvm_copy_{to,from}_user{,_inatomic)() to WARN_ON_ONCE() on failure.

Quoted 6 lines

And then in the near-ish future, take things a step further and do:

6. Fix the vmx_leave_nested() trainwreck.
7. Harden the common kvm_{read,write}_guest family of APIs even further by adding an early WARN_ON_ONCE() on current->mm != kvm->mm, i.e. to detect bad KVM behavior as additional defense-in-depth.

This all SGTM, thanks Sean.

#8 lore raw
Quoted 10 lines · Sean Christopherson
Quoted 4 lines · James Houghton

On Wed, Sep 9, 2026 at 12:00 PM Sean Christopherson <[email protected]> wrote:
I wish we could just change the uaccess primitives, like {,__}access_ok(), to check that current->mm is not NULL (and WARN and return -EFAULT if it is NULL).

That wouldn't help at all in this case, because the access_ok() check is done when memslots are modified. Which is the crux of KVM's problems: KVM decouples the initial checks from the accesses, relying on kvm->mm to

Quoted 7 lines

And even if we hardened all of the uaccess helpers, we'd _still_ have problems, because it's not just a NULL current->mm that's problematic. The last reference to a VM file, i.e. to struct kvm, can be put by a different _process_. I.e. KVM still needs to guard against reading/writing guest memory using a valid, non-NULL current->mm that isn't kvm->mm. That can't be genericized in the uaccess APIs, because the rule that only a specific address space can be used is very much unique to KVM.

Oh, and I'm not saying we shouldn't try to harden the uaccess APIs to guard against a NULL current->mm. That absolutely would be worthwhile. I'm just saying that for KVM, it sadly isn't sufficient.

#9 lore raw
In reply to Sean Christopherson
Quoted 21 lines · Sean Christopherson
Quoted 6 lines · James Houghton
Quoted 5 lines · Sean Christopherson

If the above works for PPC, then KVM can nuke memslots before calling into kvm_arch_destroy_vm(). x86's asinine memslot deletion in kvm_arch_destroy_vm() needs to be addressed, but that code exists purely to do vm_munmap(), and can and should be moved to kvm_arch_free_memslot().

Quoted 8 lines
Quoted 4 lines

All that said, I'm not sure this aggressive fix is the right thing to send to stable@. For that, James' suggestion of hardening KVM's usage of __copy_{to,from}_user() seems like the best blend of being comprehensive without being overly invasive/risky.

This seems kind of nightmareish to backport; there are a lot of copy_*_user() callsites that will need updating. Maybe I have a different idea of the diff you're suggesting.

Nah, it's not many, because it's only the __copy_{to,from}_user{,inatomic}() usage that needs handling. Everything else is strictly scoped to an ioctl, where (a) current->mm can't be NULL and (b) KVM doesn't make any assumption about the address space.

Quoted 6 lines

At a glance, it's 11 total: 5 in virt/kvm, 4 in vmx.c, and 2 in PPC's book3s_64_mmu_radix.c. Well, plus 4 more to also harden {,__}kvm_{get,put}_guest().

And even if that number were doubled or tripled, the backports would still be relatively easy. The overwhelming majority won't conflict, and the few that do should be trivial to resolve (more than likely, simply drop the change).

To clarify: my goal isn't to harden literally every uaccess in KVM, just those that have a dependency on memslots, i.e. are accessing guest memory. Those also happen to be the ones that are often buried deep in KVM, in widely-used APIs.

#10 lore raw
In reply to Sean Christopherson
Quoted 3 lines · Sean Christopherson

So, as an immediate set of changes, what if we do this over ~5 patches, with patches 1 and 2 tagged for stable@?

By "we" here, you do mean the Royal "we," right?

I just want to confirm that you aren't expecting anything from me. :)

#11 lore raw
Quoted 6 lines · Jim Mattson
Quoted 3 lines · Sean Christopherson

So, as an immediate set of changes, what if we do this over ~5 patches, with patches 1 and 2 tagged for stable@?

By "we" here, you do mean the Royal "we," right?

Correct.

Quoted 1 line

I just want to confirm that you aren't expecting anything from me. :)

Do you happen to have a selftest for this? Even if it's half-baked. I'll take anything you have, at this point I just want a way to test the changes.

#12 lore raw

PATCH 1/1 KVM: selftests: Add test for shadow VMCS flush during vCPU teardown

As requested, a half-baked selftest. :)

I dropped stable from the cc list.

When a vCPU is destroyed while L2 is active and VMCS shadowing is enabled, KVM synthesizes a nested VM-Exit. This flushes the cached shadow VMCS12 back to guest memory. However, on process exit, do_exit() calls exit_mm() before closing file descriptors. KVM teardown runs with current->mm == NULL on a borrowed lazy TLB active_mm. Consequently, nested_flush_cached_shadow_vmcs12() writes the shadow VMCS12 into whatever address space is active on that CPU.

Add a selftest to verify this behavior. The test runs a victim process and a nested VMM process on the same physical CPU. The victim process maps a page and fills it with canary bytes. The VMM sets up an L2 guest with VMCS shadowing mapped at the identical host virtual address using MAP_FIXED_NOREPLACE. When the VMM exits with open file descriptors, the victim yields the CPU while the VMM terminates. This scheduling heuristic attempts to hit the race window where VMM teardown runs under the victim's active_mm and flushes the shadow VMCS into the victim's address space.

---
 tools/testing/selftests/kvm/Makefile.kvm      |   1 +
 .../kvm/x86/vmx_shadow_vmcs_teardown_test.c   | 317 ++++++++++++++++++
 2 files changed, 318 insertions(+)
 create mode 100644 tools/testing/selftests/kvm/x86/vmx_shadow_vmcs_teardown_test.c
tools/testing/selftests/kvm/Makefile.kvm +1 -0
index 5e2fcee198f2..2aa9cc75fbd7 100644
@@ -143,6 +143,7 @@ TEST_GEN_PROGS_x86 += x86/vmx_exception_with_invalid_guest_state
 TEST_GEN_PROGS_x86 += x86/vmx_msrs_test
 TEST_GEN_PROGS_x86 += x86/vmx_invalid_nested_guest_state
 TEST_GEN_PROGS_x86 += x86/vmx_nested_la57_state_test
+TEST_GEN_PROGS_x86 += x86/vmx_shadow_vmcs_teardown_test
 TEST_GEN_PROGS_x86 += x86/apic_bus_clock_test
 TEST_GEN_PROGS_x86 += x86/xapic_ipi_test
 TEST_GEN_PROGS_x86 += x86/xapic_state_test
tools/testing/selftests/kvm/x86/vmx_shadow_vmcs_teardown_test.c new file +317 -0

317 lines not on this page · raw message

Signature · 1 line
2.55.0.1032.g73a4cd73de-goog
#13 lore raw

Re: [PATCH] KVM: selftests: Add test for shadow VMCS flush during vCPU teardown

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:

New issues:
- [Medium] Virtual address collision causes mmap with MAP_FIXED_NOREPLACE to fail, preventing the test from running.
- [Low] The test invokes an undefined function vm_userspace_mem_region_add_caller_managed(), causing a compilation error.
- [Low] The function prepare_vmcs is called with three arguments, but it is declared to take only two.

Pre-existing issues:
- [Critical] Cross-process memory corruption during nested VMM teardown due to guest memory write from lazy TLB address space. --

commit 7a55753773b4f88412b975373e87f2ed41cc10a0
Author: Jim Mattson <[email protected]>

KVM: selftests: Add test for shadow VMCS flush during vCPU teardown

This commit adds a selftest to verify KVM's behavior when a vCPU is destroyed while L2 is active and VMCS shadowing is enabled. It attempts to trigger a race condition where the nested VMM terminates and flushes the shadow VMCS12 into a victim process's address space.

Quoted 7 lines

When a vCPU is destroyed while L2 is active and VMCS shadowing is enabled, KVM synthesizes a nested VM-Exit. This flushes the cached shadow VMCS12 back to guest memory. However, on process exit, do_exit() calls exit_mm() before closing file descriptors. KVM teardown runs with current->mm == NULL on a borrowed lazy TLB active_mm. Consequently, nested_flush_cached_shadow_vmcs12() writes the shadow VMCS12 into whatever address space is active on that CPU.

[Severity: Critical]
This is a pre-existing issue, but this text describes a cross-process memory corruption vulnerability during nested VMM teardown. When KVM destroys a vCPU via kvm_arch_vcpu_destroy() calling vmx_leave_nested(), it synthesizes a nested VM-exit. This flushes the shadow VMCS to guest memory via kvm_write_guest_cached().

Because VMM teardown runs during do_exit() after exit_mm() sets current->mm to NULL, kvm_write_guest_offset_cached() invokes __copy_to_user() using the host virtual address on the borrowed active_mm of whatever process previously ran on that CPU. If the HVA maps to valid memory in the victim process, __copy_to_user() will silently overwrite it with KVM's shadow VMCS data. Is there an upstream fix planned for this underlying KVM vulnerability?

Quoted 4 lines
tools/testing/selftests/kvm/x86/vmx_shadow_vmcs_teardown_test.c new file +0 -0
new file mode 100644

[ ... ]

tools/testing/selftests/kvm/x86/vmx_shadow_vmcs_teardown_test.c line 55

Quoted 10 lines
tools/testing/selftests/kvm/x86/vmx_shadow_vmcs_teardown_test.c new file +10 -0
+static void l1_guest_code(struct vmx_pages *vmx_pages)
+{
+	unsigned long l2_guest_stack[L2_GUEST_STACK_SIZE];
+
+	GUEST_ASSERT(prepare_for_vmx_operation(vmx_pages));
+	GUEST_ASSERT(load_vmcs(vmx_pages));
+
+	/* Prepare the VMCS for L2 execution. */
+	prepare_vmcs(vmx_pages, l2_guest_code,
+		     &l2_guest_stack[L2_GUEST_STACK_SIZE]);

[Severity: Low]
Does this function call cause a build failure? The prepare_vmcs() function is declared in the KVM selftests headers to take only two arguments (struct vmx_pages *vmx, void *guest_rip), but it is being called here with a third argument for the guest stack.

[ ... ]

Quoted 13 lines
tools/testing/selftests/kvm/x86/vmx_shadow_vmcs_teardown_test.c new file +13 -0
+static void run_vmm(int pcpu, void *target_hva, int c2_to_c1_fd)
+{
+	vm_vaddr_t vmx_pages_gva;
+	struct kvm_vcpu *vcpu;
+	struct kvm_vm *vm;
+	struct vmx_pages *vmx;
+	void *shadow_hva;
+
+	pin_self_to_cpu(pcpu);
+
+	vm = vm_create_with_one_vcpu(&vcpu, l1_guest_code);
+
+	/* Allocate VMX pages and shared descriptors. */

tools/testing/selftests/kvm/x86/vmx_shadow_vmcs_teardown_test.c line 100

Quoted 10 lines
tools/testing/selftests/kvm/x86/vmx_shadow_vmcs_teardown_test.c new file +10 -0
+	vcpu_alloc_vmx(vm, &vmx_pages_gva);
+	vmx = addr_gva2hva(vm, vmx_pages_gva);
+
+	/*
+	 * Map the shadow VMCS page at the exact target_hva allocated by the
+	 * victim so it collides with the victim process's mapping.
+	 */
+	shadow_hva = mmap(target_hva, PAGE_SIZE, PROT_READ | PROT_WRITE,
+			  MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
+	TEST_ASSERT(shadow_hva == target_hva, "mmap target_hva failed in VMM");

[Severity: Medium]
Will this mmap() call reliably fail with EEXIST and prevent the test from running? Because the VMM and victim processes are forked from the same parent and share identical ASLR bases, the victim's earlier mmap grabs the highest available virtual address as target_hva.

When run_vmm() calls vm_create_with_one_vcpu() earlier in this function, it makes its own large guest memory allocations using mmap(). Since mmap() allocates top-down, the VMM's allocation is likely to overlap or envelop target_hva before we reach this MAP_FIXED_NOREPLACE call.

tools/testing/selftests/kvm/x86/vmx_shadow_vmcs_teardown_test.c line 105

Quoted 5 lines
tools/testing/selftests/kvm/x86/vmx_shadow_vmcs_teardown_test.c new file +5 -0
+	memset(shadow_hva, 0, PAGE_SIZE);
+
+	/* Add a caller-managed memslot for the shadow VMCS backing page. */
+	vm_userspace_mem_region_add_caller_managed(vm, shadow_hva,
+						   SHADOW_VMCS_GPA, 10, 1, 0);

[Severity: Low]
Does this result in a compilation error? The function vm_userspace_mem_region_add_caller_managed() does not appear to be defined anywhere in the KVM selftests codebase.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#14 lore raw

Re: [PATCH] KVM: selftests: Add test for shadow VMCS flush during vCPU teardown

In reply to Jim Mattson
Quoted 22 lines · Jim Mattson

As requested, a half-baked selftest. :)

I dropped stable from the cc list.

When a vCPU is destroyed while L2 is active and VMCS shadowing is enabled, KVM synthesizes a nested VM-Exit. This flushes the cached shadow VMCS12 back to guest memory. However, on process exit, do_exit() calls exit_mm() before closing file descriptors. KVM teardown runs with current->mm == NULL on a borrowed lazy TLB active_mm. Consequently, nested_flush_cached_shadow_vmcs12() writes the shadow VMCS12 into whatever address space is active on that CPU.

Add a selftest to verify this behavior. The test runs a victim process and a nested VMM process on the same physical CPU. The victim process maps a page and fills it with canary bytes. The VMM sets up an L2 guest with VMCS shadowing mapped at the identical host virtual address using MAP_FIXED_NOREPLACE. When the VMM exits with open file descriptors, the victim yields the CPU while the VMM terminates. This scheduling heuristic attempts to hit the race window where VMM teardown runs under the victim's active_mm and flushes the shadow VMCS into the victim's address space.

Quoted 1 line

---

FWIW, diff to get this working on the current kvm-x86/next. I hacked it to use VA=0x1000 for the "bad" mapping as the address picked by the kernel for the victim was colliding with an existing allocation in the VMM (I didn't bother trying to figure out where the allocation came from, didn't seem interesting).

tools/testing/selftests/kvm/x86/vmx_shadow_vmcs_teardown_test.c +8 -12
index e0863ef20d3e..fbaba40ceefa 100644
@@ -45,18 +45,15 @@ static void l2_guest_code(void)
 
 static void l1_guest_code(struct vmx_pages *vmx_pages)
 {
-	unsigned long l2_guest_stack[L2_GUEST_STACK_SIZE];
-
-	GUEST_ASSERT(prepare_for_vmx_operation(vmx_pages));
-	GUEST_ASSERT(load_vmcs(vmx_pages));
+	prepare_for_vmx_operation(vmx_pages);
+	load_vmcs(vmx_pages);
 
 	/* Prepare the VMCS for L2 execution. */
-	prepare_vmcs(vmx_pages, l2_guest_code,
-		     &l2_guest_stack[L2_GUEST_STACK_SIZE]);
+	prepare_vmcs(vmx_pages, l2_guest_code);
 
 	/* Enable VMCS shadowing and set the shadow VMCS link pointer. */
 	vmwrite(SECONDARY_VM_EXEC_CONTROL,
-		vmreadz(SECONDARY_VM_EXEC_CONTROL) | SECONDARY_EXEC_SHADOW_VMCS);
+		vmread(SECONDARY_VM_EXEC_CONTROL) | SECONDARY_EXEC_SHADOW_VMCS);
 	vmwrite(VMCS_LINK_POINTER, vmx_pages->shadow_vmcs_gpa);
 
 	vmlaunch();
@@ -77,10 +74,10 @@ static bool kvm_cpu_has_shadow_vmcs(void)
 
 static void run_vmm(int pcpu, void *target_hva, int c2_to_c1_fd)
 {
-	vm_vaddr_t vmx_pages_gva;
 	struct kvm_vcpu *vcpu;
 	struct kvm_vm *vm;
 	struct vmx_pages *vmx;
+	gva_t vmx_pages_gva;
 	void *shadow_hva;
 
 	pin_self_to_cpu(pcpu);
@@ -97,12 +94,11 @@ static void run_vmm(int pcpu, void *target_hva, int c2_to_c1_fd)
 	 */
 	shadow_hva = mmap(target_hva, PAGE_SIZE, PROT_READ | PROT_WRITE,
 			  MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
-	TEST_ASSERT(shadow_hva == target_hva, "mmap target_hva failed in VMM");
+	TEST_ASSERT_EQ(shadow_hva, target_hva);
 	memset(shadow_hva, 0, PAGE_SIZE);
 
 	/* Add a caller-managed memslot for the shadow VMCS backing page. */
-	vm_userspace_mem_region_add_caller_managed(vm, shadow_hva,
-						   SHADOW_VMCS_GPA, 10, 1, 0);
+	vm_set_user_memory_region2(vm, 10, 0, SHADOW_VMCS_GPA, PAGE_SIZE, shadow_hva, -1, 0);
 	virt_pg_map(vm, SHADOW_VMCS_GVA, SHADOW_VMCS_GPA);
 
 	/* Override the shadow VMCS pointers in vmx_pages. */
@@ -156,7 +152,7 @@ static void run_victim(int pcpu, int ready_fd, int c2_to_c1_fd,
 
 	pin_self_to_cpu(pcpu);
 
-	victim_hva = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE,
+	victim_hva = mmap((void *)0x1000ul, PAGE_SIZE, PROT_READ | PROT_WRITE,
 			  MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
 	TEST_ASSERT(victim_hva != MAP_FAILED, "mmap failed in victim");
 	memset(victim_hva, CANARY_BYTE, PAGE_SIZE);