Re: [PATCH v2] efi_64: Fix a missing-check bug in arch/x86/platform/efi/efi_64.c

From: Gen Zhang
Date: Mon May 20 2019 - 23:00:40 EST


On Fri, May 17, 2019 at 11:24:27AM +0200, Ard Biesheuvel wrote:
> On Fri, 17 May 2019 at 11:06, Gen Zhang <blackgod016574@xxxxxxxxx> wrote:
> >
> > On Fri, May 17, 2019 at 10:41:28AM +0200, Ard Biesheuvel wrote:
> > > Returning an error here is not going to make much difference, given
> > > that the caller of efi_call_phys_prolog() does not bother to check it,
> > > and passes the result straight into efi_call_phys_epilog(), which
> > > happily attempts to dereference it.
> > >
> > > So if you want to fix this properly, please fix it at the call site as
> > > well. I'd prefer to avoid ERR_PTR() and just return NULL for a failed
> > > allocation though.
> > Hi Ard,
> > Thanks for your timely reply!
> > I think returning NULL in efi_call_phys_prolog() and checking in
> > efi_call_phys_epilog() is much better. But I am confused what to return
> > in efi_call_phys_epilog() if save_pgd is NULL. Definitely not return
> > -ENOMEM, because efi_call_phys_epilog() returns unsigned long. Could
> > please light on me to fix this problem?
>
>
> If efi_call_phys_prolog() returns NULL, the calling function should
> abort and never call efi_call_phys_epilog().
In efi_call_phys_prolog(), save_pgd is allocated by kmalloc_array().
And it is dereferenced in the following codes. However, memory
allocation functions such as kmalloc_array() may fail. Dereferencing
this save_pgd null pointer may cause the kernel go wrong. Thus we
should check this allocation.
Further, if efi_call_phys_prolog() returns NULL, we should abort the
process in phys_efi_set_virtual_address_map(), and return EFI_ABORTED.

Signed-off-by: Gen Zhang <blackgod016574@xxxxxxxxx>

---
diff --git a/arch/x86/platform/efi/efi.c b/arch/x86/platform/efi/efi.c
index e1cb01a..a7189a3 100644
--- a/arch/x86/platform/efi/efi.c
+++ b/arch/x86/platform/efi/efi.c
@@ -85,6 +85,8 @@ static efi_status_t __init phys_efi_set_virtual_address_map(
pgd_t *save_pgd;

save_pgd = efi_call_phys_prolog();
+ if (!save_pgd)
+ return EFI_ABORTED;

/* Disable interrupts around EFI calls: */
local_irq_save(flags);
diff --git a/arch/x86/platform/efi/efi_64.c b/arch/x86/platform/efi/efi_64.c
index cf0347f..828460a 100644
--- a/arch/x86/platform/efi/efi_64.c
+++ b/arch/x86/platform/efi/efi_64.c
@@ -91,6 +91,8 @@ pgd_t * __init efi_call_phys_prolog(void)

n_pgds = DIV_ROUND_UP((max_pfn << PAGE_SHIFT), PGDIR_SIZE);
save_pgd = kmalloc_array(n_pgds, sizeof(*save_pgd), GFP_KERNEL);
+ if (!save_pgd)
+ return NULL;

/*
* Build 1:1 identity mapping for efi=old_map usage. Note that
---