Skip to content

Commit 4b23e0c

Browse files
dmatlacksean-jc
authored andcommitted
KVM: Ensure new code that references immediate_exit gets extra scrutiny
Ensure that any new KVM code that references immediate_exit gets extra scrutiny by renaming it to immediate_exit__unsafe in kernel code. All fields in struct kvm_run are subject to TOCTOU races since they are mapped into userspace, which may be malicious or buggy. To protect KVM, introduces a new macro that appends __unsafe to select field names in struct kvm_run, hinting to developers and reviewers that accessing such fields must be done carefully. Apply the new macro to immediate_exit, since userspace can make immediate_exit inconsistent with vcpu->wants_to_run, i.e. accessing immediate_exit directly could lead to unexpected bugs in the future. Signed-off-by: David Matlack <[email protected]> Link: https://lore.kernel.org/r/[email protected] [sean: massage changelog] Signed-off-by: Sean Christopherson <[email protected]>
1 parent a681631 commit 4b23e0c

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

include/uapi/linux/kvm.h

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,11 +192,24 @@ struct kvm_xen_exit {
192192
/* Flags that describe what fields in emulation_failure hold valid data. */
193193
#define KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES (1ULL << 0)
194194

195+
/*
196+
* struct kvm_run can be modified by userspace at any time, so KVM must be
197+
* careful to avoid TOCTOU bugs. In order to protect KVM, HINT_UNSAFE_IN_KVM()
198+
* renames fields in struct kvm_run from <symbol> to <symbol>__unsafe when
199+
* compiled into the kernel, ensuring that any use within KVM is obvious and
200+
* gets extra scrutiny.
201+
*/
202+
#ifdef __KERNEL__
203+
#define HINT_UNSAFE_IN_KVM(_symbol) _symbol##__unsafe
204+
#else
205+
#define HINT_UNSAFE_IN_KVM(_symbol) _symbol
206+
#endif
207+
195208
/* for KVM_RUN, returned by mmap(vcpu_fd, offset=0) */
196209
struct kvm_run {
197210
/* in */
198211
__u8 request_interrupt_window;
199-
__u8 immediate_exit;
212+
__u8 HINT_UNSAFE_IN_KVM(immediate_exit);
200213
__u8 padding1[6];
201214

202215
/* out */

virt/kvm/kvm_main.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4435,7 +4435,7 @@ static long kvm_vcpu_ioctl(struct file *filp,
44354435
synchronize_rcu();
44364436
put_pid(oldpid);
44374437
}
4438-
vcpu->wants_to_run = !READ_ONCE(vcpu->run->immediate_exit);
4438+
vcpu->wants_to_run = !READ_ONCE(vcpu->run->immediate_exit__unsafe);
44394439
r = kvm_arch_vcpu_ioctl_run(vcpu);
44404440
vcpu->wants_to_run = false;
44414441

0 commit comments

Comments
 (0)