Re: [PATCH v2 4/4] KVM: x86: Fix stack-out-of-bounds memory access from ioapic_write_indirect()

From: Sean Christopherson
Date: Thu Aug 26 2021 - 14:01:25 EST


On Thu, Aug 26, 2021, Eduardo Habkost wrote:
> > @@ -918,7 +918,7 @@ static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
> > static inline bool kvm_apic_map_get_dest_lapic(struct kvm *kvm,
> > struct kvm_lapic **src, struct kvm_lapic_irq *irq,
> > struct kvm_apic_map *map, struct kvm_lapic ***dst,
> > - unsigned long *bitmap)
> > + unsigned long *bitmap64)
>
> You can communicate the expected bitmap size to the compiler
> without typedefs if using DECLARE_BITMAP inside the function
> parameter list is acceptable coding style (is it?).
>
> For example, the following would have allowed the compiler to
> catch the bug you are fixing:
>
> Signed-off-by: Eduardo Habkost <ehabkost@xxxxxxxxxx>
> ---
> diff --git a/arch/x86/kvm/lapic.h b/arch/x86/kvm/lapic.h
> index d7c25d0c1354..e8c64747121a 100644
> --- a/arch/x86/kvm/lapic.h
> +++ b/arch/x86/kvm/lapic.h
> @@ -236,7 +236,7 @@ bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector);
> void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu);
>
> void kvm_bitmap_or_dest_vcpus(struct kvm *kvm, struct kvm_lapic_irq *irq,
> - unsigned long *vcpu_bitmap);
> + DECLARE_BITMAP(vcpu_bitmap, KVM_MAX_VCPUS));
>
> bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
> struct kvm_vcpu **dest_vcpu);
> diff --git a/arch/x86/kvm/lapic.c b/arch/x86/kvm/lapic.c
> index 76fb00921203..1df113894cba 100644
> --- a/arch/x86/kvm/lapic.c
> +++ b/arch/x86/kvm/lapic.c
> @@ -1166,7 +1166,7 @@ static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
> * each available vcpu to identify the same.
> */
> void kvm_bitmap_or_dest_vcpus(struct kvm *kvm, struct kvm_lapic_irq *irq,
> - unsigned long *vcpu_bitmap)
> + DECLARE_BITMAP(vcpu_bitmap, KVM_MAX_VCPUS))
> {
> struct kvm_lapic **dest_vcpu = NULL;
> struct kvm_lapic *src = NULL;

Sadly, that would not have actually caught the bug. In C++, an array param does
indeed have a fixed size, but in C an array param is nothing more than syntatic
sugar that is demoted to a plain ol' pointer. E.g. gcc-10 and clang-11 both
happily compile with "DECLARE_BITMAP(vcpu_bitmap, 0)" and the original single
"unsigned long vcpu_bitmap". Maybe there are gcc extensions to enforce array
sizes? But if there are, they are not (yet) enabled for kernel builds.