KVM: SVM: Flush pages under kvm->lock to fix UAF in svm_register_enc_region()

Do the cache flush of converted pages in svm_register_enc_region() before
dropping kvm->lock to fix use-after-free issues where region and/or its
array of pages could be freed by a different task, e.g. if userspace has
__unregister_enc_region_locked() already queued up for the region.

Note, the "obvious" alternative of using local variables doesn't fully
resolve the bug, as region->pages is also dynamically allocated. I.e. the
region structure itself would be fine, but region->pages could be freed.

Flushing multiple pages under kvm->lock is unfortunate, but the entire
flow is a rare slow path, and the manual flush is only needed on CPUs that
lack coherency for encrypted memory.

Fixes: 19a23da53932 ("Fix unsynchronized access to sev members through svm_register_enc_region")
Reported-by: Gabe Kirkpatrick <gkirkpatrick@google.com>
Cc: Josh Eads <josheads@google.com>
Cc: Peter Gonda <pgonda@google.com>
Cc: stable@vger.kernel.org
Signed-off-by: Sean Christopherson <seanjc@google.com>
Message-Id: <20240217013430.2079561-1-seanjc@google.com>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>

authored by Sean Christopherson and committed by Paolo Bonzini 5ef1d8c1 c48617fb

Changed files
+10 -8
arch
x86
kvm
svm
+10 -8
arch/x86/kvm/svm/sev.c
··· 1975 1975 goto e_free; 1976 1976 } 1977 1977 1978 + /* 1979 + * The guest may change the memory encryption attribute from C=0 -> C=1 1980 + * or vice versa for this memory range. Lets make sure caches are 1981 + * flushed to ensure that guest data gets written into memory with 1982 + * correct C-bit. Note, this must be done before dropping kvm->lock, 1983 + * as region and its array of pages can be freed by a different task 1984 + * once kvm->lock is released. 1985 + */ 1986 + sev_clflush_pages(region->pages, region->npages); 1987 + 1978 1988 region->uaddr = range->addr; 1979 1989 region->size = range->size; 1980 1990 1981 1991 list_add_tail(&region->list, &sev->regions_list); 1982 1992 mutex_unlock(&kvm->lock); 1983 - 1984 - /* 1985 - * The guest may change the memory encryption attribute from C=0 -> C=1 1986 - * or vice versa for this memory range. Lets make sure caches are 1987 - * flushed to ensure that guest data gets written into memory with 1988 - * correct C-bit. 1989 - */ 1990 - sev_clflush_pages(region->pages, region->npages); 1991 1993 1992 1994 return ret; 1993 1995