相当简单的c代码中的安全漏洞

Ces*_*sar 5 c security buffer-overflow

我正在读我的最后一次考试(是的!),并遇到了一个我很难搞清楚的问题.这是一个旧的考试问题,你应该找到至少两个可以在读取ppm图像文件的函数中利用的漏洞.我可以识别的唯一问题是,如果cols和/或行被赋予意外值,或者太大(导致整数溢出)或者是负数,这会导致img-> raster的大小不正确,从而开启了基于堆的可能性缓冲区溢出攻击.

据我所知,未经检查的malloc不应该被利用.

struct image *read_ppm(FILE *fp)
{
    int version;
    int rows, cols, maxval;
    int pixBytes=0, rowBytes=0, rasterBytes;
    uint8_t *p;
    struct image *img;
    /* Read the magic number from the file */
    if ((fscanf(fp, " P%d ", &version) < 1) || (version != 6)) {
        return NULL;
    }
    /* Read the image dimensions and color depth from the file */
    if (fscanf(fp, " %d %d %d ", &cols, &rows, &maxval) < 3) {
        return NULL;
    }
    /* Calculate some sizes */
    pixBytes = (maxval > 255) ? 6 : 3; // Bytes per pixel
    rowBytes = pixBytes * cols; // Bytes per row
    rasterBytes = rowBytes * rows; // Bytes for the whole image
    /* Allocate the image structure and initialize its fields */
    img = malloc(sizeof(*img));
    if (img == NULL) return NULL;
    img->rows = rows;
    img->cols = cols; 
    img->depth = (maxval > 255) ? 2 : 1;
    img->raster = (void*)malloc(rasterBytes);
    /* Get a pointer to the first pixel in the raster data. */
    /* It is to this pointer that all image data will be written. */
    p = img->raster;
    /* Iterate over the rows in the file */
    while (rows--) {
        /* Iterate over the columns in the file */
        cols = img->cols;
        while (cols--) {
            /* Try to read a single pixel from the file */
            if (fread(p, pixBytes, 1, fp) < 1) {
                /* If the read fails, free memory and return */
                free(img->raster);
                free(img);
                return NULL;
            }
            /* Advance the pointer to the next location to which we
            should read a single pixel. */
            p += pixBytes;
        }
    }
    /* Return the image */
    return img;
}
Run Code Online (Sandbox Code Playgroud)

原文(最后一个问题):http://www.ida.liu.se/~TDDC90/exam/old/TDDC90%20TEN1%202009-12-22.pdf

谢谢你的帮助.

UmN*_*obe 3

创建一个大文件,使得读取rowcols都是负数。rasterBytes = pixBytes * rows * cols积极的,所以一切都会好起来,直到p = img->raster;。但此时你有两个无限循环,并且程序可能会覆盖堆。

另一种攻击是设置rowcols使它们具有不同的符号。您可以选择其中一个值为-1,而另一个值足够大以读取您想要的数据。分配情况

  img->raster = (void*)malloc(rasterBytes);
Run Code Online (Sandbox Code Playgroud)

会失败,导致 img->raster 指向 NULL。意思是

 fread(p, pixBytes, 1, fp) < 1
Run Code Online (Sandbox Code Playgroud)

将尝试将文件的内容读取到内核内存。如果这段代码在内核模式下执行,根据系统(比如不使用内存段的旧unix),那么您将用文件的内容覆盖内核内存的内容。不使用内存段的内核不依赖于分段错误,而是依赖于页面错误(没有分配任何实际页面的虚拟地址)。问题在于虚拟内存设计使得第一个实际页面直接分配给内核页面。即内核虚拟地址 0x0 对应于 0x0 处的实际内存,并且完全有效(在内核内部)。

编辑:在这两种情况下,攻击者的目标是将输入文件的内容(完全在他的控制之下)注入他不应该访问的内存区域,同时无法修改函数read_ppm()