Re: [PATCH v2 04/13] KVM: x86: dynamic kvm_apic_map

From: Yang Zhang
Date: Mon Jul 11 2016 - 06:14:43 EST


On 2016/7/11 15:43, Paolo Bonzini wrote:


On 11/07/2016 08:07, Yang Zhang wrote:

mutex_lock(&kvm->arch.apic_map_lock);

+ kvm_for_each_vcpu(i, vcpu, kvm)
+ if (kvm_apic_present(vcpu))
+ max_id = max(max_id, kvm_apic_id(vcpu->arch.apic));
+
+ new = kzalloc(sizeof(struct kvm_apic_map) +
+ sizeof(struct kvm_lapic *) * (max_id + 1),
GFP_KERNEL);
+

I think this may cause the host runs out of memory if a malicious guest
did follow thing:
1. vcpu a is doing apic map recalculation.
2. vcpu b write the apic id with 0xff
3. then vcpu b enable the x2apic: in kvm_lapic_set_base(), we will set
apic_base to new value before reset the apic id.
4. vcpu a may see the x2apic enabled in vcpu b plus an old apic
id(0xff), and max_id will become (0xff >> 24).

The bug is not really here but in patch 6---but you're right nevertheless!

I guess the easiest solution is to replace kvm_apic_id with a field in
struct kvm_lapic, which is already shifted right by 24 in xAPIC mode.

Or we can just simply put the assignment of apic_base to the end.

diff --git a/arch/x86/kvm/lapic.c b/arch/x86/kvm/lapic.c
index fdc05ae..9c69059 100644
--- a/arch/x86/kvm/lapic.c
+++ b/arch/x86/kvm/lapic.c
@@ -1745,7 +1745,6 @@ void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
return;
}

- vcpu->arch.apic_base = value;

/* update jump label if enable bit changes */
if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
@@ -1753,7 +1752,6 @@ void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
static_key_slow_dec_deferred(&apic_hw_disabled);
else
static_key_slow_inc(&apic_hw_disabled.key);
- recalculate_apic_map(vcpu->kvm);
}

if ((old_value ^ value) & X2APIC_ENABLE) {
@@ -1764,6 +1762,8 @@ void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
kvm_x86_ops->set_virtual_x2apic_mode(vcpu, false);
}

+ vcpu->arch.apic_base = value;
+ recalculate_apic_map(vcpu->kvm);
apic->base_address = apic->vcpu->arch.apic_base &
MSR_IA32_APICBASE_BASE;


btw, i noticed that there is no apic map recalculation after turn off the x2apic mode.Is it correct?

--
best regards
yang