malloc: Use overflow checking primitives where we do complex allocations

This attempts to fix the places where we do the following where
arithmetic_expr may include unvalidated data:

  X = grub_malloc(arithmetic_expr);

It accomplishes this by doing the arithmetic ahead of time using grub_add(),
grub_sub(), grub_mul() and testing for overflow before proceeding.

Among other issues, this fixes:
  - allocation of integer overflow in grub_video_bitmap_create()
    reported by Chris Coulson,
  - allocation of integer overflow in grub_png_decode_image_header()
    reported by Chris Coulson,
  - allocation of integer overflow in grub_squash_read_symlink()
    reported by Chris Coulson,
  - allocation of integer overflow in grub_ext2_read_symlink()
    reported by Chris Coulson,
  - allocation of integer overflow in read_section_as_string()
    reported by Chris Coulson.

Fixes: CVE-2020-14309, CVE-2020-14310, CVE-2020-14311

Signed-off-by: Peter Jones <pjones@redhat.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
This commit is contained in:
Peter Jones 2020-06-15 12:28:27 -04:00 committed by Daniel Kiper
parent f725fa7cb2
commit 3f05d693d1
23 changed files with 382 additions and 113 deletions

View file

@ -20,6 +20,7 @@
#include <grub/mm.h>
#include <grub/misc.h>
#include <grub/script_sh.h>
#include <grub/safemath.h>
/* Return nearest power of two that is >= v. */
static unsigned
@ -81,11 +82,16 @@ int
grub_script_argv_next (struct grub_script_argv *argv)
{
char **p = argv->args;
grub_size_t sz;
if (argv->args && argv->argc && argv->args[argv->argc - 1] == 0)
return 0;
p = grub_realloc (p, round_up_exp ((argv->argc + 2) * sizeof (char *)));
if (grub_add (argv->argc, 2, &sz) ||
grub_mul (sz, sizeof (char *), &sz))
return 1;
p = grub_realloc (p, round_up_exp (sz));
if (! p)
return 1;
@ -105,13 +111,19 @@ grub_script_argv_append (struct grub_script_argv *argv, const char *s,
{
grub_size_t a;
char *p = argv->args[argv->argc - 1];
grub_size_t sz;
if (! s)
return 0;
a = p ? grub_strlen (p) : 0;
p = grub_realloc (p, round_up_exp ((a + slen + 1) * sizeof (char)));
if (grub_add (a, slen, &sz) ||
grub_add (sz, 1, &sz) ||
grub_mul (sz, sizeof (char), &sz))
return 1;
p = grub_realloc (p, round_up_exp (sz));
if (! p)
return 1;