我正在为我的最后一次考试而学习(是的!),并且遇到了一个我很难弄清楚的问题。这是一个古老的考试问题,您应该在其中找到至少两个可以在读取 ppm 图像文件的函数中被利用的漏洞。我能确定的唯一问题是 cols 和/或 rows 是否被赋予了意外的值,要么太大(导致整数溢出)要么为负,这会导致 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;
}
原文(最后一题):http ://www.ida.liu.se/~TDDC90/exam/old/TDDC90%20TEN1%202009-12-22.pdf
谢谢你的帮助。