instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[AV_NUM_DATA_POINTERS]) { int i; int w_align = 1; int h_align = 1; AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt); if (desc) { w_align = 1 << desc->log2_chroma_w; h_align = 1 << desc->log2_chroma_h; } switch (s->pix_fmt) { case AV_PIX_FMT_YUV420P: case AV_PIX_FMT_YUYV422: case AV_PIX_FMT_YVYU422: case AV_PIX_FMT_UYVY422: case AV_PIX_FMT_YUV422P: case AV_PIX_FMT_YUV440P: case AV_PIX_FMT_YUV444P: case AV_PIX_FMT_GBRP: case AV_PIX_FMT_GBRAP: case AV_PIX_FMT_GRAY8: case AV_PIX_FMT_GRAY16BE: case AV_PIX_FMT_GRAY16LE: case AV_PIX_FMT_YUVJ420P: case AV_PIX_FMT_YUVJ422P: case AV_PIX_FMT_YUVJ440P: case AV_PIX_FMT_YUVJ444P: case AV_PIX_FMT_YUVA420P: case AV_PIX_FMT_YUVA422P: case AV_PIX_FMT_YUVA444P: case AV_PIX_FMT_YUV420P9LE: case AV_PIX_FMT_YUV420P9BE: case AV_PIX_FMT_YUV420P10LE: case AV_PIX_FMT_YUV420P10BE: case AV_PIX_FMT_YUV420P12LE: case AV_PIX_FMT_YUV420P12BE: case AV_PIX_FMT_YUV420P14LE: case AV_PIX_FMT_YUV420P14BE: case AV_PIX_FMT_YUV420P16LE: case AV_PIX_FMT_YUV420P16BE: case AV_PIX_FMT_YUVA420P9LE: case AV_PIX_FMT_YUVA420P9BE: case AV_PIX_FMT_YUVA420P10LE: case AV_PIX_FMT_YUVA420P10BE: case AV_PIX_FMT_YUVA420P16LE: case AV_PIX_FMT_YUVA420P16BE: case AV_PIX_FMT_YUV422P9LE: case AV_PIX_FMT_YUV422P9BE: case AV_PIX_FMT_YUV422P10LE: case AV_PIX_FMT_YUV422P10BE: case AV_PIX_FMT_YUV422P12LE: case AV_PIX_FMT_YUV422P12BE: case AV_PIX_FMT_YUV422P14LE: case AV_PIX_FMT_YUV422P14BE: case AV_PIX_FMT_YUV422P16LE: case AV_PIX_FMT_YUV422P16BE: case AV_PIX_FMT_YUVA422P9LE: case AV_PIX_FMT_YUVA422P9BE: case AV_PIX_FMT_YUVA422P10LE: case AV_PIX_FMT_YUVA422P10BE: case AV_PIX_FMT_YUVA422P16LE: case AV_PIX_FMT_YUVA422P16BE: case AV_PIX_FMT_YUV440P10LE: case AV_PIX_FMT_YUV440P10BE: case AV_PIX_FMT_YUV440P12LE: case AV_PIX_FMT_YUV440P12BE: case AV_PIX_FMT_YUV444P9LE: case AV_PIX_FMT_YUV444P9BE: case AV_PIX_FMT_YUV444P10LE: case AV_PIX_FMT_YUV444P10BE: case AV_PIX_FMT_YUV444P12LE: case AV_PIX_FMT_YUV444P12BE: case AV_PIX_FMT_YUV444P14LE: case AV_PIX_FMT_YUV444P14BE: case AV_PIX_FMT_YUV444P16LE: case AV_PIX_FMT_YUV444P16BE: case AV_PIX_FMT_YUVA444P9LE: case AV_PIX_FMT_YUVA444P9BE: case AV_PIX_FMT_YUVA444P10LE: case AV_PIX_FMT_YUVA444P10BE: case AV_PIX_FMT_YUVA444P16LE: case AV_PIX_FMT_YUVA444P16BE: case AV_PIX_FMT_GBRP9LE: case AV_PIX_FMT_GBRP9BE: case AV_PIX_FMT_GBRP10LE: case AV_PIX_FMT_GBRP10BE: case AV_PIX_FMT_GBRP12LE: case AV_PIX_FMT_GBRP12BE: case AV_PIX_FMT_GBRP14LE: case AV_PIX_FMT_GBRP14BE: case AV_PIX_FMT_GBRP16LE: case AV_PIX_FMT_GBRP16BE: case AV_PIX_FMT_GBRAP12LE: case AV_PIX_FMT_GBRAP12BE: case AV_PIX_FMT_GBRAP16LE: case AV_PIX_FMT_GBRAP16BE: w_align = 16; //FIXME assume 16 pixel per macroblock h_align = 16 * 2; // interlaced needs 2 macroblocks height break; case AV_PIX_FMT_YUV411P: case AV_PIX_FMT_YUVJ411P: case AV_PIX_FMT_UYYVYY411: w_align = 32; h_align = 16 * 2; break; case AV_PIX_FMT_YUV410P: if (s->codec_id == AV_CODEC_ID_SVQ1) { w_align = 64; h_align = 64; } break; case AV_PIX_FMT_RGB555: if (s->codec_id == AV_CODEC_ID_RPZA) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_PAL8: case AV_PIX_FMT_BGR8: case AV_PIX_FMT_RGB8: if (s->codec_id == AV_CODEC_ID_SMC || s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_JV) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_BGR24: if ((s->codec_id == AV_CODEC_ID_MSZH) || (s->codec_id == AV_CODEC_ID_ZLIB)) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_RGB24: if (s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } break; default: break; } if (s->codec_id == AV_CODEC_ID_IFF_ILBM) { w_align = FFMAX(w_align, 8); } *width = FFALIGN(*width, w_align); *height = FFALIGN(*height, h_align); if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) { *height += 2; *width = FFMAX(*width, 32); } for (i = 0; i < 4; i++) linesize_align[i] = STRIDE_ALIGN; } Commit Message: avcodec/utils: correct align value for interplay Fixes out of array access Fixes: 452/fuzz-1-ffmpeg_VIDEO_AV_CODEC_ID_INTERPLAY_VIDEO_fuzzer Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-787
void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[AV_NUM_DATA_POINTERS]) { int i; int w_align = 1; int h_align = 1; AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt); if (desc) { w_align = 1 << desc->log2_chroma_w; h_align = 1 << desc->log2_chroma_h; } switch (s->pix_fmt) { case AV_PIX_FMT_YUV420P: case AV_PIX_FMT_YUYV422: case AV_PIX_FMT_YVYU422: case AV_PIX_FMT_UYVY422: case AV_PIX_FMT_YUV422P: case AV_PIX_FMT_YUV440P: case AV_PIX_FMT_YUV444P: case AV_PIX_FMT_GBRP: case AV_PIX_FMT_GBRAP: case AV_PIX_FMT_GRAY8: case AV_PIX_FMT_GRAY16BE: case AV_PIX_FMT_GRAY16LE: case AV_PIX_FMT_YUVJ420P: case AV_PIX_FMT_YUVJ422P: case AV_PIX_FMT_YUVJ440P: case AV_PIX_FMT_YUVJ444P: case AV_PIX_FMT_YUVA420P: case AV_PIX_FMT_YUVA422P: case AV_PIX_FMT_YUVA444P: case AV_PIX_FMT_YUV420P9LE: case AV_PIX_FMT_YUV420P9BE: case AV_PIX_FMT_YUV420P10LE: case AV_PIX_FMT_YUV420P10BE: case AV_PIX_FMT_YUV420P12LE: case AV_PIX_FMT_YUV420P12BE: case AV_PIX_FMT_YUV420P14LE: case AV_PIX_FMT_YUV420P14BE: case AV_PIX_FMT_YUV420P16LE: case AV_PIX_FMT_YUV420P16BE: case AV_PIX_FMT_YUVA420P9LE: case AV_PIX_FMT_YUVA420P9BE: case AV_PIX_FMT_YUVA420P10LE: case AV_PIX_FMT_YUVA420P10BE: case AV_PIX_FMT_YUVA420P16LE: case AV_PIX_FMT_YUVA420P16BE: case AV_PIX_FMT_YUV422P9LE: case AV_PIX_FMT_YUV422P9BE: case AV_PIX_FMT_YUV422P10LE: case AV_PIX_FMT_YUV422P10BE: case AV_PIX_FMT_YUV422P12LE: case AV_PIX_FMT_YUV422P12BE: case AV_PIX_FMT_YUV422P14LE: case AV_PIX_FMT_YUV422P14BE: case AV_PIX_FMT_YUV422P16LE: case AV_PIX_FMT_YUV422P16BE: case AV_PIX_FMT_YUVA422P9LE: case AV_PIX_FMT_YUVA422P9BE: case AV_PIX_FMT_YUVA422P10LE: case AV_PIX_FMT_YUVA422P10BE: case AV_PIX_FMT_YUVA422P16LE: case AV_PIX_FMT_YUVA422P16BE: case AV_PIX_FMT_YUV440P10LE: case AV_PIX_FMT_YUV440P10BE: case AV_PIX_FMT_YUV440P12LE: case AV_PIX_FMT_YUV440P12BE: case AV_PIX_FMT_YUV444P9LE: case AV_PIX_FMT_YUV444P9BE: case AV_PIX_FMT_YUV444P10LE: case AV_PIX_FMT_YUV444P10BE: case AV_PIX_FMT_YUV444P12LE: case AV_PIX_FMT_YUV444P12BE: case AV_PIX_FMT_YUV444P14LE: case AV_PIX_FMT_YUV444P14BE: case AV_PIX_FMT_YUV444P16LE: case AV_PIX_FMT_YUV444P16BE: case AV_PIX_FMT_YUVA444P9LE: case AV_PIX_FMT_YUVA444P9BE: case AV_PIX_FMT_YUVA444P10LE: case AV_PIX_FMT_YUVA444P10BE: case AV_PIX_FMT_YUVA444P16LE: case AV_PIX_FMT_YUVA444P16BE: case AV_PIX_FMT_GBRP9LE: case AV_PIX_FMT_GBRP9BE: case AV_PIX_FMT_GBRP10LE: case AV_PIX_FMT_GBRP10BE: case AV_PIX_FMT_GBRP12LE: case AV_PIX_FMT_GBRP12BE: case AV_PIX_FMT_GBRP14LE: case AV_PIX_FMT_GBRP14BE: case AV_PIX_FMT_GBRP16LE: case AV_PIX_FMT_GBRP16BE: case AV_PIX_FMT_GBRAP12LE: case AV_PIX_FMT_GBRAP12BE: case AV_PIX_FMT_GBRAP16LE: case AV_PIX_FMT_GBRAP16BE: w_align = 16; //FIXME assume 16 pixel per macroblock h_align = 16 * 2; // interlaced needs 2 macroblocks height break; case AV_PIX_FMT_YUV411P: case AV_PIX_FMT_YUVJ411P: case AV_PIX_FMT_UYYVYY411: w_align = 32; h_align = 16 * 2; break; case AV_PIX_FMT_YUV410P: if (s->codec_id == AV_CODEC_ID_SVQ1) { w_align = 64; h_align = 64; } break; case AV_PIX_FMT_RGB555: if (s->codec_id == AV_CODEC_ID_RPZA) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_PAL8: case AV_PIX_FMT_BGR8: case AV_PIX_FMT_RGB8: if (s->codec_id == AV_CODEC_ID_SMC || s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_JV || s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_BGR24: if ((s->codec_id == AV_CODEC_ID_MSZH) || (s->codec_id == AV_CODEC_ID_ZLIB)) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_RGB24: if (s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } break; default: break; } if (s->codec_id == AV_CODEC_ID_IFF_ILBM) { w_align = FFMAX(w_align, 8); } *width = FFALIGN(*width, w_align); *height = FFALIGN(*height, h_align); if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) { *height += 2; *width = FFMAX(*width, 32); } for (i = 0; i < 4; i++) linesize_align[i] = STRIDE_ALIGN; }
168,246
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); one=1; image=AcquireImage(image_info); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported"); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; Rec2.RecordLength = 0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if (Rec.RecordLength > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->x_resolution=BitmapHeader1.HorzRes/470.0; image->y_resolution=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->x_resolution=BitmapHeader2.HorzRes/470.0; image->y_resolution=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp <= 16)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors)) { NoMemory: ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* printf("Load default colormap \n"); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelPacket *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,"UnableToDecompressImage"); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); ReplaceImageInList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp != 24)) { size_t one; one=1; image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelPacket *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk+1,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(BImgBuff,i,image,bpp); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); } } Finish: (void) CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers. */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, "ImageFileDoesNotContainAnyImageData"); return(image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/851 CWE ID: CWE-119
static Image *ReadWPGImage(const ImageInfo *image_info, ExceptionInfo *exception) { typedef struct { size_t FileId; MagickOffsetType DataOffset; unsigned int ProductType; unsigned int FileType; unsigned char MajorVersion; unsigned char MinorVersion; unsigned int EncryptKey; unsigned int Reserved; } WPGHeader; typedef struct { unsigned char RecType; size_t RecordLength; } WPGRecord; typedef struct { unsigned char Class; unsigned char RecType; size_t Extension; size_t RecordLength; } WPG2Record; typedef struct { unsigned HorizontalUnits; unsigned VerticalUnits; unsigned char PosSizePrecision; } WPG2Start; typedef struct { unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType1; typedef struct { unsigned int Width; unsigned int Height; unsigned char Depth; unsigned char Compression; } WPG2BitmapType1; typedef struct { unsigned int RotAngle; unsigned int LowLeftX; unsigned int LowLeftY; unsigned int UpRightX; unsigned int UpRightY; unsigned int Width; unsigned int Height; unsigned int Depth; unsigned int HorzRes; unsigned int VertRes; } WPGBitmapType2; typedef struct { unsigned int StartIndex; unsigned int NumOfEntries; } WPGColorMapRec; /* typedef struct { size_t PS_unknown1; unsigned int PS_unknown2; unsigned int PS_unknown3; } WPGPSl1Record; */ Image *image; unsigned int status; WPGHeader Header; WPGRecord Rec; WPG2Record Rec2; WPG2Start StartWPG; WPGBitmapType1 BitmapHeader1; WPG2BitmapType1 Bitmap2Header1; WPGBitmapType2 BitmapHeader2; WPGColorMapRec WPG_Palette; int i, bpp, WPG2Flags; ssize_t ldblk; size_t one; unsigned char *BImgBuff; tCTM CTM; /*current transform matrix*/ /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); one=1; image=AcquireImage(image_info); image->depth=8; status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read WPG image. */ Header.FileId=ReadBlobLSBLong(image); Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); Header.ProductType=ReadBlobLSBShort(image); Header.FileType=ReadBlobLSBShort(image); Header.MajorVersion=ReadBlobByte(image); Header.MinorVersion=ReadBlobByte(image); Header.EncryptKey=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (Header.EncryptKey!=0) ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported"); image->columns = 1; image->rows = 1; image->colors = 0; bpp=0; BitmapHeader2.RotAngle=0; Rec2.RecordLength = 0; switch(Header.FileType) { case 1: /* WPG level 1 */ while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec.RecordLength); if (Rec.RecordLength > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec.RecordLength; switch(Rec.RecType) { case 0x0B: /* bitmap type 1 */ BitmapHeader1.Width=ReadBlobLSBShort(image); BitmapHeader1.Height=ReadBlobLSBShort(image); if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader1.Depth=ReadBlobLSBShort(image); BitmapHeader1.HorzRes=ReadBlobLSBShort(image); BitmapHeader1.VertRes=ReadBlobLSBShort(image); if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) { image->units=PixelsPerCentimeterResolution; image->x_resolution=BitmapHeader1.HorzRes/470.0; image->y_resolution=BitmapHeader1.VertRes/470.0; } image->columns=BitmapHeader1.Width; image->rows=BitmapHeader1.Height; bpp=BitmapHeader1.Depth; goto UnpackRaster; case 0x0E: /*Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); if (WPG_Palette.StartIndex > WPG_Palette.NumOfEntries) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (!AcquireImageColormap(image,image->colors)) goto NoMemory; for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } break; case 0x11: /* Start PS l1 */ if(Rec.RecordLength > 8) image=ExtractPostscript(image,image_info, TellBlob(image)+8, /* skip PS header in the wpg */ (ssize_t) Rec.RecordLength-8,exception); break; case 0x14: /* bitmap type 2 */ BitmapHeader2.RotAngle=ReadBlobLSBShort(image); BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); BitmapHeader2.UpRightX=ReadBlobLSBShort(image); BitmapHeader2.UpRightY=ReadBlobLSBShort(image); BitmapHeader2.Width=ReadBlobLSBShort(image); BitmapHeader2.Height=ReadBlobLSBShort(image); if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); BitmapHeader2.Depth=ReadBlobLSBShort(image); BitmapHeader2.HorzRes=ReadBlobLSBShort(image); BitmapHeader2.VertRes=ReadBlobLSBShort(image); image->units=PixelsPerCentimeterResolution; image->page.width=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); image->page.height=(unsigned int) ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) { image->x_resolution=BitmapHeader2.HorzRes/470.0; image->y_resolution=BitmapHeader2.VertRes/470.0; } image->columns=BitmapHeader2.Width; image->rows=BitmapHeader2.Height; bpp=BitmapHeader2.Depth; UnpackRaster: status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp <= 16)) { image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors)) { NoMemory: ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } /* printf("Load default colormap \n"); */ for (i=0; (i < (int) image->colors) && (i < 256); i++) { image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); } } else { if (bpp < 24) if ( (image->colors < (one << bpp)) && (bpp != 24) ) image->colormap=(PixelPacket *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } if (bpp == 1) { if(image->colormap[0].red==0 && image->colormap[0].green==0 && image->colormap[0].blue==0 && image->colormap[1].red==0 && image->colormap[1].green==0 && image->colormap[1].blue==0) { /* fix crippled monochrome palette */ image->colormap[1].red = image->colormap[1].green = image->colormap[1].blue = QuantumRange; } } if(UnpackWPGRaster(image,bpp) < 0) /* The raster cannot be unpacked */ { DecompressionFailed: ThrowReaderException(CoderError,"UnableToDecompressImage"); } if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) { /* flop command */ if(BitmapHeader2.RotAngle & 0x8000) { Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } } /* flip command */ if(BitmapHeader2.RotAngle & 0x2000) { Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } } /* rotate command */ if(BitmapHeader2.RotAngle & 0x0FFF) { Image *rotate_image; rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & 0x0FFF), exception); if (rotate_image != (Image *) NULL) { DuplicateBlob(rotate_image,image); ReplaceImageInList(&image,rotate_image); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x1B: /* Postscript l2 */ if(Rec.RecordLength>0x3C) image=ExtractPostscript(image,image_info, TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ (ssize_t) Rec.RecordLength-0x3C,exception); break; } } break; case 2: /* WPG level 2 */ (void) memset(CTM,0,sizeof(CTM)); StartWPG.PosSizePrecision = 0; while(!EOFBlob(image)) /* object parser loop */ { (void) SeekBlob(image,Header.DataOffset,SEEK_SET); if(EOFBlob(image)) break; Rec2.Class=(i=ReadBlobByte(image)); if(i==EOF) break; Rec2.RecType=(i=ReadBlobByte(image)); if(i==EOF) break; Rd_WP_DWORD(image,&Rec2.Extension); Rd_WP_DWORD(image,&Rec2.RecordLength); if(EOFBlob(image)) break; Header.DataOffset=TellBlob(image)+Rec2.RecordLength; switch(Rec2.RecType) { case 1: StartWPG.HorizontalUnits=ReadBlobLSBShort(image); StartWPG.VerticalUnits=ReadBlobLSBShort(image); StartWPG.PosSizePrecision=ReadBlobByte(image); break; case 0x0C: /* Color palette */ WPG_Palette.StartIndex=ReadBlobLSBShort(image); WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > (Rec2.RecordLength-2-2) / 3) ThrowReaderException(CorruptImageError,"InvalidColormapIndex"); image->colors=WPG_Palette.NumOfEntries; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); for (i=WPG_Palette.StartIndex; i < (int)WPG_Palette.NumOfEntries; i++) { image->colormap[i].red=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].green=ScaleCharToQuantum((char) ReadBlobByte(image)); image->colormap[i].blue=ScaleCharToQuantum((char) ReadBlobByte(image)); (void) ReadBlobByte(image); /*Opacity??*/ } break; case 0x0E: Bitmap2Header1.Width=ReadBlobLSBShort(image); Bitmap2Header1.Height=ReadBlobLSBShort(image); if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); Bitmap2Header1.Depth=ReadBlobByte(image); Bitmap2Header1.Compression=ReadBlobByte(image); if(Bitmap2Header1.Compression > 1) continue; /*Unknown compression method */ switch(Bitmap2Header1.Depth) { case 1: bpp=1; break; case 2: bpp=2; break; case 3: bpp=4; break; case 4: bpp=8; break; case 8: bpp=24; break; default: continue; /*Ignore raster with unknown depth*/ } image->columns=Bitmap2Header1.Width; image->rows=Bitmap2Header1.Height; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) break; if ((image->colors == 0) && (bpp != 24)) { size_t one; one=1; image->colors=one << bpp; if (!AcquireImageColormap(image,image->colors)) goto NoMemory; } else { if(bpp < 24) if( image->colors<(one << bpp) && bpp!=24 ) image->colormap=(PixelPacket *) ResizeQuantumMemory( image->colormap,(size_t) (one << bpp), sizeof(*image->colormap)); } switch(Bitmap2Header1.Compression) { case 0: /*Uncompressed raster*/ { ldblk=(ssize_t) ((bpp*image->columns+7)/8); BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk+1,sizeof(*BImgBuff)); if (BImgBuff == (unsigned char *) NULL) goto NoMemory; for(i=0; i< (ssize_t) image->rows; i++) { (void) ReadBlob(image,ldblk,BImgBuff); InsertRow(BImgBuff,i,image,bpp); } if(BImgBuff) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); break; } case 1: /*RLE for WPG2 */ { if( UnpackWPG2Raster(image,bpp) < 0) goto DecompressionFailed; break; } } if(CTM[0][0]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flop_image; flop_image = FlopImage(image, exception); if (flop_image != (Image *) NULL) { DuplicateBlob(flop_image,image); ReplaceImageInList(&image,flop_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); Tx(1,2)=0; Tx(2,2)=1; */ } if(CTM[1][1]<0 && !image_info->ping) { /*?? RotAngle=360-RotAngle;*/ Image *flip_image; flip_image = FlipImage(image, exception); if (flip_image != (Image *) NULL) { DuplicateBlob(flip_image,image); ReplaceImageInList(&image,flip_image); } /* Try to change CTM according to Flip - I am not sure, must be checked. float_matrix Tx(3,3); Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); Tx(2,2)=1; */ } /* Allocate next image structure. */ AcquireNextImage(image_info,image); image->depth=8; if (image->next == (Image *) NULL) goto Finish; image=SyncNextImageInList(image); image->columns=image->rows=1; image->colors=0; break; case 0x12: /* Postscript WPG2*/ i=ReadBlobLSBShort(image); if(Rec2.RecordLength > (unsigned int) i) image=ExtractPostscript(image,image_info, TellBlob(image)+i, /*skip PS header in the wpg2*/ (ssize_t) (Rec2.RecordLength-i-2),exception); break; case 0x1B: /*bitmap rectangle*/ WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); (void) WPG2Flags; break; } } break; default: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); } } Finish: (void) CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers. */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=(size_t) scene++; } if (image == (Image *) NULL) ThrowReaderException(CorruptImageError, "ImageFileDoesNotContainAnyImageData"); return(image); }
170,011
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xlate_to_uni(const unsigned char *name, int len, unsigned char *outname, int *longlen, int *outlen, int escape, int utf8, struct nls_table *nls) { const unsigned char *ip; unsigned char nc; unsigned char *op; unsigned int ec; int i, k, fill; int charlen; if (utf8) { *outlen = utf8s_to_utf16s(name, len, (wchar_t *)outname); if (*outlen < 0) return *outlen; else if (*outlen > FAT_LFN_LEN) return -ENAMETOOLONG; op = &outname[*outlen * sizeof(wchar_t)]; } else { if (nls) { for (i = 0, ip = name, op = outname, *outlen = 0; i < len && *outlen <= FAT_LFN_LEN; *outlen += 1) { if (escape && (*ip == ':')) { if (i > len - 5) return -EINVAL; ec = 0; for (k = 1; k < 5; k++) { nc = ip[k]; ec <<= 4; if (nc >= '0' && nc <= '9') { ec |= nc - '0'; continue; } if (nc >= 'a' && nc <= 'f') { ec |= nc - ('a' - 10); continue; } if (nc >= 'A' && nc <= 'F') { ec |= nc - ('A' - 10); continue; } return -EINVAL; } *op++ = ec & 0xFF; *op++ = ec >> 8; ip += 5; i += 5; } else { if ((charlen = nls->char2uni(ip, len - i, (wchar_t *)op)) < 0) return -EINVAL; ip += charlen; i += charlen; op += 2; } } if (i < len) return -ENAMETOOLONG; } else { for (i = 0, ip = name, op = outname, *outlen = 0; i < len && *outlen <= FAT_LFN_LEN; i++, *outlen += 1) { *op++ = *ip++; *op++ = 0; } if (i < len) return -ENAMETOOLONG; } } *longlen = *outlen; if (*outlen % 13) { *op++ = 0; *op++ = 0; *outlen += 1; if (*outlen % 13) { fill = 13 - (*outlen % 13); for (i = 0; i < fill; i++) { *op++ = 0xff; *op++ = 0xff; } *outlen += fill; } } return 0; } Commit Message: NLS: improve UTF8 -> UTF16 string conversion routine The utf8s_to_utf16s conversion routine needs to be improved. Unlike its utf16s_to_utf8s sibling, it doesn't accept arguments specifying the maximum length of the output buffer or the endianness of its 16-bit output. This patch (as1501) adds the two missing arguments, and adjusts the only two places in the kernel where the function is called. A follow-on patch will add a third caller that does utilize the new capabilities. The two conversion routines are still annoyingly inconsistent in the way they handle invalid byte combinations. But that's a subject for a different patch. Signed-off-by: Alan Stern <[email protected]> CC: Clemens Ladisch <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119
xlate_to_uni(const unsigned char *name, int len, unsigned char *outname, int *longlen, int *outlen, int escape, int utf8, struct nls_table *nls) { const unsigned char *ip; unsigned char nc; unsigned char *op; unsigned int ec; int i, k, fill; int charlen; if (utf8) { *outlen = utf8s_to_utf16s(name, len, UTF16_HOST_ENDIAN, (wchar_t *) outname, FAT_LFN_LEN + 2); if (*outlen < 0) return *outlen; else if (*outlen > FAT_LFN_LEN) return -ENAMETOOLONG; op = &outname[*outlen * sizeof(wchar_t)]; } else { if (nls) { for (i = 0, ip = name, op = outname, *outlen = 0; i < len && *outlen <= FAT_LFN_LEN; *outlen += 1) { if (escape && (*ip == ':')) { if (i > len - 5) return -EINVAL; ec = 0; for (k = 1; k < 5; k++) { nc = ip[k]; ec <<= 4; if (nc >= '0' && nc <= '9') { ec |= nc - '0'; continue; } if (nc >= 'a' && nc <= 'f') { ec |= nc - ('a' - 10); continue; } if (nc >= 'A' && nc <= 'F') { ec |= nc - ('A' - 10); continue; } return -EINVAL; } *op++ = ec & 0xFF; *op++ = ec >> 8; ip += 5; i += 5; } else { if ((charlen = nls->char2uni(ip, len - i, (wchar_t *)op)) < 0) return -EINVAL; ip += charlen; i += charlen; op += 2; } } if (i < len) return -ENAMETOOLONG; } else { for (i = 0, ip = name, op = outname, *outlen = 0; i < len && *outlen <= FAT_LFN_LEN; i++, *outlen += 1) { *op++ = *ip++; *op++ = 0; } if (i < len) return -ENAMETOOLONG; } } *longlen = *outlen; if (*outlen % 13) { *op++ = 0; *op++ = 0; *outlen += 1; if (*outlen % 13) { fill = 13 - (*outlen % 13); for (i = 0; i < fill; i++) { *op++ = 0xff; *op++ = 0xff; } *outlen += fill; } } return 0; }
166,124
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ContentEncoding::ContentCompression::~ContentCompression() { delete [] settings; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
ContentEncoding::ContentCompression::~ContentCompression() { delete[] settings; }
174,459
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image) { const char *comment; int bits; MagickBooleanType status; PDBImage pdb_image; PDBInfo pdb_info; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t x; register unsigned char *q; size_t bits_per_pixel, literal, packets, packet_size, repeat; ssize_t y; unsigned char *buffer, *runlength, *scanline; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); if ((image -> colors <= 2 ) || (GetImageType(image,&image->exception ) == BilevelType)) { bits_per_pixel=1; } else if (image->colors <= 4) { bits_per_pixel=2; } else if (image->colors <= 8) { bits_per_pixel=3; } else { bits_per_pixel=4; } (void) ResetMagickMemory(&pdb_info,0,sizeof(pdb_info)); (void) CopyMagickString(pdb_info.name,image_info->filename, sizeof(pdb_info.name)); pdb_info.attributes=0; pdb_info.version=0; pdb_info.create_time=time(NULL); pdb_info.modify_time=pdb_info.create_time; pdb_info.archive_time=0; pdb_info.modify_number=0; pdb_info.application_info=0; pdb_info.sort_info=0; (void) CopyMagickMemory(pdb_info.type,"vIMG",4); (void) CopyMagickMemory(pdb_info.id,"View",4); pdb_info.seed=0; pdb_info.next_record=0; comment=GetImageProperty(image,"comment"); pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2); (void) WriteBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info); (void) WriteBlob(image,4,(unsigned char *) pdb_info.type); (void) WriteBlob(image,4,(unsigned char *) pdb_info.id); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records); (void) CopyMagickString(pdb_image.name,pdb_info.name,sizeof(pdb_image.name)); pdb_image.version=1; /* RLE Compressed */ switch (bits_per_pixel) { case 1: pdb_image.type=(unsigned char) 0xff; break; /* monochrome */ case 2: pdb_image.type=(unsigned char) 0x00; break; /* 2 bit gray */ default: pdb_image.type=(unsigned char) 0x02; /* 4 bit gray */ } pdb_image.reserved_1=0; pdb_image.note=0; pdb_image.x_last=0; pdb_image.y_last=0; pdb_image.reserved_2=0; pdb_image.x_anchor=(unsigned short) 0xffff; pdb_image.y_anchor=(unsigned short) 0xffff; pdb_image.width=(short) image->columns; if (image->columns % 16) pdb_image.width=(short) (16*(image->columns/16+1)); pdb_image.height=(short) image->rows; packets=((bits_per_pixel*image->columns+7)/8); runlength=(unsigned char *) AcquireQuantumMemory(9UL*packets, image->rows*sizeof(*runlength)); if (runlength == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); buffer=(unsigned char *) AcquireQuantumMemory(512,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); packet_size=(size_t) (image->depth > 8 ? 2: 1); scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size* sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); /* Convert to GRAY raster scanline. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); bits=8/(int) bits_per_pixel-1; /* start at most significant bits */ literal=0; repeat=0; q=runlength; buffer[0]=0x00; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, GrayQuantum,scanline,&image->exception); for (x=0; x < (ssize_t) pdb_image.width; x++) { if (x < (ssize_t) image->columns) buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >> (8-bits_per_pixel) << bits*bits_per_pixel; bits--; if (bits < 0) { if (((literal+repeat) > 0) && (buffer[literal+repeat] == buffer[literal+repeat-1])) { if (repeat == 0) { literal--; repeat++; } repeat++; if (0x7f < repeat) { q=EncodeRLE(q,buffer,literal,repeat); literal=0; repeat=0; } } else { if (repeat >= 2) literal+=repeat; else { q=EncodeRLE(q,buffer,literal,repeat); buffer[0]=buffer[literal+repeat]; literal=0; } literal++; repeat=0; if (0x7f < literal) { q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0); (void) CopyMagickMemory(buffer,buffer+literal+repeat,0x80); literal-=0x80; } } bits=8/(int) bits_per_pixel-1; buffer[literal+repeat]=0x00; } } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } q=EncodeRLE(q,buffer,literal,repeat); scanline=(unsigned char *) RelinquishMagickMemory(scanline); buffer=(unsigned char *) RelinquishMagickMemory(buffer); quantum_info=DestroyQuantumInfo(quantum_info); /* Write the Image record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8* pdb_info.number_records)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,0); if (pdb_info.number_records > 1) { /* Write the comment record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q- runlength)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,1); } /* Write the Image data. */ (void) WriteBlob(image,sizeof(pdb_image.name),(unsigned char *) pdb_image.name); (void) WriteBlobByte(image,(unsigned char) pdb_image.version); (void) WriteBlobByte(image,pdb_image.type); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2); (void) WriteBlobMSBShort(image,pdb_image.x_anchor); (void) WriteBlobMSBShort(image,pdb_image.y_anchor); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height); (void) WriteBlob(image,(size_t) (q-runlength),runlength); runlength=(unsigned char *) RelinquishMagickMemory(runlength); if (pdb_info.number_records > 1) (void) WriteBlobString(image,comment); (void) CloseBlob(image); return(MagickTrue); } Commit Message: Prevent buffer overflow in SIXEL, PDB, MAP, and CALS coders (bug report from Donghai Zhu) CWE ID: CWE-119
static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image) { const char *comment; int bits; MagickBooleanType status; PDBImage pdb_image; PDBInfo pdb_info; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t x; register unsigned char *q; size_t bits_per_pixel, literal, packets, packet_size, repeat; ssize_t y; unsigned char *buffer, *runlength, *scanline; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); if ((image -> colors <= 2 ) || (GetImageType(image,&image->exception ) == BilevelType)) { bits_per_pixel=1; } else if (image->colors <= 4) { bits_per_pixel=2; } else if (image->colors <= 8) { bits_per_pixel=3; } else { bits_per_pixel=4; } (void) ResetMagickMemory(&pdb_info,0,sizeof(pdb_info)); (void) CopyMagickString(pdb_info.name,image_info->filename, sizeof(pdb_info.name)); pdb_info.attributes=0; pdb_info.version=0; pdb_info.create_time=time(NULL); pdb_info.modify_time=pdb_info.create_time; pdb_info.archive_time=0; pdb_info.modify_number=0; pdb_info.application_info=0; pdb_info.sort_info=0; (void) CopyMagickMemory(pdb_info.type,"vIMG",4); (void) CopyMagickMemory(pdb_info.id,"View",4); pdb_info.seed=0; pdb_info.next_record=0; comment=GetImageProperty(image,"comment"); pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2); (void) WriteBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info); (void) WriteBlob(image,4,(unsigned char *) pdb_info.type); (void) WriteBlob(image,4,(unsigned char *) pdb_info.id); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records); (void) CopyMagickString(pdb_image.name,pdb_info.name,sizeof(pdb_image.name)); pdb_image.version=1; /* RLE Compressed */ switch (bits_per_pixel) { case 1: pdb_image.type=(unsigned char) 0xff; break; /* monochrome */ case 2: pdb_image.type=(unsigned char) 0x00; break; /* 2 bit gray */ default: pdb_image.type=(unsigned char) 0x02; /* 4 bit gray */ } pdb_image.reserved_1=0; pdb_image.note=0; pdb_image.x_last=0; pdb_image.y_last=0; pdb_image.reserved_2=0; pdb_image.x_anchor=(unsigned short) 0xffff; pdb_image.y_anchor=(unsigned short) 0xffff; pdb_image.width=(short) image->columns; if (image->columns % 16) pdb_image.width=(short) (16*(image->columns/16+1)); pdb_image.height=(short) image->rows; packets=((bits_per_pixel*image->columns+7)/8); runlength=(unsigned char *) AcquireQuantumMemory(9UL*packets, image->rows*sizeof(*runlength)); if (runlength == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); buffer=(unsigned char *) AcquireQuantumMemory(512,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); packet_size=(size_t) (image->depth > 8 ? 2 : 1); scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size* sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace); /* Convert to GRAY raster scanline. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,image->depth > 8 ? 16 : 8); bits=8/(int) bits_per_pixel-1; /* start at most significant bits */ literal=0; repeat=0; q=runlength; buffer[0]=0x00; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, GrayQuantum,scanline,&image->exception); for (x=0; x < (ssize_t) pdb_image.width; x++) { if (x < (ssize_t) image->columns) buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >> (8-bits_per_pixel) << bits*bits_per_pixel; bits--; if (bits < 0) { if (((literal+repeat) > 0) && (buffer[literal+repeat] == buffer[literal+repeat-1])) { if (repeat == 0) { literal--; repeat++; } repeat++; if (0x7f < repeat) { q=EncodeRLE(q,buffer,literal,repeat); literal=0; repeat=0; } } else { if (repeat >= 2) literal+=repeat; else { q=EncodeRLE(q,buffer,literal,repeat); buffer[0]=buffer[literal+repeat]; literal=0; } literal++; repeat=0; if (0x7f < literal) { q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0); (void) CopyMagickMemory(buffer,buffer+literal+repeat,0x80); literal-=0x80; } } bits=8/(int) bits_per_pixel-1; buffer[literal+repeat]=0x00; } } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } q=EncodeRLE(q,buffer,literal,repeat); scanline=(unsigned char *) RelinquishMagickMemory(scanline); buffer=(unsigned char *) RelinquishMagickMemory(buffer); quantum_info=DestroyQuantumInfo(quantum_info); /* Write the Image record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8* pdb_info.number_records)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,0); if (pdb_info.number_records > 1) { /* Write the comment record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q- runlength)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,1); } /* Write the Image data. */ (void) WriteBlob(image,sizeof(pdb_image.name),(unsigned char *) pdb_image.name); (void) WriteBlobByte(image,(unsigned char) pdb_image.version); (void) WriteBlobByte(image,pdb_image.type); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2); (void) WriteBlobMSBShort(image,pdb_image.x_anchor); (void) WriteBlobMSBShort(image,pdb_image.y_anchor); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height); (void) WriteBlob(image,(size_t) (q-runlength),runlength); runlength=(unsigned char *) RelinquishMagickMemory(runlength); if (pdb_info.number_records > 1) (void) WriteBlobString(image,comment); (void) CloseBlob(image); return(MagickTrue); }
168,633
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const char* Track::GetCodecId() const { return m_info.codecId; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const char* Track::GetCodecId() const
174,293
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ikev2_ID_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_id *idp; struct ikev2_id id; int id_len, idtype_len, i; unsigned int dumpascii, dumphex; const unsigned char *typedata; idp = (const struct ikev2_id *)ext; ND_TCHECK(*idp); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical); id_len = ntohs(id.h.len); ND_PRINT((ndo," len=%d", id_len - 4)); if (2 < ndo->ndo_vflag && 4 < id_len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4)) goto trunc; } idtype_len =id_len - sizeof(struct ikev2_id); dumpascii = 0; dumphex = 0; typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id); switch(id.type) { case ID_IPV4_ADDR: ND_PRINT((ndo, " ipv4:")); dumphex=1; break; case ID_FQDN: ND_PRINT((ndo, " fqdn:")); dumpascii=1; break; case ID_RFC822_ADDR: ND_PRINT((ndo, " rfc822:")); dumpascii=1; break; case ID_IPV6_ADDR: ND_PRINT((ndo, " ipv6:")); dumphex=1; break; case ID_DER_ASN1_DN: ND_PRINT((ndo, " dn:")); dumphex=1; break; case ID_DER_ASN1_GN: ND_PRINT((ndo, " gn:")); dumphex=1; break; case ID_KEY_ID: ND_PRINT((ndo, " keyid:")); dumphex=1; break; } if(dumpascii) { ND_TCHECK2(*typedata, idtype_len); for(i=0; i<idtype_len; i++) { if(ND_ISPRINT(typedata[i])) { ND_PRINT((ndo, "%c", typedata[i])); } else { ND_PRINT((ndo, ".")); } } } if(dumphex) { if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len)) goto trunc; } return (const u_char *)ext + id_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; }
167,796
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GLboolean WebGLRenderingContextBase::isTexture(WebGLTexture* texture) { if (!texture || isContextLost()) return 0; if (!texture->HasEverBeenBound()) return 0; if (texture->IsDeleted()) return 0; return ContextGL()->IsTexture(texture->Object()); } Commit Message: Validate all incoming WebGLObjects. A few entry points were missing the correct validation. Tested with improved conformance tests in https://github.com/KhronosGroup/WebGL/pull/2654 . Bug: 848914 Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008 Reviewed-on: https://chromium-review.googlesource.com/1086718 Reviewed-by: Kai Ninomiya <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Commit-Queue: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#565016} CWE ID: CWE-119
GLboolean WebGLRenderingContextBase::isTexture(WebGLTexture* texture) { if (!texture || isContextLost() || !texture->Validate(ContextGroup(), this)) return 0; if (!texture->HasEverBeenBound()) return 0; if (texture->IsDeleted()) return 0; return ContextGL()->IsTexture(texture->Object()); }
173,133
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int rds_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int msg_flags) { struct sock *sk = sock->sk; struct rds_sock *rs = rds_sk_to_rs(sk); long timeo; int ret = 0, nonblock = msg_flags & MSG_DONTWAIT; struct sockaddr_in *sin; struct rds_incoming *inc = NULL; /* udp_recvmsg()->sock_recvtimeo() gets away without locking too.. */ timeo = sock_rcvtimeo(sk, nonblock); rdsdebug("size %zu flags 0x%x timeo %ld\n", size, msg_flags, timeo); if (msg_flags & MSG_OOB) goto out; while (1) { /* If there are pending notifications, do those - and nothing else */ if (!list_empty(&rs->rs_notify_queue)) { ret = rds_notify_queue_get(rs, msg); break; } if (rs->rs_cong_notify) { ret = rds_notify_cong(rs, msg); break; } if (!rds_next_incoming(rs, &inc)) { if (nonblock) { ret = -EAGAIN; break; } timeo = wait_event_interruptible_timeout(*sk_sleep(sk), (!list_empty(&rs->rs_notify_queue) || rs->rs_cong_notify || rds_next_incoming(rs, &inc)), timeo); rdsdebug("recvmsg woke inc %p timeo %ld\n", inc, timeo); if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT) continue; ret = timeo; if (ret == 0) ret = -ETIMEDOUT; break; } rdsdebug("copying inc %p from %pI4:%u to user\n", inc, &inc->i_conn->c_faddr, ntohs(inc->i_hdr.h_sport)); ret = inc->i_conn->c_trans->inc_copy_to_user(inc, msg->msg_iov, size); if (ret < 0) break; /* * if the message we just copied isn't at the head of the * recv queue then someone else raced us to return it, try * to get the next message. */ if (!rds_still_queued(rs, inc, !(msg_flags & MSG_PEEK))) { rds_inc_put(inc); inc = NULL; rds_stats_inc(s_recv_deliver_raced); continue; } if (ret < be32_to_cpu(inc->i_hdr.h_len)) { if (msg_flags & MSG_TRUNC) ret = be32_to_cpu(inc->i_hdr.h_len); msg->msg_flags |= MSG_TRUNC; } if (rds_cmsg_recv(inc, msg)) { ret = -EFAULT; goto out; } rds_stats_inc(s_recv_delivered); sin = (struct sockaddr_in *)msg->msg_name; if (sin) { sin->sin_family = AF_INET; sin->sin_port = inc->i_hdr.h_sport; sin->sin_addr.s_addr = inc->i_saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); } break; } if (inc) rds_inc_put(inc); out: return ret; } Commit Message: rds: set correct msg_namelen Jay Fenlason ([email protected]) found a bug, that recvfrom() on an RDS socket can return the contents of random kernel memory to userspace if it was called with a address length larger than sizeof(struct sockaddr_in). rds_recvmsg() also fails to set the addr_len paramater properly before returning, but that's just a bug. There are also a number of cases wher recvfrom() can return an entirely bogus address. Anything in rds_recvmsg() that returns a non-negative value but does not go through the "sin = (struct sockaddr_in *)msg->msg_name;" code path at the end of the while(1) loop will return up to 128 bytes of kernel memory to userspace. And I write two test programs to reproduce this bug, you will see that in rds_server, fromAddr will be overwritten and the following sock_fd will be destroyed. Yes, it is the programmer's fault to set msg_namelen incorrectly, but it is better to make the kernel copy the real length of address to user space in such case. How to run the test programs ? I test them on 32bit x86 system, 3.5.0-rc7. 1 compile gcc -o rds_client rds_client.c gcc -o rds_server rds_server.c 2 run ./rds_server on one console 3 run ./rds_client on another console 4 you will see something like: server is waiting to receive data... old socket fd=3 server received data from client:data from client msg.msg_namelen=32 new socket fd=-1067277685 sendmsg() : Bad file descriptor /***************** rds_client.c ********************/ int main(void) { int sock_fd; struct sockaddr_in serverAddr; struct sockaddr_in toAddr; char recvBuffer[128] = "data from client"; struct msghdr msg; struct iovec iov; sock_fd = socket(AF_RDS, SOCK_SEQPACKET, 0); if (sock_fd < 0) { perror("create socket error\n"); exit(1); } memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); serverAddr.sin_port = htons(4001); if (bind(sock_fd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) { perror("bind() error\n"); close(sock_fd); exit(1); } memset(&toAddr, 0, sizeof(toAddr)); toAddr.sin_family = AF_INET; toAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); toAddr.sin_port = htons(4000); msg.msg_name = &toAddr; msg.msg_namelen = sizeof(toAddr); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_iov->iov_base = recvBuffer; msg.msg_iov->iov_len = strlen(recvBuffer) + 1; msg.msg_control = 0; msg.msg_controllen = 0; msg.msg_flags = 0; if (sendmsg(sock_fd, &msg, 0) == -1) { perror("sendto() error\n"); close(sock_fd); exit(1); } printf("client send data:%s\n", recvBuffer); memset(recvBuffer, '\0', 128); msg.msg_name = &toAddr; msg.msg_namelen = sizeof(toAddr); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_iov->iov_base = recvBuffer; msg.msg_iov->iov_len = 128; msg.msg_control = 0; msg.msg_controllen = 0; msg.msg_flags = 0; if (recvmsg(sock_fd, &msg, 0) == -1) { perror("recvmsg() error\n"); close(sock_fd); exit(1); } printf("receive data from server:%s\n", recvBuffer); close(sock_fd); return 0; } /***************** rds_server.c ********************/ int main(void) { struct sockaddr_in fromAddr; int sock_fd; struct sockaddr_in serverAddr; unsigned int addrLen; char recvBuffer[128]; struct msghdr msg; struct iovec iov; sock_fd = socket(AF_RDS, SOCK_SEQPACKET, 0); if(sock_fd < 0) { perror("create socket error\n"); exit(0); } memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); serverAddr.sin_port = htons(4000); if (bind(sock_fd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) { perror("bind error\n"); close(sock_fd); exit(1); } printf("server is waiting to receive data...\n"); msg.msg_name = &fromAddr; /* * I add 16 to sizeof(fromAddr), ie 32, * and pay attention to the definition of fromAddr, * recvmsg() will overwrite sock_fd, * since kernel will copy 32 bytes to userspace. * * If you just use sizeof(fromAddr), it works fine. * */ msg.msg_namelen = sizeof(fromAddr) + 16; /* msg.msg_namelen = sizeof(fromAddr); */ msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_iov->iov_base = recvBuffer; msg.msg_iov->iov_len = 128; msg.msg_control = 0; msg.msg_controllen = 0; msg.msg_flags = 0; while (1) { printf("old socket fd=%d\n", sock_fd); if (recvmsg(sock_fd, &msg, 0) == -1) { perror("recvmsg() error\n"); close(sock_fd); exit(1); } printf("server received data from client:%s\n", recvBuffer); printf("msg.msg_namelen=%d\n", msg.msg_namelen); printf("new socket fd=%d\n", sock_fd); strcat(recvBuffer, "--data from server"); if (sendmsg(sock_fd, &msg, 0) == -1) { perror("sendmsg()\n"); close(sock_fd); exit(1); } } close(sock_fd); return 0; } Signed-off-by: Weiping Pan <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
int rds_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int msg_flags) { struct sock *sk = sock->sk; struct rds_sock *rs = rds_sk_to_rs(sk); long timeo; int ret = 0, nonblock = msg_flags & MSG_DONTWAIT; struct sockaddr_in *sin; struct rds_incoming *inc = NULL; /* udp_recvmsg()->sock_recvtimeo() gets away without locking too.. */ timeo = sock_rcvtimeo(sk, nonblock); rdsdebug("size %zu flags 0x%x timeo %ld\n", size, msg_flags, timeo); msg->msg_namelen = 0; if (msg_flags & MSG_OOB) goto out; while (1) { /* If there are pending notifications, do those - and nothing else */ if (!list_empty(&rs->rs_notify_queue)) { ret = rds_notify_queue_get(rs, msg); break; } if (rs->rs_cong_notify) { ret = rds_notify_cong(rs, msg); break; } if (!rds_next_incoming(rs, &inc)) { if (nonblock) { ret = -EAGAIN; break; } timeo = wait_event_interruptible_timeout(*sk_sleep(sk), (!list_empty(&rs->rs_notify_queue) || rs->rs_cong_notify || rds_next_incoming(rs, &inc)), timeo); rdsdebug("recvmsg woke inc %p timeo %ld\n", inc, timeo); if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT) continue; ret = timeo; if (ret == 0) ret = -ETIMEDOUT; break; } rdsdebug("copying inc %p from %pI4:%u to user\n", inc, &inc->i_conn->c_faddr, ntohs(inc->i_hdr.h_sport)); ret = inc->i_conn->c_trans->inc_copy_to_user(inc, msg->msg_iov, size); if (ret < 0) break; /* * if the message we just copied isn't at the head of the * recv queue then someone else raced us to return it, try * to get the next message. */ if (!rds_still_queued(rs, inc, !(msg_flags & MSG_PEEK))) { rds_inc_put(inc); inc = NULL; rds_stats_inc(s_recv_deliver_raced); continue; } if (ret < be32_to_cpu(inc->i_hdr.h_len)) { if (msg_flags & MSG_TRUNC) ret = be32_to_cpu(inc->i_hdr.h_len); msg->msg_flags |= MSG_TRUNC; } if (rds_cmsg_recv(inc, msg)) { ret = -EFAULT; goto out; } rds_stats_inc(s_recv_delivered); sin = (struct sockaddr_in *)msg->msg_name; if (sin) { sin->sin_family = AF_INET; sin->sin_port = inc->i_hdr.h_sport; sin->sin_addr.s_addr = inc->i_saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); msg->msg_namelen = sizeof(*sin); } break; } if (inc) rds_inc_put(inc); out: return ret; }
165,583
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ps_files_valid_key(const char *key) { size_t len; const char *p; char c; int ret = 1; for (p = key; (c = *p); p++) { /* valid characters are a..z,A..Z,0..9 */ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == ',' || c == '-')) { ret = 0; break; } } len = p - key; /* Somewhat arbitrary length limit here, but should be way more than anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */ if (len == 0 || len > 128) { ret = 0; } return ret; } Commit Message: CWE ID: CWE-264
static int ps_files_valid_key(const char *key)
164,871
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *zap = NULL; int ret; /* check the quota and attach the new data */ ret = key_payload_reserve(key, prep->datalen); if (ret < 0) return ret; /* attach the new data, displacing the old */ key->expiry = prep->expiry; if (!test_bit(KEY_FLAG_NEGATIVE, &key->flags)) zap = dereference_key_locked(key); rcu_assign_keypointer(key, prep->payload.data[0]); prep->payload.data[0] = NULL; if (zap) call_rcu(&zap->rcu, user_free_payload_rcu); return ret; } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
int user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *zap = NULL; int ret; /* check the quota and attach the new data */ ret = key_payload_reserve(key, prep->datalen); if (ret < 0) return ret; /* attach the new data, displacing the old */ key->expiry = prep->expiry; if (key_is_positive(key)) zap = dereference_key_locked(key); rcu_assign_keypointer(key, prep->payload.data[0]); prep->payload.data[0] = NULL; if (zap) call_rcu(&zap->rcu, user_free_payload_rcu); return ret; }
167,710
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind) : host_id_(host_id), gpu_process_(base::kNullProcessHandle), in_process_(false), software_rendering_(false), kind_(kind), process_launched_(false) { if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) || CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU)) in_process_ = true; DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL); g_gpu_process_hosts[kind] = this; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id)); process_.reset( new BrowserChildProcessHostImpl(content::PROCESS_TYPE_GPU, this)); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind) : host_id_(host_id), in_process_(false), software_rendering_(false), kind_(kind), process_launched_(false) { if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) || CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU)) in_process_ = true; DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL); g_gpu_process_hosts[kind] = this; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id)); process_.reset( new BrowserChildProcessHostImpl(content::PROCESS_TYPE_GPU, this)); }
170,921
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileInfo, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } }
167,032
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: write_png(const char **name, FILE *fp, int color_type, int bit_depth, volatile png_fixed_point gamma, chunk_insert * volatile insert, unsigned int filters, unsigned int *colors) { png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, name, makepng_error, makepng_warning); volatile png_infop info_ptr = NULL; volatile png_bytep row = NULL; if (png_ptr == NULL) { fprintf(stderr, "makepng: OOM allocating write structure\n"); return 1; } if (setjmp(png_jmpbuf(png_ptr))) { png_structp nv_ptr = png_ptr; png_infop nv_info = info_ptr; png_ptr = NULL; info_ptr = NULL; png_destroy_write_struct(&nv_ptr, &nv_info); if (row != NULL) free(row); return 1; } /* Allow benign errors so that we can write PNGs with errors */ png_set_benign_errors(png_ptr, 1/*allowed*/); png_init_io(png_ptr, fp); info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) png_error(png_ptr, "OOM allocating info structure"); { unsigned int size = image_size_of_type(color_type, bit_depth, colors); png_fixed_point real_gamma = 45455; /* For sRGB */ png_byte gamma_table[256]; double conv; /* This function uses the libpng values used on read to carry extra * information about the gamma: */ if (gamma == PNG_GAMMA_MAC_18) gamma = 65909; else if (gamma > 0 && gamma < 1000) gamma = PNG_FP_1; if (gamma > 0) real_gamma = gamma; { unsigned int i; if (real_gamma == 45455) for (i=0; i<256; ++i) { gamma_table[i] = (png_byte)i; conv = 1.; } else { /* Convert 'i' from sRGB (45455) to real_gamma, this makes * the images look the same regardless of the gAMA chunk. */ conv = real_gamma; conv /= 45455; gamma_table[0] = 0; for (i=1; i<255; ++i) gamma_table[i] = (png_byte)floor(pow(i/255.,conv) * 255 + .5); gamma_table[255] = 255; } } png_set_IHDR(png_ptr, info_ptr, size, size, bit_depth, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); if (color_type & PNG_COLOR_MASK_PALETTE) { int npalette; png_color palette[256]; png_byte trans[256]; npalette = generate_palette(palette, trans, bit_depth, gamma_table, colors); png_set_PLTE(png_ptr, info_ptr, palette, npalette); png_set_tRNS(png_ptr, info_ptr, trans, npalette-1, NULL/*transparent color*/); /* Reset gamma_table to prevent the image rows being changed */ for (npalette=0; npalette<256; ++npalette) gamma_table[npalette] = (png_byte)npalette; } if (gamma == PNG_DEFAULT_sRGB) png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_ABSOLUTE); else if (gamma > 0) /* Else don't set color space information */ { png_set_gAMA_fixed(png_ptr, info_ptr, real_gamma); /* Just use the sRGB values here. */ png_set_cHRM_fixed(png_ptr, info_ptr, /* color x y */ /* white */ 31270, 32900, /* red */ 64000, 33000, /* green */ 30000, 60000, /* blue */ 15000, 6000 ); } /* Insert extra information. */ while (insert != NULL) { insert->insert(png_ptr, info_ptr, insert->nparams, insert->parameters); insert = insert->next; } /* Write the file header. */ png_write_info(png_ptr, info_ptr); /* Restrict the filters */ png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, filters); { int passes = png_set_interlace_handling(png_ptr); int pass; png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr); row = malloc(rowbytes); if (row == NULL) png_error(png_ptr, "OOM allocating row buffer"); for (pass = 0; pass < passes; ++pass) { unsigned int y; for (y=0; y<size; ++y) { generate_row(row, rowbytes, y, color_type, bit_depth, gamma_table, conv, colors); png_write_row(png_ptr, row); } } } } /* Finish writing the file. */ png_write_end(png_ptr, info_ptr); { png_structp nv_ptr = png_ptr; png_infop nv_info = info_ptr; png_ptr = NULL; info_ptr = NULL; png_destroy_write_struct(&nv_ptr, &nv_info); } free(row); return 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
write_png(const char **name, FILE *fp, int color_type, int bit_depth, volatile png_fixed_point gamma, chunk_insert * volatile insert, unsigned int filters, unsigned int *colors, int small, int tRNS) { png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, name, makepng_error, makepng_warning); volatile png_infop info_ptr = NULL; volatile png_bytep row = NULL; if (png_ptr == NULL) { fprintf(stderr, "makepng: OOM allocating write structure\n"); return 1; } if (setjmp(png_jmpbuf(png_ptr))) { png_structp nv_ptr = png_ptr; png_infop nv_info = info_ptr; png_ptr = NULL; info_ptr = NULL; png_destroy_write_struct(&nv_ptr, &nv_info); if (row != NULL) free(row); return 1; } /* Allow benign errors so that we can write PNGs with errors */ png_set_benign_errors(png_ptr, 1/*allowed*/); /* Max out the text compression level in an attempt to make the license * small. If --small then do the same for the IDAT. */ if (small) png_set_compression_level(png_ptr, Z_BEST_COMPRESSION); png_set_text_compression_level(png_ptr, Z_BEST_COMPRESSION); png_init_io(png_ptr, fp); info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) png_error(png_ptr, "OOM allocating info structure"); { const unsigned int size = image_size_of_type(color_type, bit_depth, colors, small); unsigned int ysize; png_fixed_point real_gamma = 45455; /* For sRGB */ png_byte gamma_table[256]; double conv; /* Normally images are square, but with 'small' we want to simply generate * all the pixel values, or all that we reasonably can: */ if (small) { const unsigned int pixel_depth = pixel_depth_of_type(color_type, bit_depth); if (pixel_depth <= 8U) { assert(size == (1U<<pixel_depth)); ysize = 1U; } else { assert(size == 256U); ysize = 256U; } } else ysize = size; /* This function uses the libpng values used on read to carry extra * information about the gamma: */ if (gamma == PNG_GAMMA_MAC_18) gamma = 65909; else if (gamma > 0 && gamma < 1000) gamma = PNG_FP_1; if (gamma > 0) real_gamma = gamma; { unsigned int i; if (real_gamma == 45455) for (i=0; i<256; ++i) { gamma_table[i] = (png_byte)i; conv = 1.; } else { /* Convert 'i' from sRGB (45455) to real_gamma, this makes * the images look the same regardless of the gAMA chunk. */ conv = real_gamma; conv /= 45455; gamma_table[0] = 0; for (i=1; i<255; ++i) gamma_table[i] = floorb(pow(i/255.,conv) * 255 + .5); gamma_table[255] = 255; } } png_set_IHDR(png_ptr, info_ptr, size, ysize, bit_depth, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); if (color_type & PNG_COLOR_MASK_PALETTE) { int npalette; png_color palette[256]; png_byte trans[256]; npalette = generate_palette(palette, trans, bit_depth, gamma_table, colors); png_set_PLTE(png_ptr, info_ptr, palette, npalette); if (tRNS) png_set_tRNS(png_ptr, info_ptr, trans, npalette-1, NULL/*transparent color*/); /* Reset gamma_table to prevent the image rows being changed */ for (npalette=0; npalette<256; ++npalette) gamma_table[npalette] = (png_byte)npalette; } else if (tRNS) { png_color_16 col; col.red = col.green = col.blue = col.gray = 0x0101U & ((1U<<bit_depth)-1U); col.index = 0U; png_set_tRNS(png_ptr, info_ptr, NULL/*trans*/, 1U, &col); } if (gamma == PNG_DEFAULT_sRGB) png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_ABSOLUTE); else if (gamma > 0) /* Else don't set color space information */ { png_set_gAMA_fixed(png_ptr, info_ptr, real_gamma); /* Just use the sRGB values here. */ png_set_cHRM_fixed(png_ptr, info_ptr, /* color x y */ /* white */ 31270, 32900, /* red */ 64000, 33000, /* green */ 30000, 60000, /* blue */ 15000, 6000 ); } /* Insert extra information. */ while (insert != NULL) { insert->insert(png_ptr, info_ptr, insert->nparams, insert->parameters); insert = insert->next; } /* Write the file header. */ png_write_info(png_ptr, info_ptr); /* Restrict the filters */ png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, filters); { # ifdef PNG_WRITE_INTERLACING_SUPPORTED int passes = png_set_interlace_handling(png_ptr); # else /* !WRITE_INTERLACING */ int passes = 1; # endif /* !WRITE_INTERLACING */ int pass; png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr); row = malloc(rowbytes); if (row == NULL) png_error(png_ptr, "OOM allocating row buffer"); for (pass = 0; pass < passes; ++pass) { unsigned int y; for (y=0; y<ysize; ++y) { unsigned int row_filters = generate_row(row, rowbytes, y, color_type, bit_depth, gamma_table, conv, colors, small); if (row_filters != 0 && filters == PNG_ALL_FILTERS) png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, row_filters); png_write_row(png_ptr, row); } } } } /* Finish writing the file. */ png_write_end(png_ptr, info_ptr); { png_structp nv_ptr = png_ptr; png_infop nv_info = info_ptr; png_ptr = NULL; info_ptr = NULL; png_destroy_write_struct(&nv_ptr, &nv_info); } free(row); return 0; }
173,586
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int irda_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; struct irda_sock *self; if (net != &init_net) return -EAFNOSUPPORT; /* Check for valid socket type */ switch (sock->type) { case SOCK_STREAM: /* For TTP connections with SAR disabled */ case SOCK_SEQPACKET: /* For TTP connections with SAR enabled */ case SOCK_DGRAM: /* For TTP Unitdata or LMP Ultra transfers */ break; default: return -ESOCKTNOSUPPORT; } /* Allocate networking socket */ sk = sk_alloc(net, PF_IRDA, GFP_KERNEL, &irda_proto, kern); if (sk == NULL) return -ENOMEM; self = irda_sk(sk); pr_debug("%s() : self is %p\n", __func__, self); init_waitqueue_head(&self->query_wait); switch (sock->type) { case SOCK_STREAM: sock->ops = &irda_stream_ops; self->max_sdu_size_rx = TTP_SAR_DISABLE; break; case SOCK_SEQPACKET: sock->ops = &irda_seqpacket_ops; self->max_sdu_size_rx = TTP_SAR_UNBOUND; break; case SOCK_DGRAM: switch (protocol) { #ifdef CONFIG_IRDA_ULTRA case IRDAPROTO_ULTRA: sock->ops = &irda_ultra_ops; /* Initialise now, because we may send on unbound * sockets. Jean II */ self->max_data_size = ULTRA_MAX_DATA - LMP_PID_HEADER; self->max_header_size = IRDA_MAX_HEADER + LMP_PID_HEADER; break; #endif /* CONFIG_IRDA_ULTRA */ case IRDAPROTO_UNITDATA: sock->ops = &irda_dgram_ops; /* We let Unitdata conn. be like seqpack conn. */ self->max_sdu_size_rx = TTP_SAR_UNBOUND; break; default: sk_free(sk); return -ESOCKTNOSUPPORT; } break; default: sk_free(sk); return -ESOCKTNOSUPPORT; } /* Initialise networking socket struct */ sock_init_data(sock, sk); /* Note : set sk->sk_refcnt to 1 */ sk->sk_family = PF_IRDA; sk->sk_protocol = protocol; /* Register as a client with IrLMP */ self->ckey = irlmp_register_client(0, NULL, NULL, NULL); self->mask.word = 0xffff; self->rx_flow = self->tx_flow = FLOW_START; self->nslots = DISCOVERY_DEFAULT_SLOTS; self->daddr = DEV_ADDR_ANY; /* Until we get connected */ self->saddr = 0x0; /* so IrLMP assign us any link */ return 0; } Commit Message: net: add validation for the socket syscall protocol argument 郭永刚 reported that one could simply crash the kernel as root by using a simple program: int socket_fd; struct sockaddr_in addr; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = 10; socket_fd = socket(10,3,0x40000000); connect(socket_fd , &addr,16); AF_INET, AF_INET6 sockets actually only support 8-bit protocol identifiers. inet_sock's skc_protocol field thus is sized accordingly, thus larger protocol identifiers simply cut off the higher bits and store a zero in the protocol fields. This could lead to e.g. NULL function pointer because as a result of the cut off inet_num is zero and we call down to inet_autobind, which is NULL for raw sockets. kernel: Call Trace: kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70 kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80 kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110 kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80 kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200 kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10 kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89 I found no particular commit which introduced this problem. CVE: CVE-2015-8543 Cc: Cong Wang <[email protected]> Reported-by: 郭永刚 <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static int irda_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; struct irda_sock *self; if (protocol < 0 || protocol > SK_PROTOCOL_MAX) return -EINVAL; if (net != &init_net) return -EAFNOSUPPORT; /* Check for valid socket type */ switch (sock->type) { case SOCK_STREAM: /* For TTP connections with SAR disabled */ case SOCK_SEQPACKET: /* For TTP connections with SAR enabled */ case SOCK_DGRAM: /* For TTP Unitdata or LMP Ultra transfers */ break; default: return -ESOCKTNOSUPPORT; } /* Allocate networking socket */ sk = sk_alloc(net, PF_IRDA, GFP_KERNEL, &irda_proto, kern); if (sk == NULL) return -ENOMEM; self = irda_sk(sk); pr_debug("%s() : self is %p\n", __func__, self); init_waitqueue_head(&self->query_wait); switch (sock->type) { case SOCK_STREAM: sock->ops = &irda_stream_ops; self->max_sdu_size_rx = TTP_SAR_DISABLE; break; case SOCK_SEQPACKET: sock->ops = &irda_seqpacket_ops; self->max_sdu_size_rx = TTP_SAR_UNBOUND; break; case SOCK_DGRAM: switch (protocol) { #ifdef CONFIG_IRDA_ULTRA case IRDAPROTO_ULTRA: sock->ops = &irda_ultra_ops; /* Initialise now, because we may send on unbound * sockets. Jean II */ self->max_data_size = ULTRA_MAX_DATA - LMP_PID_HEADER; self->max_header_size = IRDA_MAX_HEADER + LMP_PID_HEADER; break; #endif /* CONFIG_IRDA_ULTRA */ case IRDAPROTO_UNITDATA: sock->ops = &irda_dgram_ops; /* We let Unitdata conn. be like seqpack conn. */ self->max_sdu_size_rx = TTP_SAR_UNBOUND; break; default: sk_free(sk); return -ESOCKTNOSUPPORT; } break; default: sk_free(sk); return -ESOCKTNOSUPPORT; } /* Initialise networking socket struct */ sock_init_data(sock, sk); /* Note : set sk->sk_refcnt to 1 */ sk->sk_family = PF_IRDA; sk->sk_protocol = protocol; /* Register as a client with IrLMP */ self->ckey = irlmp_register_client(0, NULL, NULL, NULL); self->mask.word = 0xffff; self->rx_flow = self->tx_flow = FLOW_START; self->nslots = DISCOVERY_DEFAULT_SLOTS; self->daddr = DEV_ADDR_ANY; /* Until we get connected */ self->saddr = 0x0; /* so IrLMP assign us any link */ return 0; }
166,566
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_instruction( struct translate_ctx *ctx, boolean has_label ) { uint i; uint saturate = 0; const struct tgsi_opcode_info *info; struct tgsi_full_instruction inst; const char *cur; uint advance; inst = tgsi_default_full_instruction(); /* Parse predicate. */ eat_opt_white( &ctx->cur ); if (*ctx->cur == '(') { uint file; int index; uint swizzle[4]; boolean parsed_swizzle; inst.Instruction.Predicate = 1; ctx->cur++; if (*ctx->cur == '!') { ctx->cur++; inst.Predicate.Negate = 1; } if (!parse_register_1d( ctx, &file, &index )) return FALSE; if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { inst.Predicate.SwizzleX = swizzle[0]; inst.Predicate.SwizzleY = swizzle[1]; inst.Predicate.SwizzleZ = swizzle[2]; inst.Predicate.SwizzleW = swizzle[3]; } } if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } /* Parse instruction name. */ eat_opt_white( &ctx->cur ); for (i = 0; i < TGSI_OPCODE_LAST; i++) { cur = ctx->cur; info = tgsi_get_opcode_info( i ); if (match_inst(&cur, &saturate, info)) { if (info->num_dst + info->num_src + info->is_tex == 0) { ctx->cur = cur; break; } else if (*cur == '\0' || eat_white( &cur )) { ctx->cur = cur; break; } } } if (i == TGSI_OPCODE_LAST) { if (has_label) report_error( ctx, "Unknown opcode" ); else report_error( ctx, "Expected `DCL', `IMM' or a label" ); return FALSE; } inst.Instruction.Opcode = i; inst.Instruction.Saturate = saturate; inst.Instruction.NumDstRegs = info->num_dst; inst.Instruction.NumSrcRegs = info->num_src; if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) { /* * These are not considered tex opcodes here (no additional * target argument) however we're required to set the Texture * bit so we can set the number of tex offsets. */ inst.Instruction.Texture = 1; inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN; } /* Parse instruction operands. */ for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) { if (i > 0) { eat_opt_white( &ctx->cur ); if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } if (i < info->num_dst) { if (!parse_dst_operand( ctx, &inst.Dst[i] )) return FALSE; } else if (i < info->num_dst + info->num_src) { if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] )) return FALSE; } else { uint j; for (j = 0; j < TGSI_TEXTURE_COUNT; j++) { if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) { inst.Instruction.Texture = 1; inst.Texture.Texture = j; break; } } if (j == TGSI_TEXTURE_COUNT) { report_error( ctx, "Expected texture target" ); return FALSE; } } } cur = ctx->cur; eat_opt_white( &cur ); for (i = 0; inst.Instruction.Texture && *cur == ','; i++) { cur++; eat_opt_white( &cur ); ctx->cur = cur; if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] )) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); } inst.Texture.NumOffsets = i; cur = ctx->cur; eat_opt_white( &cur ); if (info->is_branch && *cur == ':') { uint target; cur++; eat_opt_white( &cur ); if (!parse_uint( &cur, &target )) { report_error( ctx, "Expected a label" ); return FALSE; } inst.Instruction.Label = 1; inst.Label.Label = target; ctx->cur = cur; } advance = tgsi_build_full_instruction( &inst, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; } Commit Message: CWE ID: CWE-119
parse_instruction( struct translate_ctx *ctx, boolean has_label ) { uint i; uint saturate = 0; const struct tgsi_opcode_info *info; struct tgsi_full_instruction inst; const char *cur; uint advance; inst = tgsi_default_full_instruction(); /* Parse predicate. */ eat_opt_white( &ctx->cur ); if (*ctx->cur == '(') { uint file; int index; uint swizzle[4]; boolean parsed_swizzle; inst.Instruction.Predicate = 1; ctx->cur++; if (*ctx->cur == '!') { ctx->cur++; inst.Predicate.Negate = 1; } if (!parse_register_1d( ctx, &file, &index )) return FALSE; if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { inst.Predicate.SwizzleX = swizzle[0]; inst.Predicate.SwizzleY = swizzle[1]; inst.Predicate.SwizzleZ = swizzle[2]; inst.Predicate.SwizzleW = swizzle[3]; } } if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } /* Parse instruction name. */ eat_opt_white( &ctx->cur ); for (i = 0; i < TGSI_OPCODE_LAST; i++) { cur = ctx->cur; info = tgsi_get_opcode_info( i ); if (match_inst(&cur, &saturate, info)) { if (info->num_dst + info->num_src + info->is_tex == 0) { ctx->cur = cur; break; } else if (*cur == '\0' || eat_white( &cur )) { ctx->cur = cur; break; } } } if (i == TGSI_OPCODE_LAST) { if (has_label) report_error( ctx, "Unknown opcode" ); else report_error( ctx, "Expected `DCL', `IMM' or a label" ); return FALSE; } inst.Instruction.Opcode = i; inst.Instruction.Saturate = saturate; inst.Instruction.NumDstRegs = info->num_dst; inst.Instruction.NumSrcRegs = info->num_src; if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) { /* * These are not considered tex opcodes here (no additional * target argument) however we're required to set the Texture * bit so we can set the number of tex offsets. */ inst.Instruction.Texture = 1; inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN; } /* Parse instruction operands. */ for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) { if (i > 0) { eat_opt_white( &ctx->cur ); if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } if (i < info->num_dst) { if (!parse_dst_operand( ctx, &inst.Dst[i] )) return FALSE; } else if (i < info->num_dst + info->num_src) { if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] )) return FALSE; } else { uint j; for (j = 0; j < TGSI_TEXTURE_COUNT; j++) { if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) { inst.Instruction.Texture = 1; inst.Texture.Texture = j; break; } } if (j == TGSI_TEXTURE_COUNT) { report_error( ctx, "Expected texture target" ); return FALSE; } } } cur = ctx->cur; eat_opt_white( &cur ); for (i = 0; inst.Instruction.Texture && *cur == ',' && i < TGSI_FULL_MAX_TEX_OFFSETS; i++) { cur++; eat_opt_white( &cur ); ctx->cur = cur; if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] )) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); } inst.Texture.NumOffsets = i; cur = ctx->cur; eat_opt_white( &cur ); if (info->is_branch && *cur == ':') { uint target; cur++; eat_opt_white( &cur ); if (!parse_uint( &cur, &target )) { report_error( ctx, "Expected a label" ); return FALSE; } inst.Instruction.Label = 1; inst.Label.Label = target; ctx->cur = cur; } advance = tgsi_build_full_instruction( &inst, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; }
164,987
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool TabStripModel::InternalCloseTabs(const std::vector<int>& indices, uint32 close_types) { if (indices.empty()) return true; bool retval = true; std::vector<TabContentsWrapper*> tabs; for (size_t i = 0; i < indices.size(); ++i) tabs.push_back(GetContentsAt(indices[i])); if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) { std::map<RenderProcessHost*, size_t> processes; for (size_t i = 0; i < indices.size(); ++i) { if (!delegate_->CanCloseContentsAt(indices[i])) { retval = false; continue; } TabContentsWrapper* detached_contents = GetContentsAt(indices[i]); RenderProcessHost* process = detached_contents->tab_contents()->GetRenderProcessHost(); std::map<RenderProcessHost*, size_t>::iterator iter = processes.find(process); if (iter == processes.end()) { processes[process] = 1; } else { iter->second++; } } for (std::map<RenderProcessHost*, size_t>::iterator iter = processes.begin(); iter != processes.end(); ++iter) { iter->first->FastShutdownForPageCount(iter->second); } } for (size_t i = 0; i < tabs.size(); ++i) { TabContentsWrapper* detached_contents = tabs[i]; int index = GetIndexOfTabContents(detached_contents); if (index == kNoTab) continue; detached_contents->tab_contents()->OnCloseStarted(); if (!delegate_->CanCloseContentsAt(index)) { retval = false; continue; } if (!detached_contents->tab_contents()->closed_by_user_gesture()) { detached_contents->tab_contents()->set_closed_by_user_gesture( close_types & CLOSE_USER_GESTURE); } if (delegate_->RunUnloadListenerBeforeClosing(detached_contents)) { retval = false; continue; } InternalCloseTab(detached_contents, index, (close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0); } return retval; } Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab. BUG=chromium-os:12088 TEST=verify bug per bug report. Review URL: http://codereview.chromium.org/6882058 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool TabStripModel::InternalCloseTabs(const std::vector<int>& indices, bool TabStripModel::InternalCloseTabs(const std::vector<int>& in_indices, uint32 close_types) { if (in_indices.empty()) return true; std::vector<int> indices(in_indices); bool retval = delegate_->CanCloseContents(&indices); if (indices.empty()) return retval; std::vector<TabContentsWrapper*> tabs; for (size_t i = 0; i < indices.size(); ++i) tabs.push_back(GetContentsAt(indices[i])); if (browser_shutdown::GetShutdownType() == browser_shutdown::NOT_VALID) { std::map<RenderProcessHost*, size_t> processes; for (size_t i = 0; i < indices.size(); ++i) { TabContentsWrapper* detached_contents = GetContentsAt(indices[i]); RenderProcessHost* process = detached_contents->tab_contents()->GetRenderProcessHost(); std::map<RenderProcessHost*, size_t>::iterator iter = processes.find(process); if (iter == processes.end()) { processes[process] = 1; } else { iter->second++; } } for (std::map<RenderProcessHost*, size_t>::iterator iter = processes.begin(); iter != processes.end(); ++iter) { iter->first->FastShutdownForPageCount(iter->second); } } for (size_t i = 0; i < tabs.size(); ++i) { TabContentsWrapper* detached_contents = tabs[i]; int index = GetIndexOfTabContents(detached_contents); if (index == kNoTab) continue; detached_contents->tab_contents()->OnCloseStarted(); if (!detached_contents->tab_contents()->closed_by_user_gesture()) { detached_contents->tab_contents()->set_closed_by_user_gesture( close_types & CLOSE_USER_GESTURE); } if (delegate_->RunUnloadListenerBeforeClosing(detached_contents)) { retval = false; continue; } InternalCloseTab(detached_contents, index, (close_types & CLOSE_CREATE_HISTORICAL_TAB) != 0); } return retval; }
170,302
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int is_rndis(USBNetState *s) { return s->dev.config->bConfigurationValue == DEV_RNDIS_CONFIG_VALUE; } Commit Message: CWE ID:
static int is_rndis(USBNetState *s) { return s->dev.config ? s->dev.config->bConfigurationValue == DEV_RNDIS_CONFIG_VALUE : 0; }
165,187
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass) { png_const_structp pp = ppIn; PNG_CONST standard_display *dp = voidcast(standard_display*, png_get_progressive_ptr(pp)); /* When handling interlacing some rows will be absent in each pass, the * callback still gets called, but with a NULL pointer. This is checked * in the 'else' clause below. We need our own 'cbRow', but we can't call * png_get_rowbytes because we got no info structure. */ if (new_row != NULL) { png_bytep row; /* In the case where the reader doesn't do the interlace it gives * us the y in the sub-image: */ if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7) { #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED /* Use this opportunity to validate the png 'current' APIs: */ if (y != png_get_current_row_number(pp)) png_error(pp, "png_get_current_row_number is broken"); if (pass != png_get_current_pass_number(pp)) png_error(pp, "png_get_current_pass_number is broken"); #endif y = PNG_ROW_FROM_PASS_ROW(y, pass); } /* Validate this just in case. */ if (y >= dp->h) png_error(pp, "invalid y to progressive row callback"); row = store_image_row(dp->ps, pp, 0, y); #ifdef PNG_READ_INTERLACING_SUPPORTED /* Combine the new row into the old: */ if (dp->do_interlace) { if (dp->interlace_type == PNG_INTERLACE_ADAM7) deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass); else row_copy(row, new_row, dp->pixel_size * dp->w); } else png_progressive_combine_row(pp, row, new_row); #endif /* PNG_READ_INTERLACING_SUPPORTED */ } #ifdef PNG_READ_INTERLACING_SUPPORTED else if (dp->interlace_type == PNG_INTERLACE_ADAM7 && PNG_ROW_IN_INTERLACE_PASS(y, pass) && PNG_PASS_COLS(dp->w, pass) > 0) png_error(pp, "missing row in progressive de-interlacing"); #endif /* PNG_READ_INTERLACING_SUPPORTED */ } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass) { png_const_structp pp = ppIn; const standard_display *dp = voidcast(standard_display*, png_get_progressive_ptr(pp)); /* When handling interlacing some rows will be absent in each pass, the * callback still gets called, but with a NULL pointer. This is checked * in the 'else' clause below. We need our own 'cbRow', but we can't call * png_get_rowbytes because we got no info structure. */ if (new_row != NULL) { png_bytep row; /* In the case where the reader doesn't do the interlace it gives * us the y in the sub-image: */ if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7) { #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED /* Use this opportunity to validate the png 'current' APIs: */ if (y != png_get_current_row_number(pp)) png_error(pp, "png_get_current_row_number is broken"); if (pass != png_get_current_pass_number(pp)) png_error(pp, "png_get_current_pass_number is broken"); #endif /* USER_TRANSFORM_INFO */ y = PNG_ROW_FROM_PASS_ROW(y, pass); } /* Validate this just in case. */ if (y >= dp->h) png_error(pp, "invalid y to progressive row callback"); row = store_image_row(dp->ps, pp, 0, y); /* Combine the new row into the old: */ #ifdef PNG_READ_INTERLACING_SUPPORTED if (dp->do_interlace) #endif /* READ_INTERLACING */ { if (dp->interlace_type == PNG_INTERLACE_ADAM7) deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass, dp->littleendian); else row_copy(row, new_row, dp->pixel_size * dp->w, dp->littleendian); } #ifdef PNG_READ_INTERLACING_SUPPORTED else png_progressive_combine_row(pp, row, new_row); #endif /* PNG_READ_INTERLACING_SUPPORTED */ } else if (dp->interlace_type == PNG_INTERLACE_ADAM7 && PNG_ROW_IN_INTERLACE_PASS(y, pass) && PNG_PASS_COLS(dp->w, pass) > 0) png_error(pp, "missing row in progressive de-interlacing"); }
173,686
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void _xml_startElementHandler(void *userData, const XML_Char *name, const XML_Char **attributes) { xml_parser *parser = (xml_parser *)userData; const char **attrs = (const char **) attributes; char *tag_name; char *att, *val; int val_len; zval *retval, *args[3]; if (parser) { parser->level++; tag_name = _xml_decode_tag(parser, name); if (parser->startElementHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset); MAKE_STD_ZVAL(args[2]); array_init(args[2]); while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(args[2], att, val, val_len, 0); attributes += 2; efree(att); } if ((retval = xml_call_handler(parser, parser->startElementHandler, parser->startElementPtr, 3, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { if (parser->level <= XML_MAXLEVEL) { zval *tag, *atr; int atcnt = 0; MAKE_STD_ZVAL(tag); MAKE_STD_ZVAL(atr); array_init(tag); array_init(atr); _xml_add_to_info(parser,((char *) tag_name) + parser->toffset); add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */ add_assoc_string(tag,"type","open",1); add_assoc_long(tag,"level",parser->level); parser->ltags[parser->level-1] = estrdup(tag_name); parser->lastwasopen = 1; attributes = (const XML_Char **) attrs; while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(atr,att,val,val_len,0); atcnt++; attributes += 2; efree(att); } if (atcnt) { zend_hash_add(Z_ARRVAL_P(tag),"attributes",sizeof("attributes"),&atr,sizeof(zval*),NULL); } else { zval_ptr_dtor(&atr); } zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),(void *) &parser->ctag); } else if (parser->level == (XML_MAXLEVEL + 1)) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated"); } } efree(tag_name); } } Commit Message: CWE ID: CWE-119
void _xml_startElementHandler(void *userData, const XML_Char *name, const XML_Char **attributes) { xml_parser *parser = (xml_parser *)userData; const char **attrs = (const char **) attributes; char *tag_name; char *att, *val; int val_len; zval *retval, *args[3]; if (parser) { parser->level++; tag_name = _xml_decode_tag(parser, name); if (parser->startElementHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset); MAKE_STD_ZVAL(args[2]); array_init(args[2]); while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(args[2], att, val, val_len, 0); attributes += 2; efree(att); } if ((retval = xml_call_handler(parser, parser->startElementHandler, parser->startElementPtr, 3, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { if (parser->level <= XML_MAXLEVEL) { zval *tag, *atr; int atcnt = 0; MAKE_STD_ZVAL(tag); MAKE_STD_ZVAL(atr); array_init(tag); array_init(atr); _xml_add_to_info(parser,((char *) tag_name) + parser->toffset); add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */ add_assoc_string(tag,"type","open",1); add_assoc_long(tag,"level",parser->level); parser->ltags[parser->level-1] = estrdup(tag_name); parser->lastwasopen = 1; attributes = (const XML_Char **) attrs; while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(atr,att,val,val_len,0); atcnt++; attributes += 2; efree(att); } if (atcnt) { zend_hash_add(Z_ARRVAL_P(tag),"attributes",sizeof("attributes"),&atr,sizeof(zval*),NULL); } else { zval_ptr_dtor(&atr); } zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),(void *) &parser->ctag); } else if (parser->level == (XML_MAXLEVEL + 1)) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated"); } } efree(tag_name); } }
165,042
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void nsc_decode(NSC_CONTEXT* context) { UINT16 x; UINT16 y; UINT16 rw = ROUND_UP_TO(context->width, 8); BYTE shift = context->ColorLossLevel - 1; /* colorloss recovery + YCoCg shift */ BYTE* bmpdata = context->BitmapData; for (y = 0; y < context->height; y++) { const BYTE* yplane; const BYTE* coplane; const BYTE* cgplane; const BYTE* aplane = context->priv->PlaneBuffers[3] + y * context->width; /* A */ if (context->ChromaSubsamplingLevel) { yplane = context->priv->PlaneBuffers[0] + y * rw; /* Y */ coplane = context->priv->PlaneBuffers[1] + (y >> 1) * (rw >> 1); /* Co, supersampled */ cgplane = context->priv->PlaneBuffers[2] + (y >> 1) * (rw >> 1); /* Cg, supersampled */ } else { yplane = context->priv->PlaneBuffers[0] + y * context->width; /* Y */ coplane = context->priv->PlaneBuffers[1] + y * context->width; /* Co */ cgplane = context->priv->PlaneBuffers[2] + y * context->width; /* Cg */ } for (x = 0; x < context->width; x++) { INT16 y_val = (INT16) * yplane; INT16 co_val = (INT16)(INT8)(*coplane << shift); INT16 cg_val = (INT16)(INT8)(*cgplane << shift); INT16 r_val = y_val + co_val - cg_val; INT16 g_val = y_val + cg_val; INT16 b_val = y_val - co_val - cg_val; *bmpdata++ = MINMAX(b_val, 0, 0xFF); *bmpdata++ = MINMAX(g_val, 0, 0xFF); *bmpdata++ = MINMAX(r_val, 0, 0xFF); *bmpdata++ = *aplane; yplane++; coplane += (context->ChromaSubsamplingLevel ? x % 2 : 1); cgplane += (context->ChromaSubsamplingLevel ? x % 2 : 1); aplane++; } } } Commit Message: Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-787
static void nsc_decode(NSC_CONTEXT* context) static BOOL nsc_decode(NSC_CONTEXT* context) { UINT16 x; UINT16 y; UINT16 rw; BYTE shift; BYTE* bmpdata; size_t pos = 0; if (!context) return FALSE; rw = ROUND_UP_TO(context->width, 8); shift = context->ColorLossLevel - 1; /* colorloss recovery + YCoCg shift */ bmpdata = context->BitmapData; if (!bmpdata) return FALSE; for (y = 0; y < context->height; y++) { const BYTE* yplane; const BYTE* coplane; const BYTE* cgplane; const BYTE* aplane = context->priv->PlaneBuffers[3] + y * context->width; /* A */ if (context->ChromaSubsamplingLevel) { yplane = context->priv->PlaneBuffers[0] + y * rw; /* Y */ coplane = context->priv->PlaneBuffers[1] + (y >> 1) * (rw >> 1); /* Co, supersampled */ cgplane = context->priv->PlaneBuffers[2] + (y >> 1) * (rw >> 1); /* Cg, supersampled */ } else { yplane = context->priv->PlaneBuffers[0] + y * context->width; /* Y */ coplane = context->priv->PlaneBuffers[1] + y * context->width; /* Co */ cgplane = context->priv->PlaneBuffers[2] + y * context->width; /* Cg */ } for (x = 0; x < context->width; x++) { INT16 y_val = (INT16) * yplane; INT16 co_val = (INT16)(INT8)(*coplane << shift); INT16 cg_val = (INT16)(INT8)(*cgplane << shift); INT16 r_val = y_val + co_val - cg_val; INT16 g_val = y_val + cg_val; INT16 b_val = y_val - co_val - cg_val; if (pos + 4 > context->BitmapDataLength) return FALSE; pos += 4; *bmpdata++ = MINMAX(b_val, 0, 0xFF); *bmpdata++ = MINMAX(g_val, 0, 0xFF); *bmpdata++ = MINMAX(r_val, 0, 0xFF); *bmpdata++ = *aplane; yplane++; coplane += (context->ChromaSubsamplingLevel ? x % 2 : 1); cgplane += (context->ChromaSubsamplingLevel ? x % 2 : 1); aplane++; } } return TRUE; }
169,282
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void jiffies_to_timeval(const unsigned long jiffies, struct timeval *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u64 nsec = (u64)jiffies * TICK_NSEC; long tv_usec; value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &tv_usec); tv_usec /= NSEC_PER_USEC; value->tv_usec = tv_usec; } Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189
void jiffies_to_timeval(const unsigned long jiffies, struct timeval *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u32 rem; value->tv_sec = div_u64_rem((u64)jiffies * TICK_NSEC, NSEC_PER_SEC, &rem); value->tv_usec = rem / NSEC_PER_USEC; }
165,755
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: stringprep_utf8_nfkc_normalize (const char *str, ssize_t len) { return g_utf8_normalize (str, len, G_NORMALIZE_NFKC); } Commit Message: CWE ID: CWE-125
stringprep_utf8_nfkc_normalize (const char *str, ssize_t len) { size_t n; if (len < 0) n = strlen (str); else n = len; if (u8_check ((const uint8_t *) str, n)) return NULL; return g_utf8_normalize (str, len, G_NORMALIZE_NFKC); }
164,984
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd) { PCIDevice *pci_dev = PCI_DEVICE(s); PCIDeviceClass *pci_class = PCI_DEVICE_GET_CLASS(pci_dev); MegasasBaseClass *base_class = MEGASAS_DEVICE_GET_CLASS(s); struct mfi_ctrl_info info; size_t dcmd_size = sizeof(info); BusChild *kid; int num_pd_disks = 0; memset(&info, 0x0, dcmd_size); if (cmd->iov_size < dcmd_size) { trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size, dcmd_size); return MFI_STAT_INVALID_PARAMETER; } info.pci.vendor = cpu_to_le16(pci_class->vendor_id); info.pci.device = cpu_to_le16(pci_class->device_id); info.pci.subvendor = cpu_to_le16(pci_class->subsystem_vendor_id); info.pci.subdevice = cpu_to_le16(pci_class->subsystem_id); /* * For some reason the firmware supports * only up to 8 device ports. * Despite supporting a far larger number * of devices for the physical devices. * So just display the first 8 devices * in the device port list, independent * of how many logical devices are actually * present. */ info.host.type = MFI_INFO_HOST_PCIE; info.device.type = MFI_INFO_DEV_SAS3G; info.device.port_count = 8; QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { SCSIDevice *sdev = SCSI_DEVICE(kid->child); uint16_t pd_id; if (num_pd_disks < 8) { pd_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF); info.device.port_addr[num_pd_disks] = cpu_to_le64(megasas_get_sata_addr(pd_id)); } num_pd_disks++; } memcpy(info.product_name, base_class->product_name, 24); snprintf(info.serial_number, 32, "%s", s->hba_serial); snprintf(info.package_version, 0x60, "%s-QEMU", qemu_hw_version()); memcpy(info.image_component[0].name, "APP", 3); snprintf(info.image_component[0].version, 10, "%s-QEMU", base_class->product_version); memcpy(info.image_component[0].build_date, "Apr 1 2014", 11); memcpy(info.image_component[0].build_time, "12:34:56", 8); info.image_component_count = 1; if (pci_dev->has_rom) { uint8_t biosver[32]; uint8_t *ptr; ptr = memory_region_get_ram_ptr(&pci_dev->rom); memcpy(biosver, ptr + 0x41, 31); memcpy(info.image_component[1].name, "BIOS", 4); memcpy(info.image_component[1].version, biosver, strlen((const char *)biosver)); } info.current_fw_time = cpu_to_le32(megasas_fw_time()); info.max_arms = 32; info.max_spans = 8; info.max_arrays = MEGASAS_MAX_ARRAYS; info.max_lds = MFI_MAX_LD; info.max_cmds = cpu_to_le16(s->fw_cmds); info.max_sg_elements = cpu_to_le16(s->fw_sge); info.max_request_size = cpu_to_le32(MEGASAS_MAX_SECTORS); if (!megasas_is_jbod(s)) info.lds_present = cpu_to_le16(num_pd_disks); info.pd_present = cpu_to_le16(num_pd_disks); info.pd_disks_present = cpu_to_le16(num_pd_disks); info.hw_present = cpu_to_le32(MFI_INFO_HW_NVRAM | MFI_INFO_HW_MEM | MFI_INFO_HW_FLASH); info.memory_size = cpu_to_le16(512); info.nvram_size = cpu_to_le16(32); info.flash_size = cpu_to_le16(16); info.raid_levels = cpu_to_le32(MFI_INFO_RAID_0); info.adapter_ops = cpu_to_le32(MFI_INFO_AOPS_RBLD_RATE | MFI_INFO_AOPS_SELF_DIAGNOSTIC | MFI_INFO_AOPS_MIXED_ARRAY); info.ld_ops = cpu_to_le32(MFI_INFO_LDOPS_DISK_CACHE_POLICY | MFI_INFO_LDOPS_ACCESS_POLICY | MFI_INFO_LDOPS_IO_POLICY | MFI_INFO_LDOPS_WRITE_POLICY | MFI_INFO_LDOPS_READ_POLICY); info.max_strips_per_io = cpu_to_le16(s->fw_sge); info.stripe_sz_ops.min = 3; info.stripe_sz_ops.max = ctz32(MEGASAS_MAX_SECTORS + 1); info.properties.pred_fail_poll_interval = cpu_to_le16(300); info.properties.intr_throttle_cnt = cpu_to_le16(16); info.properties.intr_throttle_timeout = cpu_to_le16(50); info.properties.rebuild_rate = 30; info.properties.patrol_read_rate = 30; info.properties.bgi_rate = 30; info.properties.cc_rate = 30; info.properties.recon_rate = 30; info.properties.cache_flush_interval = 4; info.properties.spinup_drv_cnt = 2; info.properties.spinup_delay = 6; info.properties.ecc_bucket_size = 15; info.properties.ecc_bucket_leak_rate = cpu_to_le16(1440); info.properties.expose_encl_devices = 1; info.properties.OnOffProperties = cpu_to_le32(MFI_CTRL_PROP_EnableJBOD); info.pd_ops = cpu_to_le32(MFI_INFO_PDOPS_FORCE_ONLINE | MFI_INFO_PDOPS_FORCE_OFFLINE); info.pd_mix_support = cpu_to_le32(MFI_INFO_PDMIX_SAS | MFI_INFO_PDMIX_SATA | MFI_INFO_PDMIX_LD); cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg); return MFI_STAT_OK; } Commit Message: CWE ID: CWE-200
static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd) { PCIDevice *pci_dev = PCI_DEVICE(s); PCIDeviceClass *pci_class = PCI_DEVICE_GET_CLASS(pci_dev); MegasasBaseClass *base_class = MEGASAS_DEVICE_GET_CLASS(s); struct mfi_ctrl_info info; size_t dcmd_size = sizeof(info); BusChild *kid; int num_pd_disks = 0; memset(&info, 0x0, dcmd_size); if (cmd->iov_size < dcmd_size) { trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size, dcmd_size); return MFI_STAT_INVALID_PARAMETER; } info.pci.vendor = cpu_to_le16(pci_class->vendor_id); info.pci.device = cpu_to_le16(pci_class->device_id); info.pci.subvendor = cpu_to_le16(pci_class->subsystem_vendor_id); info.pci.subdevice = cpu_to_le16(pci_class->subsystem_id); /* * For some reason the firmware supports * only up to 8 device ports. * Despite supporting a far larger number * of devices for the physical devices. * So just display the first 8 devices * in the device port list, independent * of how many logical devices are actually * present. */ info.host.type = MFI_INFO_HOST_PCIE; info.device.type = MFI_INFO_DEV_SAS3G; info.device.port_count = 8; QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { SCSIDevice *sdev = SCSI_DEVICE(kid->child); uint16_t pd_id; if (num_pd_disks < 8) { pd_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF); info.device.port_addr[num_pd_disks] = cpu_to_le64(megasas_get_sata_addr(pd_id)); } num_pd_disks++; } memcpy(info.product_name, base_class->product_name, 24); snprintf(info.serial_number, 32, "%s", s->hba_serial); snprintf(info.package_version, 0x60, "%s-QEMU", qemu_hw_version()); memcpy(info.image_component[0].name, "APP", 3); snprintf(info.image_component[0].version, 10, "%s-QEMU", base_class->product_version); memcpy(info.image_component[0].build_date, "Apr 1 2014", 11); memcpy(info.image_component[0].build_time, "12:34:56", 8); info.image_component_count = 1; if (pci_dev->has_rom) { uint8_t biosver[32]; uint8_t *ptr; ptr = memory_region_get_ram_ptr(&pci_dev->rom); memcpy(biosver, ptr + 0x41, 31); biosver[31] = 0; memcpy(info.image_component[1].name, "BIOS", 4); memcpy(info.image_component[1].version, biosver, strlen((const char *)biosver)); } info.current_fw_time = cpu_to_le32(megasas_fw_time()); info.max_arms = 32; info.max_spans = 8; info.max_arrays = MEGASAS_MAX_ARRAYS; info.max_lds = MFI_MAX_LD; info.max_cmds = cpu_to_le16(s->fw_cmds); info.max_sg_elements = cpu_to_le16(s->fw_sge); info.max_request_size = cpu_to_le32(MEGASAS_MAX_SECTORS); if (!megasas_is_jbod(s)) info.lds_present = cpu_to_le16(num_pd_disks); info.pd_present = cpu_to_le16(num_pd_disks); info.pd_disks_present = cpu_to_le16(num_pd_disks); info.hw_present = cpu_to_le32(MFI_INFO_HW_NVRAM | MFI_INFO_HW_MEM | MFI_INFO_HW_FLASH); info.memory_size = cpu_to_le16(512); info.nvram_size = cpu_to_le16(32); info.flash_size = cpu_to_le16(16); info.raid_levels = cpu_to_le32(MFI_INFO_RAID_0); info.adapter_ops = cpu_to_le32(MFI_INFO_AOPS_RBLD_RATE | MFI_INFO_AOPS_SELF_DIAGNOSTIC | MFI_INFO_AOPS_MIXED_ARRAY); info.ld_ops = cpu_to_le32(MFI_INFO_LDOPS_DISK_CACHE_POLICY | MFI_INFO_LDOPS_ACCESS_POLICY | MFI_INFO_LDOPS_IO_POLICY | MFI_INFO_LDOPS_WRITE_POLICY | MFI_INFO_LDOPS_READ_POLICY); info.max_strips_per_io = cpu_to_le16(s->fw_sge); info.stripe_sz_ops.min = 3; info.stripe_sz_ops.max = ctz32(MEGASAS_MAX_SECTORS + 1); info.properties.pred_fail_poll_interval = cpu_to_le16(300); info.properties.intr_throttle_cnt = cpu_to_le16(16); info.properties.intr_throttle_timeout = cpu_to_le16(50); info.properties.rebuild_rate = 30; info.properties.patrol_read_rate = 30; info.properties.bgi_rate = 30; info.properties.cc_rate = 30; info.properties.recon_rate = 30; info.properties.cache_flush_interval = 4; info.properties.spinup_drv_cnt = 2; info.properties.spinup_delay = 6; info.properties.ecc_bucket_size = 15; info.properties.ecc_bucket_leak_rate = cpu_to_le16(1440); info.properties.expose_encl_devices = 1; info.properties.OnOffProperties = cpu_to_le32(MFI_CTRL_PROP_EnableJBOD); info.pd_ops = cpu_to_le32(MFI_INFO_PDOPS_FORCE_ONLINE | MFI_INFO_PDOPS_FORCE_OFFLINE); info.pd_mix_support = cpu_to_le32(MFI_INFO_PDMIX_SAS | MFI_INFO_PDMIX_SATA | MFI_INFO_PDMIX_LD); cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg); return MFI_STAT_OK; }
165,013
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool NavigationControllerImpl::RendererDidNavigate( RenderFrameHostImpl* rfh, const FrameHostMsg_DidCommitProvisionalLoad_Params& params, LoadCommittedDetails* details, bool is_navigation_within_page, NavigationHandleImpl* navigation_handle) { is_initial_navigation_ = false; bool overriding_user_agent_changed = false; if (GetLastCommittedEntry()) { details->previous_url = GetLastCommittedEntry()->GetURL(); details->previous_entry_index = GetLastCommittedEntryIndex(); if (pending_entry_ && pending_entry_->GetIsOverridingUserAgent() != GetLastCommittedEntry()->GetIsOverridingUserAgent()) overriding_user_agent_changed = true; } else { details->previous_url = GURL(); details->previous_entry_index = -1; } bool was_restored = false; DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() || pending_entry_->restore_type() != RestoreType::NONE); if (pending_entry_ && pending_entry_->restore_type() != RestoreType::NONE) { pending_entry_->set_restore_type(RestoreType::NONE); was_restored = true; } details->did_replace_entry = params.should_replace_current_entry; details->type = ClassifyNavigation(rfh, params); details->is_same_document = is_navigation_within_page; if (PendingEntryMatchesHandle(navigation_handle)) { if (pending_entry_->reload_type() != ReloadType::NONE) { last_committed_reload_type_ = pending_entry_->reload_type(); last_committed_reload_time_ = time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run()); } else if (!pending_entry_->is_renderer_initiated() || params.gesture == NavigationGestureUser) { last_committed_reload_type_ = ReloadType::NONE; last_committed_reload_time_ = base::Time(); } } switch (details->type) { case NAVIGATION_TYPE_NEW_PAGE: RendererDidNavigateToNewPage(rfh, params, details->is_same_document, details->did_replace_entry, navigation_handle); break; case NAVIGATION_TYPE_EXISTING_PAGE: details->did_replace_entry = details->is_same_document; RendererDidNavigateToExistingPage(rfh, params, details->is_same_document, was_restored, navigation_handle); break; case NAVIGATION_TYPE_SAME_PAGE: RendererDidNavigateToSamePage(rfh, params, navigation_handle); break; case NAVIGATION_TYPE_NEW_SUBFRAME: RendererDidNavigateNewSubframe(rfh, params, details->is_same_document, details->did_replace_entry); break; case NAVIGATION_TYPE_AUTO_SUBFRAME: if (!RendererDidNavigateAutoSubframe(rfh, params)) { NotifyEntryChanged(GetLastCommittedEntry()); return false; } break; case NAVIGATION_TYPE_NAV_IGNORE: if (pending_entry_) { DiscardNonCommittedEntries(); delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL); } return false; default: NOTREACHED(); } base::Time timestamp = time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run()); DVLOG(1) << "Navigation finished at (smoothed) timestamp " << timestamp.ToInternalValue(); DiscardNonCommittedEntriesInternal(); DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState."; NavigationEntryImpl* active_entry = GetLastCommittedEntry(); active_entry->SetTimestamp(timestamp); active_entry->SetHttpStatusCode(params.http_status_code); FrameNavigationEntry* frame_entry = active_entry->GetFrameEntry(rfh->frame_tree_node()); if (frame_entry) { frame_entry->SetPageState(params.page_state); frame_entry->set_redirect_chain(params.redirects); } if (!rfh->GetParent() && IsBlockedNavigation(navigation_handle->GetNetErrorCode())) { DCHECK(params.url_is_unreachable); active_entry->SetURL(GURL(url::kAboutBlankURL)); active_entry->SetVirtualURL(params.url); if (frame_entry) { frame_entry->SetPageState( PageState::CreateFromURL(active_entry->GetURL())); } } size_t redirect_chain_size = 0; for (size_t i = 0; i < params.redirects.size(); ++i) { redirect_chain_size += params.redirects[i].spec().length(); } UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size); active_entry->ResetForCommit(frame_entry); if (!rfh->GetParent()) CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance()); active_entry->SetBindings(rfh->GetEnabledBindings()); details->entry = active_entry; details->is_main_frame = !rfh->GetParent(); details->http_status_code = params.http_status_code; NotifyNavigationEntryCommitted(details); if (active_entry->GetURL().SchemeIs(url::kHttpsScheme) && !rfh->GetParent() && navigation_handle->GetNetErrorCode() == net::OK) { UMA_HISTOGRAM_BOOLEAN("Navigation.SecureSchemeHasSSLStatus", !!active_entry->GetSSL().certificate); } if (overriding_user_agent_changed) delegate_->UpdateOverridingUserAgent(); int nav_entry_id = active_entry->GetUniqueID(); for (FrameTreeNode* node : delegate_->GetFrameTree()->Nodes()) node->current_frame_host()->set_nav_entry_id(nav_entry_id); return true; } Commit Message: Don't update PageState for a SiteInstance mismatch. BUG=766262 TEST=See bug for repro. Change-Id: Ifb087b687acd40d8963ef436c9ea82ca2d960117 Reviewed-on: https://chromium-review.googlesource.com/674808 Commit-Queue: Charlie Reis (OOO until 9/25) <[email protected]> Reviewed-by: Łukasz Anforowicz <[email protected]> Cr-Commit-Position: refs/heads/master@{#503297} CWE ID:
bool NavigationControllerImpl::RendererDidNavigate( RenderFrameHostImpl* rfh, const FrameHostMsg_DidCommitProvisionalLoad_Params& params, LoadCommittedDetails* details, bool is_navigation_within_page, NavigationHandleImpl* navigation_handle) { is_initial_navigation_ = false; bool overriding_user_agent_changed = false; if (GetLastCommittedEntry()) { details->previous_url = GetLastCommittedEntry()->GetURL(); details->previous_entry_index = GetLastCommittedEntryIndex(); if (pending_entry_ && pending_entry_->GetIsOverridingUserAgent() != GetLastCommittedEntry()->GetIsOverridingUserAgent()) overriding_user_agent_changed = true; } else { details->previous_url = GURL(); details->previous_entry_index = -1; } bool was_restored = false; DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() || pending_entry_->restore_type() != RestoreType::NONE); if (pending_entry_ && pending_entry_->restore_type() != RestoreType::NONE) { pending_entry_->set_restore_type(RestoreType::NONE); was_restored = true; } details->did_replace_entry = params.should_replace_current_entry; details->type = ClassifyNavigation(rfh, params); details->is_same_document = is_navigation_within_page; if (PendingEntryMatchesHandle(navigation_handle)) { if (pending_entry_->reload_type() != ReloadType::NONE) { last_committed_reload_type_ = pending_entry_->reload_type(); last_committed_reload_time_ = time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run()); } else if (!pending_entry_->is_renderer_initiated() || params.gesture == NavigationGestureUser) { last_committed_reload_type_ = ReloadType::NONE; last_committed_reload_time_ = base::Time(); } } switch (details->type) { case NAVIGATION_TYPE_NEW_PAGE: RendererDidNavigateToNewPage(rfh, params, details->is_same_document, details->did_replace_entry, navigation_handle); break; case NAVIGATION_TYPE_EXISTING_PAGE: details->did_replace_entry = details->is_same_document; RendererDidNavigateToExistingPage(rfh, params, details->is_same_document, was_restored, navigation_handle); break; case NAVIGATION_TYPE_SAME_PAGE: RendererDidNavigateToSamePage(rfh, params, navigation_handle); break; case NAVIGATION_TYPE_NEW_SUBFRAME: RendererDidNavigateNewSubframe(rfh, params, details->is_same_document, details->did_replace_entry); break; case NAVIGATION_TYPE_AUTO_SUBFRAME: if (!RendererDidNavigateAutoSubframe(rfh, params)) { NotifyEntryChanged(GetLastCommittedEntry()); return false; } break; case NAVIGATION_TYPE_NAV_IGNORE: if (pending_entry_) { DiscardNonCommittedEntries(); delegate_->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL); } return false; default: NOTREACHED(); } base::Time timestamp = time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run()); DVLOG(1) << "Navigation finished at (smoothed) timestamp " << timestamp.ToInternalValue(); DiscardNonCommittedEntriesInternal(); DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState."; NavigationEntryImpl* active_entry = GetLastCommittedEntry(); active_entry->SetTimestamp(timestamp); active_entry->SetHttpStatusCode(params.http_status_code); // Grab the corresponding FrameNavigationEntry for a few updates, but only if // the SiteInstance matches (to avoid updating the wrong entry by mistake). // A mismatch can occur if the renderer lies or due to a unique name collision // after a race with an OOPIF (see https://crbug.com/616820). FrameNavigationEntry* frame_entry = active_entry->GetFrameEntry(rfh->frame_tree_node()); if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance()) frame_entry = nullptr; if (frame_entry) { frame_entry->SetPageState(params.page_state); frame_entry->set_redirect_chain(params.redirects); } if (!rfh->GetParent() && IsBlockedNavigation(navigation_handle->GetNetErrorCode())) { DCHECK(params.url_is_unreachable); active_entry->SetURL(GURL(url::kAboutBlankURL)); active_entry->SetVirtualURL(params.url); if (frame_entry) { frame_entry->SetPageState( PageState::CreateFromURL(active_entry->GetURL())); } } size_t redirect_chain_size = 0; for (size_t i = 0; i < params.redirects.size(); ++i) { redirect_chain_size += params.redirects[i].spec().length(); } UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size); active_entry->ResetForCommit(frame_entry); if (!rfh->GetParent()) CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance()); active_entry->SetBindings(rfh->GetEnabledBindings()); details->entry = active_entry; details->is_main_frame = !rfh->GetParent(); details->http_status_code = params.http_status_code; NotifyNavigationEntryCommitted(details); if (active_entry->GetURL().SchemeIs(url::kHttpsScheme) && !rfh->GetParent() && navigation_handle->GetNetErrorCode() == net::OK) { UMA_HISTOGRAM_BOOLEAN("Navigation.SecureSchemeHasSSLStatus", !!active_entry->GetSSL().certificate); } if (overriding_user_agent_changed) delegate_->UpdateOverridingUserAgent(); int nav_entry_id = active_entry->GetUniqueID(); for (FrameTreeNode* node : delegate_->GetFrameTree()->Nodes()) node->current_frame_host()->set_nav_entry_id(nav_entry_id); return true; }
173,259
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewAura::OnLostResources() { image_transport_clients_.clear(); current_surface_ = 0; protection_state_id_ = 0; current_surface_is_protected_ = true; current_surface_in_use_by_compositor_ = true; surface_route_id_ = 0; UpdateExternalTexture(); locks_pending_commit_.clear(); DCHECK(!shared_surface_handle_.is_null()); ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); factory->DestroySharedSurfaceHandle(shared_surface_handle_); shared_surface_handle_ = factory->CreateSharedSurfaceHandle(); host_->CompositingSurfaceUpdated(); host_->ScheduleComposite(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewAura::OnLostResources() { image_transport_clients_.clear(); current_surface_ = 0; UpdateExternalTexture(); locks_pending_commit_.clear(); DCHECK(!shared_surface_handle_.is_null()); ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); factory->DestroySharedSurfaceHandle(shared_surface_handle_); shared_surface_handle_ = factory->CreateSharedSurfaceHandle(); host_->CompositingSurfaceUpdated(); host_->ScheduleComposite(); }
171,381
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long ContentEncoding::ParseContentEncAESSettingsEntry( long long start, long long size, IMkvReader* pReader, ContentEncAESSettings* aes) { assert(pReader); assert(aes); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) //error return status; if (id == 0x7E8) { aes->cipher_mode = UnserializeUInt(pReader, pos, size); if (aes->cipher_mode != 1) return E_FILE_FORMAT_INVALID; } pos += size; //consume payload assert(pos <= stop); } return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long ContentEncoding::ParseContentEncAESSettingsEntry( long long start, long long size, IMkvReader* pReader, ContentEncAESSettings* aes) { assert(pReader); assert(aes); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x7E8) { aes->cipher_mode = UnserializeUInt(pReader, pos, size); if (aes->cipher_mode != 1) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload assert(pos <= stop); } return 0; }
174,418
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: jiffies_to_timespec(const unsigned long jiffies, struct timespec *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u64 nsec = (u64)jiffies * TICK_NSEC; value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &value->tv_nsec); } Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189
jiffies_to_timespec(const unsigned long jiffies, struct timespec *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u32 rem; value->tv_sec = div_u64_rem((u64)jiffies * TICK_NSEC, NSEC_PER_SEC, &rem); value->tv_nsec = rem; }
165,754
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: IHEVCD_ERROR_T ihevcd_parse_slice_header(codec_t *ps_codec, nal_header_t *ps_nal) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; WORD32 value; WORD32 i; WORD32 sps_id; pps_t *ps_pps; sps_t *ps_sps; slice_header_t *ps_slice_hdr; WORD32 disable_deblocking_filter_flag; bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm; WORD32 idr_pic_flag; WORD32 pps_id; WORD32 first_slice_in_pic_flag; WORD32 no_output_of_prior_pics_flag = 0; WORD8 i1_nal_unit_type = ps_nal->i1_nal_unit_type; WORD32 num_poc_total_curr = 0; WORD32 slice_address; if(ps_codec->i4_slice_error == 1) return ret; idr_pic_flag = (NAL_IDR_W_LP == i1_nal_unit_type) || (NAL_IDR_N_LP == i1_nal_unit_type); BITS_PARSE("first_slice_in_pic_flag", first_slice_in_pic_flag, ps_bitstrm, 1); if((NAL_BLA_W_LP <= i1_nal_unit_type) && (NAL_RSV_RAP_VCL23 >= i1_nal_unit_type)) { BITS_PARSE("no_output_of_prior_pics_flag", no_output_of_prior_pics_flag, ps_bitstrm, 1); } UEV_PARSE("pic_parameter_set_id", pps_id, ps_bitstrm); pps_id = CLIP3(pps_id, 0, MAX_PPS_CNT - 2); /* Get the current PPS structure */ ps_pps = ps_codec->s_parse.ps_pps_base + pps_id; if(0 == ps_pps->i1_pps_valid) { pps_t *ps_pps_ref = ps_codec->ps_pps_base; while(0 == ps_pps_ref->i1_pps_valid) ps_pps_ref++; if((ps_pps_ref - ps_codec->ps_pps_base >= MAX_PPS_CNT - 1)) return IHEVCD_INVALID_HEADER; ihevcd_copy_pps(ps_codec, pps_id, ps_pps_ref->i1_pps_id); } /* Get SPS id for the current PPS */ sps_id = ps_pps->i1_sps_id; /* Get the current SPS structure */ ps_sps = ps_codec->s_parse.ps_sps_base + sps_id; /* When the current slice is the first in a pic, * check whether the previous frame is complete * If the previous frame is incomplete - * treat the remaining CTBs as skip */ if((0 != ps_codec->u4_pic_cnt || ps_codec->i4_pic_present) && first_slice_in_pic_flag) { if(ps_codec->i4_pic_present) { slice_header_t *ps_slice_hdr_next; ps_codec->i4_slice_error = 1; ps_codec->s_parse.i4_cur_slice_idx--; if(ps_codec->s_parse.i4_cur_slice_idx < 0) ps_codec->s_parse.i4_cur_slice_idx = 0; ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1)); ps_slice_hdr_next->i2_ctb_x = 0; ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb; return ret; } else { ps_codec->i4_slice_error = 0; } } if(first_slice_in_pic_flag) { ps_codec->s_parse.i4_cur_slice_idx = 0; } else { /* If the current slice is not the first slice in the pic, * but the first one to be parsed, set the current slice indx to 1 * Treat the first slice to be missing and copy the current slice header * to the first one */ if(0 == ps_codec->i4_pic_present) ps_codec->s_parse.i4_cur_slice_idx = 1; } ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)); if((ps_pps->i1_dependent_slice_enabled_flag) && (!first_slice_in_pic_flag)) { BITS_PARSE("dependent_slice_flag", value, ps_bitstrm, 1); /* If dependendent slice, copy slice header from previous slice */ if(value && (ps_codec->s_parse.i4_cur_slice_idx > 0)) { ihevcd_copy_slice_hdr(ps_codec, (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)), ((ps_codec->s_parse.i4_cur_slice_idx - 1) & (MAX_SLICE_HDR_CNT - 1))); } ps_slice_hdr->i1_dependent_slice_flag = value; } else { ps_slice_hdr->i1_dependent_slice_flag = 0; } ps_slice_hdr->i1_nal_unit_type = i1_nal_unit_type; ps_slice_hdr->i1_pps_id = pps_id; ps_slice_hdr->i1_first_slice_in_pic_flag = first_slice_in_pic_flag; ps_slice_hdr->i1_no_output_of_prior_pics_flag = 1; if((NAL_BLA_W_LP <= i1_nal_unit_type) && (NAL_RSV_RAP_VCL23 >= i1_nal_unit_type)) { ps_slice_hdr->i1_no_output_of_prior_pics_flag = no_output_of_prior_pics_flag; } ps_slice_hdr->i1_pps_id = pps_id; if(!ps_slice_hdr->i1_first_slice_in_pic_flag) { WORD32 num_bits; /* Use CLZ to compute Ceil( Log2( PicSizeInCtbsY ) ) */ num_bits = 32 - CLZ(ps_sps->i4_pic_size_in_ctb - 1); BITS_PARSE("slice_address", value, ps_bitstrm, num_bits); slice_address = value; /* If slice address is greater than the number of CTBs in a picture, * ignore the slice */ if(value >= ps_sps->i4_pic_size_in_ctb) return IHEVCD_IGNORE_SLICE; } else { slice_address = 0; } if(!ps_slice_hdr->i1_dependent_slice_flag) { ps_slice_hdr->i1_pic_output_flag = 1; ps_slice_hdr->i4_pic_order_cnt_lsb = 0; ps_slice_hdr->i1_num_long_term_sps = 0; ps_slice_hdr->i1_num_long_term_pics = 0; for(i = 0; i < ps_pps->i1_num_extra_slice_header_bits; i++) { BITS_PARSE("slice_reserved_undetermined_flag[ i ]", value, ps_bitstrm, 1); } UEV_PARSE("slice_type", value, ps_bitstrm); ps_slice_hdr->i1_slice_type = value; /* If the picture is IRAP, slice type must be equal to ISLICE */ if((ps_slice_hdr->i1_nal_unit_type >= NAL_BLA_W_LP) && (ps_slice_hdr->i1_nal_unit_type <= NAL_RSV_RAP_VCL23)) ps_slice_hdr->i1_slice_type = ISLICE; if((ps_slice_hdr->i1_slice_type < 0) || (ps_slice_hdr->i1_slice_type > 2)) return IHEVCD_IGNORE_SLICE; if(ps_pps->i1_output_flag_present_flag) { BITS_PARSE("pic_output_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_pic_output_flag = value; } ps_slice_hdr->i1_colour_plane_id = 0; if(1 == ps_sps->i1_separate_colour_plane_flag) { BITS_PARSE("colour_plane_id", value, ps_bitstrm, 2); ps_slice_hdr->i1_colour_plane_id = value; } ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = 0; if(!idr_pic_flag) { WORD32 st_rps_idx; WORD32 num_neg_pics; WORD32 num_pos_pics; WORD8 *pi1_used; BITS_PARSE("pic_order_cnt_lsb", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb); ps_slice_hdr->i4_pic_order_cnt_lsb = value; BITS_PARSE("short_term_ref_pic_set_sps_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag = value; if(1 == ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag) { WORD32 numbits; ps_slice_hdr->i1_short_term_ref_pic_set_idx = 0; if(ps_sps->i1_num_short_term_ref_pic_sets > 1) { numbits = 32 - CLZ(ps_sps->i1_num_short_term_ref_pic_sets - 1); BITS_PARSE("short_term_ref_pic_set_idx", value, ps_bitstrm, numbits); ps_slice_hdr->i1_short_term_ref_pic_set_idx = value; } st_rps_idx = ps_slice_hdr->i1_short_term_ref_pic_set_idx; num_neg_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_neg_pics; num_pos_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_pos_pics; pi1_used = ps_sps->as_stref_picset[st_rps_idx].ai1_used; } else { ihevcd_short_term_ref_pic_set(ps_bitstrm, &ps_sps->as_stref_picset[0], ps_sps->i1_num_short_term_ref_pic_sets, ps_sps->i1_num_short_term_ref_pic_sets, &ps_slice_hdr->s_stref_picset); st_rps_idx = ps_sps->i1_num_short_term_ref_pic_sets; num_neg_pics = ps_slice_hdr->s_stref_picset.i1_num_neg_pics; num_pos_pics = ps_slice_hdr->s_stref_picset.i1_num_pos_pics; pi1_used = ps_slice_hdr->s_stref_picset.ai1_used; } if(ps_sps->i1_long_term_ref_pics_present_flag) { if(ps_sps->i1_num_long_term_ref_pics_sps > 0) { UEV_PARSE("num_long_term_sps", value, ps_bitstrm); ps_slice_hdr->i1_num_long_term_sps = value; ps_slice_hdr->i1_num_long_term_sps = CLIP3(ps_slice_hdr->i1_num_long_term_sps, 0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics); } UEV_PARSE("num_long_term_pics", value, ps_bitstrm); ps_slice_hdr->i1_num_long_term_pics = value; ps_slice_hdr->i1_num_long_term_pics = CLIP3(ps_slice_hdr->i1_num_long_term_pics, 0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics - ps_slice_hdr->i1_num_long_term_sps); for(i = 0; i < (ps_slice_hdr->i1_num_long_term_sps + ps_slice_hdr->i1_num_long_term_pics); i++) { if(i < ps_slice_hdr->i1_num_long_term_sps) { /* Use CLZ to compute Ceil( Log2( num_long_term_ref_pics_sps ) ) */ WORD32 num_bits = 32 - CLZ(ps_sps->i1_num_long_term_ref_pics_sps); BITS_PARSE("lt_idx_sps[ i ]", value, ps_bitstrm, num_bits); ps_slice_hdr->ai4_poc_lsb_lt[i] = ps_sps->ai1_lt_ref_pic_poc_lsb_sps[value]; ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = ps_sps->ai1_used_by_curr_pic_lt_sps_flag[value]; } else { BITS_PARSE("poc_lsb_lt[ i ]", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb); ps_slice_hdr->ai4_poc_lsb_lt[i] = value; BITS_PARSE("used_by_curr_pic_lt_flag[ i ]", value, ps_bitstrm, 1); ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = value; } BITS_PARSE("delta_poc_msb_present_flag[ i ]", value, ps_bitstrm, 1); ps_slice_hdr->ai1_delta_poc_msb_present_flag[i] = value; ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = 0; if(ps_slice_hdr->ai1_delta_poc_msb_present_flag[i]) { UEV_PARSE("delata_poc_msb_cycle_lt[ i ]", value, ps_bitstrm); ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = value; } if((i != 0) && (i != ps_slice_hdr->i1_num_long_term_sps)) { ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] += ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i - 1]; } } } for(i = 0; i < num_neg_pics + num_pos_pics; i++) { if(pi1_used[i]) { num_poc_total_curr++; } } for(i = 0; i < ps_slice_hdr->i1_num_long_term_sps + ps_slice_hdr->i1_num_long_term_pics; i++) { if(ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i]) { num_poc_total_curr++; } } if(ps_sps->i1_sps_temporal_mvp_enable_flag) { BITS_PARSE("enable_temporal_mvp_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = value; } } ps_slice_hdr->i1_slice_sao_luma_flag = 0; ps_slice_hdr->i1_slice_sao_chroma_flag = 0; if(ps_sps->i1_sample_adaptive_offset_enabled_flag) { BITS_PARSE("slice_sao_luma_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_sao_luma_flag = value; BITS_PARSE("slice_sao_chroma_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_sao_chroma_flag = value; } ps_slice_hdr->i1_max_num_merge_cand = 1; ps_slice_hdr->i1_cabac_init_flag = 0; ps_slice_hdr->i1_num_ref_idx_l0_active = 0; ps_slice_hdr->i1_num_ref_idx_l1_active = 0; ps_slice_hdr->i1_slice_cb_qp_offset = 0; ps_slice_hdr->i1_slice_cr_qp_offset = 0; if((PSLICE == ps_slice_hdr->i1_slice_type) || (BSLICE == ps_slice_hdr->i1_slice_type)) { BITS_PARSE("num_ref_idx_active_override_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_num_ref_idx_active_override_flag = value; if(ps_slice_hdr->i1_num_ref_idx_active_override_flag) { UEV_PARSE("num_ref_idx_l0_active_minus1", value, ps_bitstrm); ps_slice_hdr->i1_num_ref_idx_l0_active = value + 1; if(BSLICE == ps_slice_hdr->i1_slice_type) { UEV_PARSE("num_ref_idx_l1_active_minus1", value, ps_bitstrm); ps_slice_hdr->i1_num_ref_idx_l1_active = value + 1; } } else { ps_slice_hdr->i1_num_ref_idx_l0_active = ps_pps->i1_num_ref_idx_l0_default_active; if(BSLICE == ps_slice_hdr->i1_slice_type) { ps_slice_hdr->i1_num_ref_idx_l1_active = ps_pps->i1_num_ref_idx_l1_default_active; } } ps_slice_hdr->i1_num_ref_idx_l0_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l0_active, 0, MAX_DPB_SIZE - 1); ps_slice_hdr->i1_num_ref_idx_l1_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l1_active, 0, MAX_DPB_SIZE - 1); if(0 == num_poc_total_curr) return IHEVCD_IGNORE_SLICE; if((ps_pps->i1_lists_modification_present_flag) && (num_poc_total_curr > 1)) { ihevcd_ref_pic_list_modification(ps_bitstrm, ps_slice_hdr, num_poc_total_curr); } else { ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l0 = 0; ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l1 = 0; } if(BSLICE == ps_slice_hdr->i1_slice_type) { BITS_PARSE("mvd_l1_zero_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_mvd_l1_zero_flag = value; } ps_slice_hdr->i1_cabac_init_flag = 0; if(ps_pps->i1_cabac_init_present_flag) { BITS_PARSE("cabac_init_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_cabac_init_flag = value; } ps_slice_hdr->i1_collocated_from_l0_flag = 1; ps_slice_hdr->i1_collocated_ref_idx = 0; if(ps_slice_hdr->i1_slice_temporal_mvp_enable_flag) { if(BSLICE == ps_slice_hdr->i1_slice_type) { BITS_PARSE("collocated_from_l0_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_collocated_from_l0_flag = value; } if((ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l0_active > 1)) || (!ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l1_active > 1))) { UEV_PARSE("collocated_ref_idx", value, ps_bitstrm); ps_slice_hdr->i1_collocated_ref_idx = value; } } ps_slice_hdr->i1_collocated_ref_idx = CLIP3(ps_slice_hdr->i1_collocated_ref_idx, 0, MAX_DPB_SIZE - 1); if((ps_pps->i1_weighted_pred_flag && (PSLICE == ps_slice_hdr->i1_slice_type)) || (ps_pps->i1_weighted_bipred_flag && (BSLICE == ps_slice_hdr->i1_slice_type))) { ihevcd_parse_pred_wt_ofst(ps_bitstrm, ps_sps, ps_pps, ps_slice_hdr); } UEV_PARSE("five_minus_max_num_merge_cand", value, ps_bitstrm); ps_slice_hdr->i1_max_num_merge_cand = 5 - value; } ps_slice_hdr->i1_max_num_merge_cand = CLIP3(ps_slice_hdr->i1_max_num_merge_cand, 1, 5); SEV_PARSE("slice_qp_delta", value, ps_bitstrm); ps_slice_hdr->i1_slice_qp_delta = value; if(ps_pps->i1_pic_slice_level_chroma_qp_offsets_present_flag) { SEV_PARSE("slice_cb_qp_offset", value, ps_bitstrm); ps_slice_hdr->i1_slice_cb_qp_offset = value; SEV_PARSE("slice_cr_qp_offset", value, ps_bitstrm); ps_slice_hdr->i1_slice_cr_qp_offset = value; } ps_slice_hdr->i1_deblocking_filter_override_flag = 0; ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag; ps_slice_hdr->i1_beta_offset_div2 = ps_pps->i1_beta_offset_div2; ps_slice_hdr->i1_tc_offset_div2 = ps_pps->i1_tc_offset_div2; disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag; if(ps_pps->i1_deblocking_filter_control_present_flag) { if(ps_pps->i1_deblocking_filter_override_enabled_flag) { BITS_PARSE("deblocking_filter_override_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_deblocking_filter_override_flag = value; } if(ps_slice_hdr->i1_deblocking_filter_override_flag) { BITS_PARSE("slice_disable_deblocking_filter_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = value; disable_deblocking_filter_flag = ps_slice_hdr->i1_slice_disable_deblocking_filter_flag; if(!ps_slice_hdr->i1_slice_disable_deblocking_filter_flag) { SEV_PARSE("beta_offset_div2", value, ps_bitstrm); ps_slice_hdr->i1_beta_offset_div2 = value; SEV_PARSE("tc_offset_div2", value, ps_bitstrm); ps_slice_hdr->i1_tc_offset_div2 = value; } } } ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = ps_pps->i1_loop_filter_across_slices_enabled_flag; if(ps_pps->i1_loop_filter_across_slices_enabled_flag && (ps_slice_hdr->i1_slice_sao_luma_flag || ps_slice_hdr->i1_slice_sao_chroma_flag || !disable_deblocking_filter_flag)) { BITS_PARSE("slice_loop_filter_across_slices_enabled_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = value; } } /* Check sanity of slice */ if((!first_slice_in_pic_flag) && (ps_codec->i4_pic_present)) { slice_header_t *ps_slice_hdr_base = ps_codec->ps_slice_hdr_base; /* According to the standard, the above conditions must be satisfied - But for error resilience, * only the following conditions are checked */ if((ps_slice_hdr_base->i1_pps_id != ps_slice_hdr->i1_pps_id) || (ps_slice_hdr_base->i4_pic_order_cnt_lsb != ps_slice_hdr->i4_pic_order_cnt_lsb)) { return IHEVCD_IGNORE_SLICE; } } if(0 == ps_codec->i4_pic_present) { ps_slice_hdr->i4_abs_pic_order_cnt = ihevcd_calc_poc(ps_codec, ps_nal, ps_sps->i1_log2_max_pic_order_cnt_lsb, ps_slice_hdr->i4_pic_order_cnt_lsb); } else { ps_slice_hdr->i4_abs_pic_order_cnt = ps_codec->s_parse.i4_abs_pic_order_cnt; } if(!first_slice_in_pic_flag) { /* Check if the current slice belongs to the same pic (Pic being parsed) */ if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt) { /* If the Next CTB's index is less than the slice address, * the previous slice is incomplete. * Indicate slice error, and treat the remaining CTBs as skip */ if(slice_address > ps_codec->s_parse.i4_next_ctb_indx) { if(ps_codec->i4_pic_present) { ps_codec->i4_slice_error = 1; ps_codec->s_parse.i4_cur_slice_idx--; if(ps_codec->s_parse.i4_cur_slice_idx < 0) ps_codec->s_parse.i4_cur_slice_idx = 0; return ret; } else { return IHEVCD_IGNORE_SLICE; } } /* If the slice address is less than the next CTB's index, * extra CTBs have been decoded in the previous slice. * Ignore the current slice. Treat it as incomplete */ else if(slice_address < ps_codec->s_parse.i4_next_ctb_indx) { return IHEVCD_IGNORE_SLICE; } else { ps_codec->i4_slice_error = 0; } } /* The current slice does not belong to the pic that is being parsed */ else { /* The previous pic is incomplete. * Treat the remaining CTBs as skip */ if(ps_codec->i4_pic_present) { slice_header_t *ps_slice_hdr_next; ps_codec->i4_slice_error = 1; ps_codec->s_parse.i4_cur_slice_idx--; if(ps_codec->s_parse.i4_cur_slice_idx < 0) ps_codec->s_parse.i4_cur_slice_idx = 0; ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1)); ps_slice_hdr_next->i2_ctb_x = 0; ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb; return ret; } /* If the previous pic is complete, * return if the current slice is dependant * otherwise, update the parse context's POC */ else { if(ps_slice_hdr->i1_dependent_slice_flag) return IHEVCD_IGNORE_SLICE; ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt; } } } /* If the slice is the first slice in the pic, update the parse context's POC */ else { /* If the first slice is repeated, ignore the second occurrence * If any other slice is repeated, the CTB addr will be greater than the slice addr, * and hence the second occurrence is ignored */ if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt) return IHEVCD_IGNORE_SLICE; ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt; } ps_slice_hdr->i4_num_entry_point_offsets = 0; if((ps_pps->i1_tiles_enabled_flag) || (ps_pps->i1_entropy_coding_sync_enabled_flag)) { UEV_PARSE("num_entry_point_offsets", value, ps_bitstrm); ps_slice_hdr->i4_num_entry_point_offsets = value; { WORD32 max_num_entry_point_offsets; if((ps_pps->i1_tiles_enabled_flag) && (ps_pps->i1_entropy_coding_sync_enabled_flag)) { max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * (ps_sps->i2_pic_ht_in_ctb - 1); } else if(ps_pps->i1_tiles_enabled_flag) { max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * ps_pps->i1_num_tile_rows; } else { max_num_entry_point_offsets = (ps_sps->i2_pic_ht_in_ctb - 1); } ps_slice_hdr->i4_num_entry_point_offsets = CLIP3(ps_slice_hdr->i4_num_entry_point_offsets, 0, max_num_entry_point_offsets); } if(ps_slice_hdr->i4_num_entry_point_offsets > 0) { UEV_PARSE("offset_len_minus1", value, ps_bitstrm); ps_slice_hdr->i1_offset_len = value + 1; for(i = 0; i < ps_slice_hdr->i4_num_entry_point_offsets; i++) { BITS_PARSE("entry_point_offset", value, ps_bitstrm, ps_slice_hdr->i1_offset_len); /* TODO: pu4_entry_point_offset needs to be initialized */ } } } if(ps_pps->i1_slice_header_extension_present_flag) { UEV_PARSE("slice_header_extension_length", value, ps_bitstrm); ps_slice_hdr->i2_slice_header_extension_length = value; for(i = 0; i < ps_slice_hdr->i2_slice_header_extension_length; i++) { BITS_PARSE("slice_header_extension_data_byte", value, ps_bitstrm, 8); } } ihevcd_bits_flush_to_byte_boundary(ps_bitstrm); { dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr; WORD32 r_idx; if((NAL_IDR_W_LP == ps_slice_hdr->i1_nal_unit_type) || (NAL_IDR_N_LP == ps_slice_hdr->i1_nal_unit_type) || (NAL_BLA_N_LP == ps_slice_hdr->i1_nal_unit_type) || (NAL_BLA_W_DLP == ps_slice_hdr->i1_nal_unit_type) || (NAL_BLA_W_LP == ps_slice_hdr->i1_nal_unit_type) || (0 == ps_codec->u4_pic_cnt)) { for(i = 0; i < MAX_DPB_BUFS; i++) { if(ps_dpb_mgr->as_dpb_info[i].ps_pic_buf) { pic_buf_t *ps_pic_buf = ps_dpb_mgr->as_dpb_info[i].ps_pic_buf; mv_buf_t *ps_mv_buf; /* Long term index is set to MAX_DPB_BUFS to ensure it is not added as LT */ ihevc_dpb_mgr_del_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, (buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_pic_buf->i4_abs_poc); /* Find buffer id of the MV bank corresponding to the buffer being freed (Buffer with POC of u4_abs_poc) */ ps_mv_buf = (mv_buf_t *)ps_codec->ps_mv_buf; for(i = 0; i < BUF_MGR_MAX_CNT; i++) { if(ps_mv_buf && ps_mv_buf->i4_abs_poc == ps_pic_buf->i4_abs_poc) { ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, i, BUF_MGR_REF); break; } ps_mv_buf++; } } } /* Initialize the reference lists to NULL * This is done to take care of the cases where the first pic is not IDR * but the reference list is not created for the first pic because * pic count is zero leaving the reference list uninitialised */ for(r_idx = 0; r_idx < MAX_DPB_SIZE; r_idx++) { ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = NULL; ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = NULL; ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = NULL; ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = NULL; } } else { ret = ihevcd_ref_list(ps_codec, ps_pps, ps_sps, ps_slice_hdr); if ((WORD32)IHEVCD_SUCCESS != ret) { return ret; } } } /* Fill the remaining entries of the reference lists with the nearest POC * This is done to handle cases where there is a corruption in the reference index */ if(ps_codec->i4_pic_present) { pic_buf_t *ps_pic_buf_ref; mv_buf_t *ps_mv_buf_ref; WORD32 r_idx; dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr; buf_mgr_t *ps_mv_buf_mgr = (buf_mgr_t *)ps_codec->pv_mv_buf_mgr; ps_pic_buf_ref = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ps_slice_hdr->i4_abs_pic_order_cnt); if(NULL == ps_pic_buf_ref) { ps_pic_buf_ref = ps_codec->as_process[0].ps_cur_pic; ps_mv_buf_ref = ps_codec->s_parse.ps_cur_mv_buf; } else { ps_mv_buf_ref = ihevcd_mv_mgr_get_poc(ps_mv_buf_mgr, ps_pic_buf_ref->i4_abs_poc); } for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx++) { if(NULL == ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf) { ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref; ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref; } } for(r_idx = ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx < MAX_DPB_SIZE; r_idx++) { ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref; ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref; } for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx++) { if(NULL == ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf) { ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref; ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref; } } for(r_idx = ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx < MAX_DPB_SIZE; r_idx++) { ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref; ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref; } } /* Update slice address in the header */ if(!ps_slice_hdr->i1_first_slice_in_pic_flag) { ps_slice_hdr->i2_ctb_x = slice_address % ps_sps->i2_pic_wd_in_ctb; ps_slice_hdr->i2_ctb_y = slice_address / ps_sps->i2_pic_wd_in_ctb; if(!ps_slice_hdr->i1_dependent_slice_flag) { ps_slice_hdr->i2_independent_ctb_x = ps_slice_hdr->i2_ctb_x; ps_slice_hdr->i2_independent_ctb_y = ps_slice_hdr->i2_ctb_y; } } else { ps_slice_hdr->i2_ctb_x = 0; ps_slice_hdr->i2_ctb_y = 0; ps_slice_hdr->i2_independent_ctb_x = 0; ps_slice_hdr->i2_independent_ctb_y = 0; } /* If the first slice in the pic is missing, copy the current slice header to * the first slice's header */ if((!first_slice_in_pic_flag) && (0 == ps_codec->i4_pic_present)) { slice_header_t *ps_slice_hdr_prev = ps_codec->s_parse.ps_slice_hdr_base; ihevcd_copy_slice_hdr(ps_codec, 0, (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))); ps_codec->i4_slice_error = 1; ps_slice_hdr_prev->i2_ctb_x = 0; ps_slice_hdr_prev->i2_ctb_y = 0; ps_codec->s_parse.i4_ctb_x = 0; ps_codec->s_parse.i4_ctb_y = 0; ps_codec->s_parse.i4_cur_slice_idx = 0; if((ps_slice_hdr->i2_ctb_x == 0) && (ps_slice_hdr->i2_ctb_y == 0)) { ps_slice_hdr->i2_ctb_x++; } } { /* If skip B is enabled, * ignore pictures that are non-reference * TODO: (i1_nal_unit_type < NAL_BLA_W_LP) && (i1_nal_unit_type % 2 == 0) only says it is * sub-layer non-reference slice. May need to find a way to detect actual non-reference pictures*/ if((i1_nal_unit_type < NAL_BLA_W_LP) && (i1_nal_unit_type % 2 == 0)) { if(IVD_SKIP_B == ps_codec->e_pic_skip_mode) return IHEVCD_IGNORE_SLICE; } /* If skip PB is enabled, * decode only I slices */ if((IVD_SKIP_PB == ps_codec->e_pic_skip_mode) && (ISLICE != ps_slice_hdr->i1_slice_type)) { return IHEVCD_IGNORE_SLICE; } } return ret; } Commit Message: Check only allocated mv bufs for releasing from reference When checking mv bufs for releasing from reference, unallocated mv bufs were also checked. This issue was fixed by restricting the loop count to allocated number of mv bufs. Bug: 34896906 Bug: 34819017 Change-Id: If832f590b301f414d4cd5206414efc61a70c17cb (cherry picked from commit 23bfe3e06d53ea749073a5d7ceda84239742b2c2) CWE ID:
IHEVCD_ERROR_T ihevcd_parse_slice_header(codec_t *ps_codec, nal_header_t *ps_nal) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; WORD32 value; WORD32 i, j; WORD32 sps_id; pps_t *ps_pps; sps_t *ps_sps; slice_header_t *ps_slice_hdr; WORD32 disable_deblocking_filter_flag; bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm; WORD32 idr_pic_flag; WORD32 pps_id; WORD32 first_slice_in_pic_flag; WORD32 no_output_of_prior_pics_flag = 0; WORD8 i1_nal_unit_type = ps_nal->i1_nal_unit_type; WORD32 num_poc_total_curr = 0; WORD32 slice_address; if(ps_codec->i4_slice_error == 1) return ret; idr_pic_flag = (NAL_IDR_W_LP == i1_nal_unit_type) || (NAL_IDR_N_LP == i1_nal_unit_type); BITS_PARSE("first_slice_in_pic_flag", first_slice_in_pic_flag, ps_bitstrm, 1); if((NAL_BLA_W_LP <= i1_nal_unit_type) && (NAL_RSV_RAP_VCL23 >= i1_nal_unit_type)) { BITS_PARSE("no_output_of_prior_pics_flag", no_output_of_prior_pics_flag, ps_bitstrm, 1); } UEV_PARSE("pic_parameter_set_id", pps_id, ps_bitstrm); pps_id = CLIP3(pps_id, 0, MAX_PPS_CNT - 2); /* Get the current PPS structure */ ps_pps = ps_codec->s_parse.ps_pps_base + pps_id; if(0 == ps_pps->i1_pps_valid) { pps_t *ps_pps_ref = ps_codec->ps_pps_base; while(0 == ps_pps_ref->i1_pps_valid) ps_pps_ref++; if((ps_pps_ref - ps_codec->ps_pps_base >= MAX_PPS_CNT - 1)) return IHEVCD_INVALID_HEADER; ihevcd_copy_pps(ps_codec, pps_id, ps_pps_ref->i1_pps_id); } /* Get SPS id for the current PPS */ sps_id = ps_pps->i1_sps_id; /* Get the current SPS structure */ ps_sps = ps_codec->s_parse.ps_sps_base + sps_id; /* When the current slice is the first in a pic, * check whether the previous frame is complete * If the previous frame is incomplete - * treat the remaining CTBs as skip */ if((0 != ps_codec->u4_pic_cnt || ps_codec->i4_pic_present) && first_slice_in_pic_flag) { if(ps_codec->i4_pic_present) { slice_header_t *ps_slice_hdr_next; ps_codec->i4_slice_error = 1; ps_codec->s_parse.i4_cur_slice_idx--; if(ps_codec->s_parse.i4_cur_slice_idx < 0) ps_codec->s_parse.i4_cur_slice_idx = 0; ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1)); ps_slice_hdr_next->i2_ctb_x = 0; ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb; return ret; } else { ps_codec->i4_slice_error = 0; } } if(first_slice_in_pic_flag) { ps_codec->s_parse.i4_cur_slice_idx = 0; } else { /* If the current slice is not the first slice in the pic, * but the first one to be parsed, set the current slice indx to 1 * Treat the first slice to be missing and copy the current slice header * to the first one */ if(0 == ps_codec->i4_pic_present) ps_codec->s_parse.i4_cur_slice_idx = 1; } ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)); if((ps_pps->i1_dependent_slice_enabled_flag) && (!first_slice_in_pic_flag)) { BITS_PARSE("dependent_slice_flag", value, ps_bitstrm, 1); /* If dependendent slice, copy slice header from previous slice */ if(value && (ps_codec->s_parse.i4_cur_slice_idx > 0)) { ihevcd_copy_slice_hdr(ps_codec, (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)), ((ps_codec->s_parse.i4_cur_slice_idx - 1) & (MAX_SLICE_HDR_CNT - 1))); } ps_slice_hdr->i1_dependent_slice_flag = value; } else { ps_slice_hdr->i1_dependent_slice_flag = 0; } ps_slice_hdr->i1_nal_unit_type = i1_nal_unit_type; ps_slice_hdr->i1_pps_id = pps_id; ps_slice_hdr->i1_first_slice_in_pic_flag = first_slice_in_pic_flag; ps_slice_hdr->i1_no_output_of_prior_pics_flag = 1; if((NAL_BLA_W_LP <= i1_nal_unit_type) && (NAL_RSV_RAP_VCL23 >= i1_nal_unit_type)) { ps_slice_hdr->i1_no_output_of_prior_pics_flag = no_output_of_prior_pics_flag; } ps_slice_hdr->i1_pps_id = pps_id; if(!ps_slice_hdr->i1_first_slice_in_pic_flag) { WORD32 num_bits; /* Use CLZ to compute Ceil( Log2( PicSizeInCtbsY ) ) */ num_bits = 32 - CLZ(ps_sps->i4_pic_size_in_ctb - 1); BITS_PARSE("slice_address", value, ps_bitstrm, num_bits); slice_address = value; /* If slice address is greater than the number of CTBs in a picture, * ignore the slice */ if(value >= ps_sps->i4_pic_size_in_ctb) return IHEVCD_IGNORE_SLICE; } else { slice_address = 0; } if(!ps_slice_hdr->i1_dependent_slice_flag) { ps_slice_hdr->i1_pic_output_flag = 1; ps_slice_hdr->i4_pic_order_cnt_lsb = 0; ps_slice_hdr->i1_num_long_term_sps = 0; ps_slice_hdr->i1_num_long_term_pics = 0; for(i = 0; i < ps_pps->i1_num_extra_slice_header_bits; i++) { BITS_PARSE("slice_reserved_undetermined_flag[ i ]", value, ps_bitstrm, 1); } UEV_PARSE("slice_type", value, ps_bitstrm); ps_slice_hdr->i1_slice_type = value; /* If the picture is IRAP, slice type must be equal to ISLICE */ if((ps_slice_hdr->i1_nal_unit_type >= NAL_BLA_W_LP) && (ps_slice_hdr->i1_nal_unit_type <= NAL_RSV_RAP_VCL23)) ps_slice_hdr->i1_slice_type = ISLICE; if((ps_slice_hdr->i1_slice_type < 0) || (ps_slice_hdr->i1_slice_type > 2)) return IHEVCD_IGNORE_SLICE; if(ps_pps->i1_output_flag_present_flag) { BITS_PARSE("pic_output_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_pic_output_flag = value; } ps_slice_hdr->i1_colour_plane_id = 0; if(1 == ps_sps->i1_separate_colour_plane_flag) { BITS_PARSE("colour_plane_id", value, ps_bitstrm, 2); ps_slice_hdr->i1_colour_plane_id = value; } ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = 0; if(!idr_pic_flag) { WORD32 st_rps_idx; WORD32 num_neg_pics; WORD32 num_pos_pics; WORD8 *pi1_used; BITS_PARSE("pic_order_cnt_lsb", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb); ps_slice_hdr->i4_pic_order_cnt_lsb = value; BITS_PARSE("short_term_ref_pic_set_sps_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag = value; if(1 == ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag) { WORD32 numbits; ps_slice_hdr->i1_short_term_ref_pic_set_idx = 0; if(ps_sps->i1_num_short_term_ref_pic_sets > 1) { numbits = 32 - CLZ(ps_sps->i1_num_short_term_ref_pic_sets - 1); BITS_PARSE("short_term_ref_pic_set_idx", value, ps_bitstrm, numbits); ps_slice_hdr->i1_short_term_ref_pic_set_idx = value; } st_rps_idx = ps_slice_hdr->i1_short_term_ref_pic_set_idx; num_neg_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_neg_pics; num_pos_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_pos_pics; pi1_used = ps_sps->as_stref_picset[st_rps_idx].ai1_used; } else { ihevcd_short_term_ref_pic_set(ps_bitstrm, &ps_sps->as_stref_picset[0], ps_sps->i1_num_short_term_ref_pic_sets, ps_sps->i1_num_short_term_ref_pic_sets, &ps_slice_hdr->s_stref_picset); st_rps_idx = ps_sps->i1_num_short_term_ref_pic_sets; num_neg_pics = ps_slice_hdr->s_stref_picset.i1_num_neg_pics; num_pos_pics = ps_slice_hdr->s_stref_picset.i1_num_pos_pics; pi1_used = ps_slice_hdr->s_stref_picset.ai1_used; } if(ps_sps->i1_long_term_ref_pics_present_flag) { if(ps_sps->i1_num_long_term_ref_pics_sps > 0) { UEV_PARSE("num_long_term_sps", value, ps_bitstrm); ps_slice_hdr->i1_num_long_term_sps = value; ps_slice_hdr->i1_num_long_term_sps = CLIP3(ps_slice_hdr->i1_num_long_term_sps, 0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics); } UEV_PARSE("num_long_term_pics", value, ps_bitstrm); ps_slice_hdr->i1_num_long_term_pics = value; ps_slice_hdr->i1_num_long_term_pics = CLIP3(ps_slice_hdr->i1_num_long_term_pics, 0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics - ps_slice_hdr->i1_num_long_term_sps); for(i = 0; i < (ps_slice_hdr->i1_num_long_term_sps + ps_slice_hdr->i1_num_long_term_pics); i++) { if(i < ps_slice_hdr->i1_num_long_term_sps) { /* Use CLZ to compute Ceil( Log2( num_long_term_ref_pics_sps ) ) */ WORD32 num_bits = 32 - CLZ(ps_sps->i1_num_long_term_ref_pics_sps); BITS_PARSE("lt_idx_sps[ i ]", value, ps_bitstrm, num_bits); ps_slice_hdr->ai4_poc_lsb_lt[i] = ps_sps->ai1_lt_ref_pic_poc_lsb_sps[value]; ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = ps_sps->ai1_used_by_curr_pic_lt_sps_flag[value]; } else { BITS_PARSE("poc_lsb_lt[ i ]", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb); ps_slice_hdr->ai4_poc_lsb_lt[i] = value; BITS_PARSE("used_by_curr_pic_lt_flag[ i ]", value, ps_bitstrm, 1); ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = value; } BITS_PARSE("delta_poc_msb_present_flag[ i ]", value, ps_bitstrm, 1); ps_slice_hdr->ai1_delta_poc_msb_present_flag[i] = value; ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = 0; if(ps_slice_hdr->ai1_delta_poc_msb_present_flag[i]) { UEV_PARSE("delata_poc_msb_cycle_lt[ i ]", value, ps_bitstrm); ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = value; } if((i != 0) && (i != ps_slice_hdr->i1_num_long_term_sps)) { ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] += ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i - 1]; } } } for(i = 0; i < num_neg_pics + num_pos_pics; i++) { if(pi1_used[i]) { num_poc_total_curr++; } } for(i = 0; i < ps_slice_hdr->i1_num_long_term_sps + ps_slice_hdr->i1_num_long_term_pics; i++) { if(ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i]) { num_poc_total_curr++; } } if(ps_sps->i1_sps_temporal_mvp_enable_flag) { BITS_PARSE("enable_temporal_mvp_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = value; } } ps_slice_hdr->i1_slice_sao_luma_flag = 0; ps_slice_hdr->i1_slice_sao_chroma_flag = 0; if(ps_sps->i1_sample_adaptive_offset_enabled_flag) { BITS_PARSE("slice_sao_luma_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_sao_luma_flag = value; BITS_PARSE("slice_sao_chroma_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_sao_chroma_flag = value; } ps_slice_hdr->i1_max_num_merge_cand = 1; ps_slice_hdr->i1_cabac_init_flag = 0; ps_slice_hdr->i1_num_ref_idx_l0_active = 0; ps_slice_hdr->i1_num_ref_idx_l1_active = 0; ps_slice_hdr->i1_slice_cb_qp_offset = 0; ps_slice_hdr->i1_slice_cr_qp_offset = 0; if((PSLICE == ps_slice_hdr->i1_slice_type) || (BSLICE == ps_slice_hdr->i1_slice_type)) { BITS_PARSE("num_ref_idx_active_override_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_num_ref_idx_active_override_flag = value; if(ps_slice_hdr->i1_num_ref_idx_active_override_flag) { UEV_PARSE("num_ref_idx_l0_active_minus1", value, ps_bitstrm); ps_slice_hdr->i1_num_ref_idx_l0_active = value + 1; if(BSLICE == ps_slice_hdr->i1_slice_type) { UEV_PARSE("num_ref_idx_l1_active_minus1", value, ps_bitstrm); ps_slice_hdr->i1_num_ref_idx_l1_active = value + 1; } } else { ps_slice_hdr->i1_num_ref_idx_l0_active = ps_pps->i1_num_ref_idx_l0_default_active; if(BSLICE == ps_slice_hdr->i1_slice_type) { ps_slice_hdr->i1_num_ref_idx_l1_active = ps_pps->i1_num_ref_idx_l1_default_active; } } ps_slice_hdr->i1_num_ref_idx_l0_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l0_active, 0, MAX_DPB_SIZE - 1); ps_slice_hdr->i1_num_ref_idx_l1_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l1_active, 0, MAX_DPB_SIZE - 1); if(0 == num_poc_total_curr) return IHEVCD_IGNORE_SLICE; if((ps_pps->i1_lists_modification_present_flag) && (num_poc_total_curr > 1)) { ihevcd_ref_pic_list_modification(ps_bitstrm, ps_slice_hdr, num_poc_total_curr); } else { ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l0 = 0; ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l1 = 0; } if(BSLICE == ps_slice_hdr->i1_slice_type) { BITS_PARSE("mvd_l1_zero_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_mvd_l1_zero_flag = value; } ps_slice_hdr->i1_cabac_init_flag = 0; if(ps_pps->i1_cabac_init_present_flag) { BITS_PARSE("cabac_init_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_cabac_init_flag = value; } ps_slice_hdr->i1_collocated_from_l0_flag = 1; ps_slice_hdr->i1_collocated_ref_idx = 0; if(ps_slice_hdr->i1_slice_temporal_mvp_enable_flag) { if(BSLICE == ps_slice_hdr->i1_slice_type) { BITS_PARSE("collocated_from_l0_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_collocated_from_l0_flag = value; } if((ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l0_active > 1)) || (!ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l1_active > 1))) { UEV_PARSE("collocated_ref_idx", value, ps_bitstrm); ps_slice_hdr->i1_collocated_ref_idx = value; } } ps_slice_hdr->i1_collocated_ref_idx = CLIP3(ps_slice_hdr->i1_collocated_ref_idx, 0, MAX_DPB_SIZE - 1); if((ps_pps->i1_weighted_pred_flag && (PSLICE == ps_slice_hdr->i1_slice_type)) || (ps_pps->i1_weighted_bipred_flag && (BSLICE == ps_slice_hdr->i1_slice_type))) { ihevcd_parse_pred_wt_ofst(ps_bitstrm, ps_sps, ps_pps, ps_slice_hdr); } UEV_PARSE("five_minus_max_num_merge_cand", value, ps_bitstrm); ps_slice_hdr->i1_max_num_merge_cand = 5 - value; } ps_slice_hdr->i1_max_num_merge_cand = CLIP3(ps_slice_hdr->i1_max_num_merge_cand, 1, 5); SEV_PARSE("slice_qp_delta", value, ps_bitstrm); ps_slice_hdr->i1_slice_qp_delta = value; if(ps_pps->i1_pic_slice_level_chroma_qp_offsets_present_flag) { SEV_PARSE("slice_cb_qp_offset", value, ps_bitstrm); ps_slice_hdr->i1_slice_cb_qp_offset = value; SEV_PARSE("slice_cr_qp_offset", value, ps_bitstrm); ps_slice_hdr->i1_slice_cr_qp_offset = value; } ps_slice_hdr->i1_deblocking_filter_override_flag = 0; ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag; ps_slice_hdr->i1_beta_offset_div2 = ps_pps->i1_beta_offset_div2; ps_slice_hdr->i1_tc_offset_div2 = ps_pps->i1_tc_offset_div2; disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag; if(ps_pps->i1_deblocking_filter_control_present_flag) { if(ps_pps->i1_deblocking_filter_override_enabled_flag) { BITS_PARSE("deblocking_filter_override_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_deblocking_filter_override_flag = value; } if(ps_slice_hdr->i1_deblocking_filter_override_flag) { BITS_PARSE("slice_disable_deblocking_filter_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = value; disable_deblocking_filter_flag = ps_slice_hdr->i1_slice_disable_deblocking_filter_flag; if(!ps_slice_hdr->i1_slice_disable_deblocking_filter_flag) { SEV_PARSE("beta_offset_div2", value, ps_bitstrm); ps_slice_hdr->i1_beta_offset_div2 = value; SEV_PARSE("tc_offset_div2", value, ps_bitstrm); ps_slice_hdr->i1_tc_offset_div2 = value; } } } ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = ps_pps->i1_loop_filter_across_slices_enabled_flag; if(ps_pps->i1_loop_filter_across_slices_enabled_flag && (ps_slice_hdr->i1_slice_sao_luma_flag || ps_slice_hdr->i1_slice_sao_chroma_flag || !disable_deblocking_filter_flag)) { BITS_PARSE("slice_loop_filter_across_slices_enabled_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = value; } } /* Check sanity of slice */ if((!first_slice_in_pic_flag) && (ps_codec->i4_pic_present)) { slice_header_t *ps_slice_hdr_base = ps_codec->ps_slice_hdr_base; /* According to the standard, the above conditions must be satisfied - But for error resilience, * only the following conditions are checked */ if((ps_slice_hdr_base->i1_pps_id != ps_slice_hdr->i1_pps_id) || (ps_slice_hdr_base->i4_pic_order_cnt_lsb != ps_slice_hdr->i4_pic_order_cnt_lsb)) { return IHEVCD_IGNORE_SLICE; } } if(0 == ps_codec->i4_pic_present) { ps_slice_hdr->i4_abs_pic_order_cnt = ihevcd_calc_poc(ps_codec, ps_nal, ps_sps->i1_log2_max_pic_order_cnt_lsb, ps_slice_hdr->i4_pic_order_cnt_lsb); } else { ps_slice_hdr->i4_abs_pic_order_cnt = ps_codec->s_parse.i4_abs_pic_order_cnt; } if(!first_slice_in_pic_flag) { /* Check if the current slice belongs to the same pic (Pic being parsed) */ if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt) { /* If the Next CTB's index is less than the slice address, * the previous slice is incomplete. * Indicate slice error, and treat the remaining CTBs as skip */ if(slice_address > ps_codec->s_parse.i4_next_ctb_indx) { if(ps_codec->i4_pic_present) { ps_codec->i4_slice_error = 1; ps_codec->s_parse.i4_cur_slice_idx--; if(ps_codec->s_parse.i4_cur_slice_idx < 0) ps_codec->s_parse.i4_cur_slice_idx = 0; return ret; } else { return IHEVCD_IGNORE_SLICE; } } /* If the slice address is less than the next CTB's index, * extra CTBs have been decoded in the previous slice. * Ignore the current slice. Treat it as incomplete */ else if(slice_address < ps_codec->s_parse.i4_next_ctb_indx) { return IHEVCD_IGNORE_SLICE; } else { ps_codec->i4_slice_error = 0; } } /* The current slice does not belong to the pic that is being parsed */ else { /* The previous pic is incomplete. * Treat the remaining CTBs as skip */ if(ps_codec->i4_pic_present) { slice_header_t *ps_slice_hdr_next; ps_codec->i4_slice_error = 1; ps_codec->s_parse.i4_cur_slice_idx--; if(ps_codec->s_parse.i4_cur_slice_idx < 0) ps_codec->s_parse.i4_cur_slice_idx = 0; ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1)); ps_slice_hdr_next->i2_ctb_x = 0; ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb; return ret; } /* If the previous pic is complete, * return if the current slice is dependant * otherwise, update the parse context's POC */ else { if(ps_slice_hdr->i1_dependent_slice_flag) return IHEVCD_IGNORE_SLICE; ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt; } } } /* If the slice is the first slice in the pic, update the parse context's POC */ else { /* If the first slice is repeated, ignore the second occurrence * If any other slice is repeated, the CTB addr will be greater than the slice addr, * and hence the second occurrence is ignored */ if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt) return IHEVCD_IGNORE_SLICE; ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt; } ps_slice_hdr->i4_num_entry_point_offsets = 0; if((ps_pps->i1_tiles_enabled_flag) || (ps_pps->i1_entropy_coding_sync_enabled_flag)) { UEV_PARSE("num_entry_point_offsets", value, ps_bitstrm); ps_slice_hdr->i4_num_entry_point_offsets = value; { WORD32 max_num_entry_point_offsets; if((ps_pps->i1_tiles_enabled_flag) && (ps_pps->i1_entropy_coding_sync_enabled_flag)) { max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * (ps_sps->i2_pic_ht_in_ctb - 1); } else if(ps_pps->i1_tiles_enabled_flag) { max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * ps_pps->i1_num_tile_rows; } else { max_num_entry_point_offsets = (ps_sps->i2_pic_ht_in_ctb - 1); } ps_slice_hdr->i4_num_entry_point_offsets = CLIP3(ps_slice_hdr->i4_num_entry_point_offsets, 0, max_num_entry_point_offsets); } if(ps_slice_hdr->i4_num_entry_point_offsets > 0) { UEV_PARSE("offset_len_minus1", value, ps_bitstrm); ps_slice_hdr->i1_offset_len = value + 1; for(i = 0; i < ps_slice_hdr->i4_num_entry_point_offsets; i++) { BITS_PARSE("entry_point_offset", value, ps_bitstrm, ps_slice_hdr->i1_offset_len); /* TODO: pu4_entry_point_offset needs to be initialized */ } } } if(ps_pps->i1_slice_header_extension_present_flag) { UEV_PARSE("slice_header_extension_length", value, ps_bitstrm); ps_slice_hdr->i2_slice_header_extension_length = value; for(i = 0; i < ps_slice_hdr->i2_slice_header_extension_length; i++) { BITS_PARSE("slice_header_extension_data_byte", value, ps_bitstrm, 8); } } ihevcd_bits_flush_to_byte_boundary(ps_bitstrm); { dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr; WORD32 r_idx; if((NAL_IDR_W_LP == ps_slice_hdr->i1_nal_unit_type) || (NAL_IDR_N_LP == ps_slice_hdr->i1_nal_unit_type) || (NAL_BLA_N_LP == ps_slice_hdr->i1_nal_unit_type) || (NAL_BLA_W_DLP == ps_slice_hdr->i1_nal_unit_type) || (NAL_BLA_W_LP == ps_slice_hdr->i1_nal_unit_type) || (0 == ps_codec->u4_pic_cnt)) { for(i = 0; i < MAX_DPB_BUFS; i++) { if(ps_dpb_mgr->as_dpb_info[i].ps_pic_buf) { pic_buf_t *ps_pic_buf = ps_dpb_mgr->as_dpb_info[i].ps_pic_buf; mv_buf_t *ps_mv_buf; /* Long term index is set to MAX_DPB_BUFS to ensure it is not added as LT */ ihevc_dpb_mgr_del_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, (buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_pic_buf->i4_abs_poc); /* Find buffer id of the MV bank corresponding to the buffer being freed (Buffer with POC of u4_abs_poc) */ ps_mv_buf = (mv_buf_t *)ps_codec->ps_mv_buf; for(j = 0; j < ps_codec->i4_max_dpb_size; j++) { if(ps_mv_buf && ps_mv_buf->i4_abs_poc == ps_pic_buf->i4_abs_poc) { ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, j, BUF_MGR_REF); break; } ps_mv_buf++; } } } /* Initialize the reference lists to NULL * This is done to take care of the cases where the first pic is not IDR * but the reference list is not created for the first pic because * pic count is zero leaving the reference list uninitialised */ for(r_idx = 0; r_idx < MAX_DPB_SIZE; r_idx++) { ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = NULL; ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = NULL; ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = NULL; ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = NULL; } } else { ret = ihevcd_ref_list(ps_codec, ps_pps, ps_sps, ps_slice_hdr); if ((WORD32)IHEVCD_SUCCESS != ret) { return ret; } } } /* Fill the remaining entries of the reference lists with the nearest POC * This is done to handle cases where there is a corruption in the reference index */ if(ps_codec->i4_pic_present) { pic_buf_t *ps_pic_buf_ref; mv_buf_t *ps_mv_buf_ref; WORD32 r_idx; dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr; buf_mgr_t *ps_mv_buf_mgr = (buf_mgr_t *)ps_codec->pv_mv_buf_mgr; ps_pic_buf_ref = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ps_slice_hdr->i4_abs_pic_order_cnt); if(NULL == ps_pic_buf_ref) { ps_pic_buf_ref = ps_codec->as_process[0].ps_cur_pic; ps_mv_buf_ref = ps_codec->s_parse.ps_cur_mv_buf; } else { ps_mv_buf_ref = ihevcd_mv_mgr_get_poc(ps_mv_buf_mgr, ps_pic_buf_ref->i4_abs_poc); } for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx++) { if(NULL == ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf) { ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref; ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref; } } for(r_idx = ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx < MAX_DPB_SIZE; r_idx++) { ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref; ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref; } for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx++) { if(NULL == ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf) { ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref; ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref; } } for(r_idx = ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx < MAX_DPB_SIZE; r_idx++) { ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref; ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref; } } /* Update slice address in the header */ if(!ps_slice_hdr->i1_first_slice_in_pic_flag) { ps_slice_hdr->i2_ctb_x = slice_address % ps_sps->i2_pic_wd_in_ctb; ps_slice_hdr->i2_ctb_y = slice_address / ps_sps->i2_pic_wd_in_ctb; if(!ps_slice_hdr->i1_dependent_slice_flag) { ps_slice_hdr->i2_independent_ctb_x = ps_slice_hdr->i2_ctb_x; ps_slice_hdr->i2_independent_ctb_y = ps_slice_hdr->i2_ctb_y; } } else { ps_slice_hdr->i2_ctb_x = 0; ps_slice_hdr->i2_ctb_y = 0; ps_slice_hdr->i2_independent_ctb_x = 0; ps_slice_hdr->i2_independent_ctb_y = 0; } /* If the first slice in the pic is missing, copy the current slice header to * the first slice's header */ if((!first_slice_in_pic_flag) && (0 == ps_codec->i4_pic_present)) { slice_header_t *ps_slice_hdr_prev = ps_codec->s_parse.ps_slice_hdr_base; ihevcd_copy_slice_hdr(ps_codec, 0, (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))); ps_codec->i4_slice_error = 1; ps_slice_hdr_prev->i2_ctb_x = 0; ps_slice_hdr_prev->i2_ctb_y = 0; ps_codec->s_parse.i4_ctb_x = 0; ps_codec->s_parse.i4_ctb_y = 0; ps_codec->s_parse.i4_cur_slice_idx = 0; if((ps_slice_hdr->i2_ctb_x == 0) && (ps_slice_hdr->i2_ctb_y == 0)) { ps_slice_hdr->i2_ctb_x++; } } { /* If skip B is enabled, * ignore pictures that are non-reference * TODO: (i1_nal_unit_type < NAL_BLA_W_LP) && (i1_nal_unit_type % 2 == 0) only says it is * sub-layer non-reference slice. May need to find a way to detect actual non-reference pictures*/ if((i1_nal_unit_type < NAL_BLA_W_LP) && (i1_nal_unit_type % 2 == 0)) { if(IVD_SKIP_B == ps_codec->e_pic_skip_mode) return IHEVCD_IGNORE_SLICE; } /* If skip PB is enabled, * decode only I slices */ if((IVD_SKIP_PB == ps_codec->e_pic_skip_mode) && (ISLICE != ps_slice_hdr->i1_slice_type)) { return IHEVCD_IGNORE_SLICE; } } return ret; }
173,997
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothDeviceChromeOS::DisplayPasskey( const dbus::ObjectPath& device_path, uint32 passkey, uint16 entered) { DCHECK(agent_.get()); DCHECK(device_path == object_path_); VLOG(1) << object_path_.value() << ": DisplayPasskey: " << passkey << " (" << entered << " entered)"; if (entered == 0) UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_DISPLAY_PASSKEY, UMA_PAIRING_METHOD_COUNT); DCHECK(pairing_delegate_); if (entered == 0) pairing_delegate_->DisplayPasskey(this, passkey); pairing_delegate_->KeysEntered(this, entered); pairing_delegate_used_ = true; } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::DisplayPasskey(
171,222
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; unsigned int copied, rlen; struct sk_buff *skb, *cskb; int err = 0; pr_debug("%p %zu\n", sk, len); lock_sock(sk); if (sk->sk_state == LLCP_CLOSED && skb_queue_empty(&sk->sk_receive_queue)) { release_sock(sk); return 0; } release_sock(sk); if (flags & (MSG_OOB)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { pr_err("Recv datagram failed state %d %d %d", sk->sk_state, err, sock_error(sk)); if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } rlen = skb->len; /* real length of skb */ copied = min_t(unsigned int, rlen, len); cskb = skb; if (skb_copy_datagram_iovec(cskb, 0, msg->msg_iov, copied)) { if (!(flags & MSG_PEEK)) skb_queue_head(&sk->sk_receive_queue, skb); return -EFAULT; } sock_recv_timestamp(msg, sk, skb); if (sk->sk_type == SOCK_DGRAM && msg->msg_name) { struct nfc_llcp_ui_cb *ui_cb = nfc_llcp_ui_skb_cb(skb); struct sockaddr_nfc_llcp *sockaddr = (struct sockaddr_nfc_llcp *) msg->msg_name; msg->msg_namelen = sizeof(struct sockaddr_nfc_llcp); pr_debug("Datagram socket %d %d\n", ui_cb->dsap, ui_cb->ssap); sockaddr->sa_family = AF_NFC; sockaddr->nfc_protocol = NFC_PROTO_NFC_DEP; sockaddr->dsap = ui_cb->dsap; sockaddr->ssap = ui_cb->ssap; } /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { /* SOCK_STREAM: re-queue skb if it contains unreceived data */ if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { skb_pull(skb, copied); if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); goto done; } } kfree_skb(skb); } /* XXX Queue backlogged skbs */ done: /* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */ if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC)) copied = rlen; return copied; } Commit Message: NFC: llcp: fix info leaks via msg_name in llcp_sock_recvmsg() The code in llcp_sock_recvmsg() does not initialize all the members of struct sockaddr_nfc_llcp when filling the sockaddr info. Nor does it initialize the padding bytes of the structure inserted by the compiler for alignment. Also, if the socket is in state LLCP_CLOSED or is shutting down during receive the msg_namelen member is not updated to 0 while otherwise returning with 0, i.e. "success". The msg_namelen update is also missing for stream and seqpacket sockets which don't fill the sockaddr info. Both issues lead to the fact that the code will leak uninitialized kernel stack bytes in net/socket.c. Fix the first issue by initializing the memory used for sockaddr info with memset(0). Fix the second one by setting msg_namelen to 0 early. It will be updated later if we're going to fill the msg_name member. Cc: Lauro Ramos Venancio <[email protected]> Cc: Aloisio Almeida Jr <[email protected]> Cc: Samuel Ortiz <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; unsigned int copied, rlen; struct sk_buff *skb, *cskb; int err = 0; pr_debug("%p %zu\n", sk, len); msg->msg_namelen = 0; lock_sock(sk); if (sk->sk_state == LLCP_CLOSED && skb_queue_empty(&sk->sk_receive_queue)) { release_sock(sk); return 0; } release_sock(sk); if (flags & (MSG_OOB)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { pr_err("Recv datagram failed state %d %d %d", sk->sk_state, err, sock_error(sk)); if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } rlen = skb->len; /* real length of skb */ copied = min_t(unsigned int, rlen, len); cskb = skb; if (skb_copy_datagram_iovec(cskb, 0, msg->msg_iov, copied)) { if (!(flags & MSG_PEEK)) skb_queue_head(&sk->sk_receive_queue, skb); return -EFAULT; } sock_recv_timestamp(msg, sk, skb); if (sk->sk_type == SOCK_DGRAM && msg->msg_name) { struct nfc_llcp_ui_cb *ui_cb = nfc_llcp_ui_skb_cb(skb); struct sockaddr_nfc_llcp *sockaddr = (struct sockaddr_nfc_llcp *) msg->msg_name; msg->msg_namelen = sizeof(struct sockaddr_nfc_llcp); pr_debug("Datagram socket %d %d\n", ui_cb->dsap, ui_cb->ssap); memset(sockaddr, 0, sizeof(*sockaddr)); sockaddr->sa_family = AF_NFC; sockaddr->nfc_protocol = NFC_PROTO_NFC_DEP; sockaddr->dsap = ui_cb->dsap; sockaddr->ssap = ui_cb->ssap; } /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { /* SOCK_STREAM: re-queue skb if it contains unreceived data */ if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { skb_pull(skb, copied); if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); goto done; } } kfree_skb(skb); } /* XXX Queue backlogged skbs */ done: /* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */ if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC)) copied = rlen; return copied; }
166,034
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int rds_ib_xmit(struct rds_connection *conn, struct rds_message *rm, unsigned int hdr_off, unsigned int sg, unsigned int off) { struct rds_ib_connection *ic = conn->c_transport_data; struct ib_device *dev = ic->i_cm_id->device; struct rds_ib_send_work *send = NULL; struct rds_ib_send_work *first; struct rds_ib_send_work *prev; struct ib_send_wr *failed_wr; struct scatterlist *scat; u32 pos; u32 i; u32 work_alloc; u32 credit_alloc = 0; u32 posted; u32 adv_credits = 0; int send_flags = 0; int bytes_sent = 0; int ret; int flow_controlled = 0; int nr_sig = 0; BUG_ON(off % RDS_FRAG_SIZE); BUG_ON(hdr_off != 0 && hdr_off != sizeof(struct rds_header)); /* Do not send cong updates to IB loopback */ if (conn->c_loopback && rm->m_inc.i_hdr.h_flags & RDS_FLAG_CONG_BITMAP) { rds_cong_map_updated(conn->c_fcong, ~(u64) 0); return sizeof(struct rds_header) + RDS_CONG_MAP_BYTES; } /* FIXME we may overallocate here */ if (be32_to_cpu(rm->m_inc.i_hdr.h_len) == 0) i = 1; else i = ceil(be32_to_cpu(rm->m_inc.i_hdr.h_len), RDS_FRAG_SIZE); work_alloc = rds_ib_ring_alloc(&ic->i_send_ring, i, &pos); if (work_alloc == 0) { set_bit(RDS_LL_SEND_FULL, &conn->c_flags); rds_ib_stats_inc(s_ib_tx_ring_full); ret = -ENOMEM; goto out; } if (ic->i_flowctl) { credit_alloc = rds_ib_send_grab_credits(ic, work_alloc, &posted, 0, RDS_MAX_ADV_CREDIT); adv_credits += posted; if (credit_alloc < work_alloc) { rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc - credit_alloc); work_alloc = credit_alloc; flow_controlled = 1; } if (work_alloc == 0) { set_bit(RDS_LL_SEND_FULL, &conn->c_flags); rds_ib_stats_inc(s_ib_tx_throttle); ret = -ENOMEM; goto out; } } /* map the message the first time we see it */ if (!ic->i_data_op) { if (rm->data.op_nents) { rm->data.op_count = ib_dma_map_sg(dev, rm->data.op_sg, rm->data.op_nents, DMA_TO_DEVICE); rdsdebug("ic %p mapping rm %p: %d\n", ic, rm, rm->data.op_count); if (rm->data.op_count == 0) { rds_ib_stats_inc(s_ib_tx_sg_mapping_failure); rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc); ret = -ENOMEM; /* XXX ? */ goto out; } } else { rm->data.op_count = 0; } rds_message_addref(rm); ic->i_data_op = &rm->data; /* Finalize the header */ if (test_bit(RDS_MSG_ACK_REQUIRED, &rm->m_flags)) rm->m_inc.i_hdr.h_flags |= RDS_FLAG_ACK_REQUIRED; if (test_bit(RDS_MSG_RETRANSMITTED, &rm->m_flags)) rm->m_inc.i_hdr.h_flags |= RDS_FLAG_RETRANSMITTED; /* If it has a RDMA op, tell the peer we did it. This is * used by the peer to release use-once RDMA MRs. */ if (rm->rdma.op_active) { struct rds_ext_header_rdma ext_hdr; ext_hdr.h_rdma_rkey = cpu_to_be32(rm->rdma.op_rkey); rds_message_add_extension(&rm->m_inc.i_hdr, RDS_EXTHDR_RDMA, &ext_hdr, sizeof(ext_hdr)); } if (rm->m_rdma_cookie) { rds_message_add_rdma_dest_extension(&rm->m_inc.i_hdr, rds_rdma_cookie_key(rm->m_rdma_cookie), rds_rdma_cookie_offset(rm->m_rdma_cookie)); } /* Note - rds_ib_piggyb_ack clears the ACK_REQUIRED bit, so * we should not do this unless we have a chance of at least * sticking the header into the send ring. Which is why we * should call rds_ib_ring_alloc first. */ rm->m_inc.i_hdr.h_ack = cpu_to_be64(rds_ib_piggyb_ack(ic)); rds_message_make_checksum(&rm->m_inc.i_hdr); /* * Update adv_credits since we reset the ACK_REQUIRED bit. */ if (ic->i_flowctl) { rds_ib_send_grab_credits(ic, 0, &posted, 1, RDS_MAX_ADV_CREDIT - adv_credits); adv_credits += posted; BUG_ON(adv_credits > 255); } } /* Sometimes you want to put a fence between an RDMA * READ and the following SEND. * We could either do this all the time * or when requested by the user. Right now, we let * the application choose. */ if (rm->rdma.op_active && rm->rdma.op_fence) send_flags = IB_SEND_FENCE; /* Each frag gets a header. Msgs may be 0 bytes */ send = &ic->i_sends[pos]; first = send; prev = NULL; scat = &ic->i_data_op->op_sg[sg]; i = 0; do { unsigned int len = 0; /* Set up the header */ send->s_wr.send_flags = send_flags; send->s_wr.opcode = IB_WR_SEND; send->s_wr.num_sge = 1; send->s_wr.next = NULL; send->s_queued = jiffies; send->s_op = NULL; send->s_sge[0].addr = ic->i_send_hdrs_dma + (pos * sizeof(struct rds_header)); send->s_sge[0].length = sizeof(struct rds_header); memcpy(&ic->i_send_hdrs[pos], &rm->m_inc.i_hdr, sizeof(struct rds_header)); /* Set up the data, if present */ if (i < work_alloc && scat != &rm->data.op_sg[rm->data.op_count]) { len = min(RDS_FRAG_SIZE, ib_sg_dma_len(dev, scat) - off); send->s_wr.num_sge = 2; send->s_sge[1].addr = ib_sg_dma_address(dev, scat) + off; send->s_sge[1].length = len; bytes_sent += len; off += len; if (off == ib_sg_dma_len(dev, scat)) { scat++; off = 0; } } rds_ib_set_wr_signal_state(ic, send, 0); /* * Always signal the last one if we're stopping due to flow control. */ if (ic->i_flowctl && flow_controlled && i == (work_alloc-1)) send->s_wr.send_flags |= IB_SEND_SIGNALED | IB_SEND_SOLICITED; if (send->s_wr.send_flags & IB_SEND_SIGNALED) nr_sig++; rdsdebug("send %p wr %p num_sge %u next %p\n", send, &send->s_wr, send->s_wr.num_sge, send->s_wr.next); if (ic->i_flowctl && adv_credits) { struct rds_header *hdr = &ic->i_send_hdrs[pos]; /* add credit and redo the header checksum */ hdr->h_credit = adv_credits; rds_message_make_checksum(hdr); adv_credits = 0; rds_ib_stats_inc(s_ib_tx_credit_updates); } if (prev) prev->s_wr.next = &send->s_wr; prev = send; pos = (pos + 1) % ic->i_send_ring.w_nr; send = &ic->i_sends[pos]; i++; } while (i < work_alloc && scat != &rm->data.op_sg[rm->data.op_count]); /* Account the RDS header in the number of bytes we sent, but just once. * The caller has no concept of fragmentation. */ if (hdr_off == 0) bytes_sent += sizeof(struct rds_header); /* if we finished the message then send completion owns it */ if (scat == &rm->data.op_sg[rm->data.op_count]) { prev->s_op = ic->i_data_op; prev->s_wr.send_flags |= IB_SEND_SOLICITED; ic->i_data_op = NULL; } /* Put back wrs & credits we didn't use */ if (i < work_alloc) { rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc - i); work_alloc = i; } if (ic->i_flowctl && i < credit_alloc) rds_ib_send_add_credits(conn, credit_alloc - i); if (nr_sig) atomic_add(nr_sig, &ic->i_signaled_sends); /* XXX need to worry about failed_wr and partial sends. */ failed_wr = &first->s_wr; ret = ib_post_send(ic->i_cm_id->qp, &first->s_wr, &failed_wr); rdsdebug("ic %p first %p (wr %p) ret %d wr %p\n", ic, first, &first->s_wr, ret, failed_wr); BUG_ON(failed_wr != &first->s_wr); if (ret) { printk(KERN_WARNING "RDS/IB: ib_post_send to %pI4 " "returned %d\n", &conn->c_faddr, ret); rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc); rds_ib_sub_signaled(ic, nr_sig); if (prev->s_op) { ic->i_data_op = prev->s_op; prev->s_op = NULL; } rds_ib_conn_error(ic->conn, "ib_post_send failed\n"); goto out; } ret = bytes_sent; out: BUG_ON(adv_credits); return ret; } Commit Message: rds: prevent BUG_ON triggering on congestion map updates Recently had this bug halt reported to me: kernel BUG at net/rds/send.c:329! Oops: Exception in kernel mode, sig: 5 [#1] SMP NR_CPUS=1024 NUMA pSeries Modules linked in: rds sunrpc ipv6 dm_mirror dm_region_hash dm_log ibmveth sg ext4 jbd2 mbcache sd_mod crc_t10dif ibmvscsic scsi_transport_srp scsi_tgt dm_mod [last unloaded: scsi_wait_scan] NIP: d000000003ca68f4 LR: d000000003ca67fc CTR: d000000003ca8770 REGS: c000000175cab980 TRAP: 0700 Not tainted (2.6.32-118.el6.ppc64) MSR: 8000000000029032 <EE,ME,CE,IR,DR> CR: 44000022 XER: 00000000 TASK = c00000017586ec90[1896] 'krdsd' THREAD: c000000175ca8000 CPU: 0 GPR00: 0000000000000150 c000000175cabc00 d000000003cb7340 0000000000002030 GPR04: ffffffffffffffff 0000000000000030 0000000000000000 0000000000000030 GPR08: 0000000000000001 0000000000000001 c0000001756b1e30 0000000000010000 GPR12: d000000003caac90 c000000000fa2500 c0000001742b2858 c0000001742b2a00 GPR16: c0000001742b2a08 c0000001742b2820 0000000000000001 0000000000000001 GPR20: 0000000000000040 c0000001742b2814 c000000175cabc70 0800000000000000 GPR24: 0000000000000004 0200000000000000 0000000000000000 c0000001742b2860 GPR28: 0000000000000000 c0000001756b1c80 d000000003cb68e8 c0000001742b27b8 NIP [d000000003ca68f4] .rds_send_xmit+0x4c4/0x8a0 [rds] LR [d000000003ca67fc] .rds_send_xmit+0x3cc/0x8a0 [rds] Call Trace: [c000000175cabc00] [d000000003ca67fc] .rds_send_xmit+0x3cc/0x8a0 [rds] (unreliable) [c000000175cabd30] [d000000003ca7e64] .rds_send_worker+0x54/0x100 [rds] [c000000175cabdb0] [c0000000000b475c] .worker_thread+0x1dc/0x3c0 [c000000175cabed0] [c0000000000baa9c] .kthread+0xbc/0xd0 [c000000175cabf90] [c000000000032114] .kernel_thread+0x54/0x70 Instruction dump: 4bfffd50 60000000 60000000 39080001 935f004c f91f0040 41820024 813d017c 7d094a78 7d290074 7929d182 394a0020 <0b090000> 40e2ff68 4bffffa4 39200000 Kernel panic - not syncing: Fatal exception Call Trace: [c000000175cab560] [c000000000012e04] .show_stack+0x74/0x1c0 (unreliable) [c000000175cab610] [c0000000005a365c] .panic+0x80/0x1b4 [c000000175cab6a0] [c00000000002fbcc] .die+0x21c/0x2a0 [c000000175cab750] [c000000000030000] ._exception+0x110/0x220 [c000000175cab910] [c000000000004b9c] program_check_common+0x11c/0x180 Signed-off-by: David S. Miller <[email protected]> CWE ID:
int rds_ib_xmit(struct rds_connection *conn, struct rds_message *rm, unsigned int hdr_off, unsigned int sg, unsigned int off) { struct rds_ib_connection *ic = conn->c_transport_data; struct ib_device *dev = ic->i_cm_id->device; struct rds_ib_send_work *send = NULL; struct rds_ib_send_work *first; struct rds_ib_send_work *prev; struct ib_send_wr *failed_wr; struct scatterlist *scat; u32 pos; u32 i; u32 work_alloc; u32 credit_alloc = 0; u32 posted; u32 adv_credits = 0; int send_flags = 0; int bytes_sent = 0; int ret; int flow_controlled = 0; int nr_sig = 0; BUG_ON(off % RDS_FRAG_SIZE); BUG_ON(hdr_off != 0 && hdr_off != sizeof(struct rds_header)); /* Do not send cong updates to IB loopback */ if (conn->c_loopback && rm->m_inc.i_hdr.h_flags & RDS_FLAG_CONG_BITMAP) { rds_cong_map_updated(conn->c_fcong, ~(u64) 0); scat = &rm->data.op_sg[sg]; ret = sizeof(struct rds_header) + RDS_CONG_MAP_BYTES; ret = min_t(int, ret, scat->length - conn->c_xmit_data_off); return ret; } /* FIXME we may overallocate here */ if (be32_to_cpu(rm->m_inc.i_hdr.h_len) == 0) i = 1; else i = ceil(be32_to_cpu(rm->m_inc.i_hdr.h_len), RDS_FRAG_SIZE); work_alloc = rds_ib_ring_alloc(&ic->i_send_ring, i, &pos); if (work_alloc == 0) { set_bit(RDS_LL_SEND_FULL, &conn->c_flags); rds_ib_stats_inc(s_ib_tx_ring_full); ret = -ENOMEM; goto out; } if (ic->i_flowctl) { credit_alloc = rds_ib_send_grab_credits(ic, work_alloc, &posted, 0, RDS_MAX_ADV_CREDIT); adv_credits += posted; if (credit_alloc < work_alloc) { rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc - credit_alloc); work_alloc = credit_alloc; flow_controlled = 1; } if (work_alloc == 0) { set_bit(RDS_LL_SEND_FULL, &conn->c_flags); rds_ib_stats_inc(s_ib_tx_throttle); ret = -ENOMEM; goto out; } } /* map the message the first time we see it */ if (!ic->i_data_op) { if (rm->data.op_nents) { rm->data.op_count = ib_dma_map_sg(dev, rm->data.op_sg, rm->data.op_nents, DMA_TO_DEVICE); rdsdebug("ic %p mapping rm %p: %d\n", ic, rm, rm->data.op_count); if (rm->data.op_count == 0) { rds_ib_stats_inc(s_ib_tx_sg_mapping_failure); rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc); ret = -ENOMEM; /* XXX ? */ goto out; } } else { rm->data.op_count = 0; } rds_message_addref(rm); ic->i_data_op = &rm->data; /* Finalize the header */ if (test_bit(RDS_MSG_ACK_REQUIRED, &rm->m_flags)) rm->m_inc.i_hdr.h_flags |= RDS_FLAG_ACK_REQUIRED; if (test_bit(RDS_MSG_RETRANSMITTED, &rm->m_flags)) rm->m_inc.i_hdr.h_flags |= RDS_FLAG_RETRANSMITTED; /* If it has a RDMA op, tell the peer we did it. This is * used by the peer to release use-once RDMA MRs. */ if (rm->rdma.op_active) { struct rds_ext_header_rdma ext_hdr; ext_hdr.h_rdma_rkey = cpu_to_be32(rm->rdma.op_rkey); rds_message_add_extension(&rm->m_inc.i_hdr, RDS_EXTHDR_RDMA, &ext_hdr, sizeof(ext_hdr)); } if (rm->m_rdma_cookie) { rds_message_add_rdma_dest_extension(&rm->m_inc.i_hdr, rds_rdma_cookie_key(rm->m_rdma_cookie), rds_rdma_cookie_offset(rm->m_rdma_cookie)); } /* Note - rds_ib_piggyb_ack clears the ACK_REQUIRED bit, so * we should not do this unless we have a chance of at least * sticking the header into the send ring. Which is why we * should call rds_ib_ring_alloc first. */ rm->m_inc.i_hdr.h_ack = cpu_to_be64(rds_ib_piggyb_ack(ic)); rds_message_make_checksum(&rm->m_inc.i_hdr); /* * Update adv_credits since we reset the ACK_REQUIRED bit. */ if (ic->i_flowctl) { rds_ib_send_grab_credits(ic, 0, &posted, 1, RDS_MAX_ADV_CREDIT - adv_credits); adv_credits += posted; BUG_ON(adv_credits > 255); } } /* Sometimes you want to put a fence between an RDMA * READ and the following SEND. * We could either do this all the time * or when requested by the user. Right now, we let * the application choose. */ if (rm->rdma.op_active && rm->rdma.op_fence) send_flags = IB_SEND_FENCE; /* Each frag gets a header. Msgs may be 0 bytes */ send = &ic->i_sends[pos]; first = send; prev = NULL; scat = &ic->i_data_op->op_sg[sg]; i = 0; do { unsigned int len = 0; /* Set up the header */ send->s_wr.send_flags = send_flags; send->s_wr.opcode = IB_WR_SEND; send->s_wr.num_sge = 1; send->s_wr.next = NULL; send->s_queued = jiffies; send->s_op = NULL; send->s_sge[0].addr = ic->i_send_hdrs_dma + (pos * sizeof(struct rds_header)); send->s_sge[0].length = sizeof(struct rds_header); memcpy(&ic->i_send_hdrs[pos], &rm->m_inc.i_hdr, sizeof(struct rds_header)); /* Set up the data, if present */ if (i < work_alloc && scat != &rm->data.op_sg[rm->data.op_count]) { len = min(RDS_FRAG_SIZE, ib_sg_dma_len(dev, scat) - off); send->s_wr.num_sge = 2; send->s_sge[1].addr = ib_sg_dma_address(dev, scat) + off; send->s_sge[1].length = len; bytes_sent += len; off += len; if (off == ib_sg_dma_len(dev, scat)) { scat++; off = 0; } } rds_ib_set_wr_signal_state(ic, send, 0); /* * Always signal the last one if we're stopping due to flow control. */ if (ic->i_flowctl && flow_controlled && i == (work_alloc-1)) send->s_wr.send_flags |= IB_SEND_SIGNALED | IB_SEND_SOLICITED; if (send->s_wr.send_flags & IB_SEND_SIGNALED) nr_sig++; rdsdebug("send %p wr %p num_sge %u next %p\n", send, &send->s_wr, send->s_wr.num_sge, send->s_wr.next); if (ic->i_flowctl && adv_credits) { struct rds_header *hdr = &ic->i_send_hdrs[pos]; /* add credit and redo the header checksum */ hdr->h_credit = adv_credits; rds_message_make_checksum(hdr); adv_credits = 0; rds_ib_stats_inc(s_ib_tx_credit_updates); } if (prev) prev->s_wr.next = &send->s_wr; prev = send; pos = (pos + 1) % ic->i_send_ring.w_nr; send = &ic->i_sends[pos]; i++; } while (i < work_alloc && scat != &rm->data.op_sg[rm->data.op_count]); /* Account the RDS header in the number of bytes we sent, but just once. * The caller has no concept of fragmentation. */ if (hdr_off == 0) bytes_sent += sizeof(struct rds_header); /* if we finished the message then send completion owns it */ if (scat == &rm->data.op_sg[rm->data.op_count]) { prev->s_op = ic->i_data_op; prev->s_wr.send_flags |= IB_SEND_SOLICITED; ic->i_data_op = NULL; } /* Put back wrs & credits we didn't use */ if (i < work_alloc) { rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc - i); work_alloc = i; } if (ic->i_flowctl && i < credit_alloc) rds_ib_send_add_credits(conn, credit_alloc - i); if (nr_sig) atomic_add(nr_sig, &ic->i_signaled_sends); /* XXX need to worry about failed_wr and partial sends. */ failed_wr = &first->s_wr; ret = ib_post_send(ic->i_cm_id->qp, &first->s_wr, &failed_wr); rdsdebug("ic %p first %p (wr %p) ret %d wr %p\n", ic, first, &first->s_wr, ret, failed_wr); BUG_ON(failed_wr != &first->s_wr); if (ret) { printk(KERN_WARNING "RDS/IB: ib_post_send to %pI4 " "returned %d\n", &conn->c_faddr, ret); rds_ib_ring_unalloc(&ic->i_send_ring, work_alloc); rds_ib_sub_signaled(ic, nr_sig); if (prev->s_op) { ic->i_data_op = prev->s_op; prev->s_op = NULL; } rds_ib_conn_error(ic->conn, "ib_post_send failed\n"); goto out; } ret = bytes_sent; out: BUG_ON(adv_credits); return ret; }
165,899
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t SampleIterator::seekTo(uint32_t sampleIndex) { ALOGV("seekTo(%d)", sampleIndex); if (sampleIndex >= mTable->mNumSampleSizes) { return ERROR_END_OF_STREAM; } if (mTable->mSampleToChunkOffset < 0 || mTable->mChunkOffsetOffset < 0 || mTable->mSampleSizeOffset < 0 || mTable->mTimeToSampleCount == 0) { return ERROR_MALFORMED; } if (mInitialized && mCurrentSampleIndex == sampleIndex) { return OK; } if (!mInitialized || sampleIndex < mFirstChunkSampleIndex) { reset(); } if (sampleIndex >= mStopChunkSampleIndex) { status_t err; if ((err = findChunkRange(sampleIndex)) != OK) { ALOGE("findChunkRange failed"); return err; } } CHECK(sampleIndex < mStopChunkSampleIndex); if (mSamplesPerChunk == 0) { ALOGE("b/22802344"); return ERROR_MALFORMED; } uint32_t chunk = (sampleIndex - mFirstChunkSampleIndex) / mSamplesPerChunk + mFirstChunk; if (!mInitialized || chunk != mCurrentChunkIndex) { mCurrentChunkIndex = chunk; status_t err; if ((err = getChunkOffset(chunk, &mCurrentChunkOffset)) != OK) { ALOGE("getChunkOffset return error"); return err; } mCurrentChunkSampleSizes.clear(); uint32_t firstChunkSampleIndex = mFirstChunkSampleIndex + mSamplesPerChunk * (mCurrentChunkIndex - mFirstChunk); for (uint32_t i = 0; i < mSamplesPerChunk; ++i) { size_t sampleSize; if ((err = getSampleSizeDirect( firstChunkSampleIndex + i, &sampleSize)) != OK) { ALOGE("getSampleSizeDirect return error"); return err; } mCurrentChunkSampleSizes.push(sampleSize); } } uint32_t chunkRelativeSampleIndex = (sampleIndex - mFirstChunkSampleIndex) % mSamplesPerChunk; mCurrentSampleOffset = mCurrentChunkOffset; for (uint32_t i = 0; i < chunkRelativeSampleIndex; ++i) { mCurrentSampleOffset += mCurrentChunkSampleSizes[i]; } mCurrentSampleSize = mCurrentChunkSampleSizes[chunkRelativeSampleIndex]; if (sampleIndex < mTTSSampleIndex) { mTimeToSampleIndex = 0; mTTSSampleIndex = 0; mTTSSampleTime = 0; mTTSCount = 0; mTTSDuration = 0; } status_t err; if ((err = findSampleTimeAndDuration( sampleIndex, &mCurrentSampleTime, &mCurrentSampleDuration)) != OK) { ALOGE("findSampleTime return error"); return err; } mCurrentSampleIndex = sampleIndex; mInitialized = true; return OK; } Commit Message: SampleIterator: clear members on seekTo error Bug: 31091777 Change-Id: Iddf99d0011961d0fd3d755e57db4365b6a6a1193 (cherry picked from commit 03237ce0f9584c98ccda76c2474a4ae84c763f5b) CWE ID: CWE-200
status_t SampleIterator::seekTo(uint32_t sampleIndex) { ALOGV("seekTo(%d)", sampleIndex); if (sampleIndex >= mTable->mNumSampleSizes) { return ERROR_END_OF_STREAM; } if (mTable->mSampleToChunkOffset < 0 || mTable->mChunkOffsetOffset < 0 || mTable->mSampleSizeOffset < 0 || mTable->mTimeToSampleCount == 0) { return ERROR_MALFORMED; } if (mInitialized && mCurrentSampleIndex == sampleIndex) { return OK; } if (!mInitialized || sampleIndex < mFirstChunkSampleIndex) { reset(); } if (sampleIndex >= mStopChunkSampleIndex) { status_t err; if ((err = findChunkRange(sampleIndex)) != OK) { ALOGE("findChunkRange failed"); return err; } } CHECK(sampleIndex < mStopChunkSampleIndex); if (mSamplesPerChunk == 0) { ALOGE("b/22802344"); return ERROR_MALFORMED; } uint32_t chunk = (sampleIndex - mFirstChunkSampleIndex) / mSamplesPerChunk + mFirstChunk; if (!mInitialized || chunk != mCurrentChunkIndex) { status_t err; if ((err = getChunkOffset(chunk, &mCurrentChunkOffset)) != OK) { ALOGE("getChunkOffset return error"); return err; } mCurrentChunkSampleSizes.clear(); uint32_t firstChunkSampleIndex = mFirstChunkSampleIndex + mSamplesPerChunk * (chunk - mFirstChunk); for (uint32_t i = 0; i < mSamplesPerChunk; ++i) { size_t sampleSize; if ((err = getSampleSizeDirect( firstChunkSampleIndex + i, &sampleSize)) != OK) { ALOGE("getSampleSizeDirect return error"); mCurrentChunkSampleSizes.clear(); return err; } mCurrentChunkSampleSizes.push(sampleSize); } mCurrentChunkIndex = chunk; } uint32_t chunkRelativeSampleIndex = (sampleIndex - mFirstChunkSampleIndex) % mSamplesPerChunk; mCurrentSampleOffset = mCurrentChunkOffset; for (uint32_t i = 0; i < chunkRelativeSampleIndex; ++i) { mCurrentSampleOffset += mCurrentChunkSampleSizes[i]; } mCurrentSampleSize = mCurrentChunkSampleSizes[chunkRelativeSampleIndex]; if (sampleIndex < mTTSSampleIndex) { mTimeToSampleIndex = 0; mTTSSampleIndex = 0; mTTSSampleTime = 0; mTTSCount = 0; mTTSDuration = 0; } status_t err; if ((err = findSampleTimeAndDuration( sampleIndex, &mCurrentSampleTime, &mCurrentSampleDuration)) != OK) { ALOGE("findSampleTime return error"); return err; } mCurrentSampleIndex = sampleIndex; mInitialized = true; return OK; }
173,378
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void snd_msndmidi_input_read(void *mpuv) { unsigned long flags; struct snd_msndmidi *mpu = mpuv; void *pwMIDQData = mpu->dev->mappedbase + MIDQ_DATA_BUFF; spin_lock_irqsave(&mpu->input_lock, flags); while (readw(mpu->dev->MIDQ + JQS_wTail) != readw(mpu->dev->MIDQ + JQS_wHead)) { u16 wTmp, val; val = readw(pwMIDQData + 2 * readw(mpu->dev->MIDQ + JQS_wHead)); if (test_bit(MSNDMIDI_MODE_BIT_INPUT_TRIGGER, &mpu->mode)) snd_rawmidi_receive(mpu->substream_input, (unsigned char *)&val, 1); wTmp = readw(mpu->dev->MIDQ + JQS_wHead) + 1; if (wTmp > readw(mpu->dev->MIDQ + JQS_wSize)) writew(0, mpu->dev->MIDQ + JQS_wHead); else writew(wTmp, mpu->dev->MIDQ + JQS_wHead); } spin_unlock_irqrestore(&mpu->input_lock, flags); } Commit Message: ALSA: msnd: Optimize / harden DSP and MIDI loops The ISA msnd drivers have loops fetching the ring-buffer head, tail and size values inside the loops. Such codes are inefficient and fragile. This patch optimizes it, and also adds the sanity check to avoid the endless loops. Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196131 Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196133 Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-125
void snd_msndmidi_input_read(void *mpuv) { unsigned long flags; struct snd_msndmidi *mpu = mpuv; void *pwMIDQData = mpu->dev->mappedbase + MIDQ_DATA_BUFF; u16 head, tail, size; spin_lock_irqsave(&mpu->input_lock, flags); head = readw(mpu->dev->MIDQ + JQS_wHead); tail = readw(mpu->dev->MIDQ + JQS_wTail); size = readw(mpu->dev->MIDQ + JQS_wSize); if (head > size || tail > size) goto out; while (head != tail) { unsigned char val = readw(pwMIDQData + 2 * head); if (test_bit(MSNDMIDI_MODE_BIT_INPUT_TRIGGER, &mpu->mode)) snd_rawmidi_receive(mpu->substream_input, &val, 1); if (++head > size) head = 0; writew(head, mpu->dev->MIDQ + JQS_wHead); } out: spin_unlock_irqrestore(&mpu->input_lock, flags); }
168,079
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void reference_32x32_dct_1d(const double in[32], double out[32], int stride) { const double kInvSqrt2 = 0.707106781186547524400844362104; for (int k = 0; k < 32; k++) { out[k] = 0.0; for (int n = 0; n < 32; n++) out[k] += in[n] * cos(kPi * (2 * n + 1) * k / 64.0); if (k == 0) out[k] = out[k] * kInvSqrt2; } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void reference_32x32_dct_1d(const double in[32], double out[32], int stride) { void reference_32x32_dct_1d(const double in[32], double out[32]) { const double kInvSqrt2 = 0.707106781186547524400844362104; for (int k = 0; k < 32; k++) { out[k] = 0.0; for (int n = 0; n < 32; n++) out[k] += in[n] * cos(kPi * (2 * n + 1) * k / 64.0); if (k == 0) out[k] = out[k] * kInvSqrt2; } }
174,532
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewUI::SetPrintPreviewDataForIndex( int index, const base::RefCountedBytes* data) { print_preview_data_service()->SetDataEntry(preview_ui_addr_str_, index, data); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::SetPrintPreviewDataForIndex( int index, const base::RefCountedBytes* data) { print_preview_data_service()->SetDataEntry(id_, index, data); }
170,843
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void prefetch_table(const volatile byte *tab, size_t len) { size_t i; for (i = 0; i < len; i += 8 * 32) { (void)tab[i + 0 * 32]; (void)tab[i + 1 * 32]; (void)tab[i + 2 * 32]; (void)tab[i + 3 * 32]; (void)tab[i + 4 * 32]; (void)tab[i + 5 * 32]; (void)tab[i + 6 * 32]; (void)tab[i + 7 * 32]; } (void)tab[len - 1]; } Commit Message: AES: move look-up tables to .data section and unshare between processes * cipher/rijndael-internal.h (ATTR_ALIGNED_64): New. * cipher/rijndael-tables.h (encT): Move to 'enc_tables' structure. (enc_tables): New structure for encryption table with counters before and after. (encT): New macro. (dec_tables): Add counters before and after encryption table; Move from .rodata to .data section. (do_encrypt): Change 'encT' to 'enc_tables.T'. (do_decrypt): Change '&dec_tables' to 'dec_tables.T'. * cipher/cipher-gcm.c (prefetch_table): Make inline; Handle input with length not multiple of 256. (prefetch_enc, prefetch_dec): Modify pre- and post-table counters to unshare look-up table pages between processes. -- GnuPG-bug-id: 4541 Signed-off-by: Jussi Kivilinna <[email protected]> CWE ID: CWE-310
static void prefetch_table(const volatile byte *tab, size_t len) static inline void prefetch_table(const volatile byte *tab, size_t len) { size_t i; for (i = 0; len - i >= 8 * 32; i += 8 * 32) { (void)tab[i + 0 * 32]; (void)tab[i + 1 * 32]; (void)tab[i + 2 * 32]; (void)tab[i + 3 * 32]; (void)tab[i + 4 * 32]; (void)tab[i + 5 * 32]; (void)tab[i + 6 * 32]; (void)tab[i + 7 * 32]; } for (; i < len; i += 32) { (void)tab[i]; } (void)tab[len - 1]; }
170,215
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static __init int hardware_setup(void) { int r = -ENOMEM, i, msr; rdmsrl_safe(MSR_EFER, &host_efer); for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) kvm_define_shared_msr(i, vmx_msr_index[i]); vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_io_bitmap_a) return r; vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_io_bitmap_b) goto out; vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_legacy) goto out1; vmx_msr_bitmap_legacy_x2apic = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_legacy_x2apic) goto out2; vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_longmode) goto out3; vmx_msr_bitmap_longmode_x2apic = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_longmode_x2apic) goto out4; if (nested) { vmx_msr_bitmap_nested = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_nested) goto out5; } vmx_vmread_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_vmread_bitmap) goto out6; vmx_vmwrite_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_vmwrite_bitmap) goto out7; memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE); memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE); /* * Allow direct access to the PC debug port (it is often used for I/O * delays, but the vmexits simply slow things down). */ memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE); clear_bit(0x80, vmx_io_bitmap_a); memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE); memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE); memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE); if (nested) memset(vmx_msr_bitmap_nested, 0xff, PAGE_SIZE); if (setup_vmcs_config(&vmcs_config) < 0) { r = -EIO; goto out8; } if (boot_cpu_has(X86_FEATURE_NX)) kvm_enable_efer_bits(EFER_NX); if (!cpu_has_vmx_vpid()) enable_vpid = 0; if (!cpu_has_vmx_shadow_vmcs()) enable_shadow_vmcs = 0; if (enable_shadow_vmcs) init_vmcs_shadow_fields(); if (!cpu_has_vmx_ept() || !cpu_has_vmx_ept_4levels()) { enable_ept = 0; enable_unrestricted_guest = 0; enable_ept_ad_bits = 0; } if (!cpu_has_vmx_ept_ad_bits()) enable_ept_ad_bits = 0; if (!cpu_has_vmx_unrestricted_guest()) enable_unrestricted_guest = 0; if (!cpu_has_vmx_flexpriority()) flexpriority_enabled = 0; /* * set_apic_access_page_addr() is used to reload apic access * page upon invalidation. No need to do anything if not * using the APIC_ACCESS_ADDR VMCS field. */ if (!flexpriority_enabled) kvm_x86_ops->set_apic_access_page_addr = NULL; if (!cpu_has_vmx_tpr_shadow()) kvm_x86_ops->update_cr8_intercept = NULL; if (enable_ept && !cpu_has_vmx_ept_2m_page()) kvm_disable_largepages(); if (!cpu_has_vmx_ple()) ple_gap = 0; if (!cpu_has_vmx_apicv()) enable_apicv = 0; if (cpu_has_vmx_tsc_scaling()) { kvm_has_tsc_control = true; kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX; kvm_tsc_scaling_ratio_frac_bits = 48; } vmx_disable_intercept_for_msr(MSR_FS_BASE, false); vmx_disable_intercept_for_msr(MSR_GS_BASE, false); vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true); vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false); vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false); vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false); vmx_disable_intercept_for_msr(MSR_IA32_BNDCFGS, true); memcpy(vmx_msr_bitmap_legacy_x2apic, vmx_msr_bitmap_legacy, PAGE_SIZE); memcpy(vmx_msr_bitmap_longmode_x2apic, vmx_msr_bitmap_longmode, PAGE_SIZE); set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */ if (enable_apicv) { for (msr = 0x800; msr <= 0x8ff; msr++) vmx_disable_intercept_msr_read_x2apic(msr); /* According SDM, in x2apic mode, the whole id reg is used. * But in KVM, it only use the highest eight bits. Need to * intercept it */ vmx_enable_intercept_msr_read_x2apic(0x802); /* TMCCT */ vmx_enable_intercept_msr_read_x2apic(0x839); /* TPR */ vmx_disable_intercept_msr_write_x2apic(0x808); /* EOI */ vmx_disable_intercept_msr_write_x2apic(0x80b); /* SELF-IPI */ vmx_disable_intercept_msr_write_x2apic(0x83f); } if (enable_ept) { kvm_mmu_set_mask_ptes(0ull, (enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull, (enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull, 0ull, VMX_EPT_EXECUTABLE_MASK); ept_set_mmio_spte_mask(); kvm_enable_tdp(); } else kvm_disable_tdp(); update_ple_window_actual_max(); /* * Only enable PML when hardware supports PML feature, and both EPT * and EPT A/D bit features are enabled -- PML depends on them to work. */ if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml()) enable_pml = 0; if (!enable_pml) { kvm_x86_ops->slot_enable_log_dirty = NULL; kvm_x86_ops->slot_disable_log_dirty = NULL; kvm_x86_ops->flush_log_dirty = NULL; kvm_x86_ops->enable_log_dirty_pt_masked = NULL; } kvm_set_posted_intr_wakeup_handler(wakeup_handler); return alloc_kvm_area(); out8: free_page((unsigned long)vmx_vmwrite_bitmap); out7: free_page((unsigned long)vmx_vmread_bitmap); out6: if (nested) free_page((unsigned long)vmx_msr_bitmap_nested); out5: free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic); out4: free_page((unsigned long)vmx_msr_bitmap_longmode); out3: free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic); out2: free_page((unsigned long)vmx_msr_bitmap_legacy); out1: free_page((unsigned long)vmx_io_bitmap_b); out: free_page((unsigned long)vmx_io_bitmap_a); return r; } Commit Message: kvm:vmx: more complete state update on APICv on/off The function to update APICv on/off state (in particular, to deactivate it when enabling Hyper-V SynIC) is incomplete: it doesn't adjust APICv-related fields among secondary processor-based VM-execution controls. As a result, Windows 2012 guests get stuck when SynIC-based auto-EOI interrupt intersected with e.g. an IPI in the guest. In addition, the MSR intercept bitmap isn't updated every time "virtualize x2APIC mode" is toggled. This path can only be triggered by a malicious guest, because Windows didn't use x2APIC but rather their own synthetic APIC access MSRs; however a guest running in a SynIC-enabled VM could switch to x2APIC and thus obtain direct access to host APIC MSRs (CVE-2016-4440). The patch fixes those omissions. Signed-off-by: Roman Kagan <[email protected]> Reported-by: Steve Rutherford <[email protected]> Reported-by: Yang Zhang <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264
static __init int hardware_setup(void) { int r = -ENOMEM, i, msr; rdmsrl_safe(MSR_EFER, &host_efer); for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) kvm_define_shared_msr(i, vmx_msr_index[i]); vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_io_bitmap_a) return r; vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_io_bitmap_b) goto out; vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_legacy) goto out1; vmx_msr_bitmap_legacy_x2apic = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_legacy_x2apic) goto out2; vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_longmode) goto out3; vmx_msr_bitmap_longmode_x2apic = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_longmode_x2apic) goto out4; if (nested) { vmx_msr_bitmap_nested = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_nested) goto out5; } vmx_vmread_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_vmread_bitmap) goto out6; vmx_vmwrite_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_vmwrite_bitmap) goto out7; memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE); memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE); /* * Allow direct access to the PC debug port (it is often used for I/O * delays, but the vmexits simply slow things down). */ memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE); clear_bit(0x80, vmx_io_bitmap_a); memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE); memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE); memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE); if (nested) memset(vmx_msr_bitmap_nested, 0xff, PAGE_SIZE); if (setup_vmcs_config(&vmcs_config) < 0) { r = -EIO; goto out8; } if (boot_cpu_has(X86_FEATURE_NX)) kvm_enable_efer_bits(EFER_NX); if (!cpu_has_vmx_vpid()) enable_vpid = 0; if (!cpu_has_vmx_shadow_vmcs()) enable_shadow_vmcs = 0; if (enable_shadow_vmcs) init_vmcs_shadow_fields(); if (!cpu_has_vmx_ept() || !cpu_has_vmx_ept_4levels()) { enable_ept = 0; enable_unrestricted_guest = 0; enable_ept_ad_bits = 0; } if (!cpu_has_vmx_ept_ad_bits()) enable_ept_ad_bits = 0; if (!cpu_has_vmx_unrestricted_guest()) enable_unrestricted_guest = 0; if (!cpu_has_vmx_flexpriority()) flexpriority_enabled = 0; /* * set_apic_access_page_addr() is used to reload apic access * page upon invalidation. No need to do anything if not * using the APIC_ACCESS_ADDR VMCS field. */ if (!flexpriority_enabled) kvm_x86_ops->set_apic_access_page_addr = NULL; if (!cpu_has_vmx_tpr_shadow()) kvm_x86_ops->update_cr8_intercept = NULL; if (enable_ept && !cpu_has_vmx_ept_2m_page()) kvm_disable_largepages(); if (!cpu_has_vmx_ple()) ple_gap = 0; if (!cpu_has_vmx_apicv()) enable_apicv = 0; if (cpu_has_vmx_tsc_scaling()) { kvm_has_tsc_control = true; kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX; kvm_tsc_scaling_ratio_frac_bits = 48; } vmx_disable_intercept_for_msr(MSR_FS_BASE, false); vmx_disable_intercept_for_msr(MSR_GS_BASE, false); vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true); vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false); vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false); vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false); vmx_disable_intercept_for_msr(MSR_IA32_BNDCFGS, true); memcpy(vmx_msr_bitmap_legacy_x2apic, vmx_msr_bitmap_legacy, PAGE_SIZE); memcpy(vmx_msr_bitmap_longmode_x2apic, vmx_msr_bitmap_longmode, PAGE_SIZE); set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */ for (msr = 0x800; msr <= 0x8ff; msr++) vmx_disable_intercept_msr_read_x2apic(msr); /* According SDM, in x2apic mode, the whole id reg is used. But in * KVM, it only use the highest eight bits. Need to intercept it */ vmx_enable_intercept_msr_read_x2apic(0x802); /* TMCCT */ vmx_enable_intercept_msr_read_x2apic(0x839); /* TPR */ vmx_disable_intercept_msr_write_x2apic(0x808); /* EOI */ vmx_disable_intercept_msr_write_x2apic(0x80b); /* SELF-IPI */ vmx_disable_intercept_msr_write_x2apic(0x83f); if (enable_ept) { kvm_mmu_set_mask_ptes(0ull, (enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull, (enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull, 0ull, VMX_EPT_EXECUTABLE_MASK); ept_set_mmio_spte_mask(); kvm_enable_tdp(); } else kvm_disable_tdp(); update_ple_window_actual_max(); /* * Only enable PML when hardware supports PML feature, and both EPT * and EPT A/D bit features are enabled -- PML depends on them to work. */ if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml()) enable_pml = 0; if (!enable_pml) { kvm_x86_ops->slot_enable_log_dirty = NULL; kvm_x86_ops->slot_disable_log_dirty = NULL; kvm_x86_ops->flush_log_dirty = NULL; kvm_x86_ops->enable_log_dirty_pt_masked = NULL; } kvm_set_posted_intr_wakeup_handler(wakeup_handler); return alloc_kvm_area(); out8: free_page((unsigned long)vmx_vmwrite_bitmap); out7: free_page((unsigned long)vmx_vmread_bitmap); out6: if (nested) free_page((unsigned long)vmx_msr_bitmap_nested); out5: free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic); out4: free_page((unsigned long)vmx_msr_bitmap_longmode); out3: free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic); out2: free_page((unsigned long)vmx_msr_bitmap_legacy); out1: free_page((unsigned long)vmx_io_bitmap_b); out: free_page((unsigned long)vmx_io_bitmap_a); return r; }
167,262
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int udf_get_filename(struct super_block *sb, uint8_t *sname, uint8_t *dname, int flen) { struct ustr *filename, *unifilename; int len = 0; filename = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!filename) return 0; unifilename = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!unifilename) goto out1; if (udf_build_ustr_exact(unifilename, sname, flen)) goto out2; if (UDF_QUERY_FLAG(sb, UDF_FLAG_UTF8)) { if (!udf_CS0toUTF8(filename, unifilename)) { udf_debug("Failed in udf_get_filename: sname = %s\n", sname); goto out2; } } else if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP)) { if (!udf_CS0toNLS(UDF_SB(sb)->s_nls_map, filename, unifilename)) { udf_debug("Failed in udf_get_filename: sname = %s\n", sname); goto out2; } } else goto out2; len = udf_translate_to_linux(dname, filename->u_name, filename->u_len, unifilename->u_name, unifilename->u_len); out2: kfree(unifilename); out1: kfree(filename); return len; } Commit Message: udf: Check path length when reading symlink Symlink reading code does not check whether the resulting path fits into the page provided by the generic code. This isn't as easy as just checking the symlink size because of various encoding conversions we perform on path. So we have to check whether there is still enough space in the buffer on the fly. CC: [email protected] Reported-by: Carl Henrik Lunde <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-17
int udf_get_filename(struct super_block *sb, uint8_t *sname, uint8_t *dname, int udf_get_filename(struct super_block *sb, uint8_t *sname, int slen, uint8_t *dname, int dlen) { struct ustr *filename, *unifilename; int len = 0; filename = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!filename) return 0; unifilename = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!unifilename) goto out1; if (udf_build_ustr_exact(unifilename, sname, slen)) goto out2; if (UDF_QUERY_FLAG(sb, UDF_FLAG_UTF8)) { if (!udf_CS0toUTF8(filename, unifilename)) { udf_debug("Failed in udf_get_filename: sname = %s\n", sname); goto out2; } } else if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP)) { if (!udf_CS0toNLS(UDF_SB(sb)->s_nls_map, filename, unifilename)) { udf_debug("Failed in udf_get_filename: sname = %s\n", sname); goto out2; } } else goto out2; len = udf_translate_to_linux(dname, dlen, filename->u_name, filename->u_len, unifilename->u_name, unifilename->u_len); out2: kfree(unifilename); out1: kfree(filename); return len; }
166,759
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: InputHandlerProxy::InputHandlerProxy(cc::InputHandler* input_handler, InputHandlerProxyClient* client, bool force_input_to_main_thread) : client_(client), input_handler_(input_handler), synchronous_input_handler_(nullptr), allow_root_animate_(true), #if DCHECK_IS_ON() expect_scroll_update_end_(false), #endif gesture_scroll_on_impl_thread_(false), scroll_sequence_ignored_(false), smooth_scroll_enabled_(false), touch_result_(kEventDispositionUndefined), mouse_wheel_result_(kEventDispositionUndefined), current_overscroll_params_(nullptr), has_ongoing_compositor_scroll_or_pinch_(false), is_first_gesture_scroll_update_(false), last_injected_gesture_was_begin_(false), tick_clock_(base::DefaultTickClock::GetInstance()), snap_fling_controller_(std::make_unique<cc::SnapFlingController>(this)), compositor_touch_action_enabled_( base::FeatureList::IsEnabled(features::kCompositorTouchAction)), force_input_to_main_thread_(force_input_to_main_thread) { DCHECK(client); input_handler_->BindToClient(this); cc::ScrollElasticityHelper* scroll_elasticity_helper = input_handler_->CreateScrollElasticityHelper(); if (scroll_elasticity_helper) { scroll_elasticity_controller_.reset( new InputScrollElasticityController(scroll_elasticity_helper)); } compositor_event_queue_ = std::make_unique<CompositorThreadEventQueue>(); scroll_predictor_ = std::make_unique<ScrollPredictor>( base::FeatureList::IsEnabled(features::kResamplingScrollEvents)); if (base::FeatureList::IsEnabled(features::kSkipTouchEventFilter) && GetFieldTrialParamValueByFeature( features::kSkipTouchEventFilter, features::kSkipTouchEventFilterFilteringProcessParamName) == features:: kSkipTouchEventFilterFilteringProcessParamValueBrowserAndRenderer) { skip_touch_filter_discrete_ = true; if (GetFieldTrialParamValueByFeature( features::kSkipTouchEventFilter, features::kSkipTouchEventFilterTypeParamName) == features::kSkipTouchEventFilterTypeParamValueAll) { skip_touch_filter_all_ = true; } } } Commit Message: Revert "Add explicit flag for compositor scrollbar injected gestures" This reverts commit d9a56afcbdf9850bc39bb3edb56d07d11a1eb2b2. Reason for revert: Findit (https://goo.gl/kROfz5) identified CL at revision 669086 as the culprit for flakes in the build cycles as shown on: https://analysis.chromium.org/p/chromium/flake-portal/analysis/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyQwsSDEZsYWtlQ3VscHJpdCIxY2hyb21pdW0vZDlhNTZhZmNiZGY5ODUwYmMzOWJiM2VkYjU2ZDA3ZDExYTFlYjJiMgw Sample Failed Build: https://ci.chromium.org/buildbot/chromium.chromiumos/linux-chromeos-rel/25818 Sample Failed Step: content_browsertests on Ubuntu-16.04 Sample Flaky Test: ScrollLatencyScrollbarBrowserTest.ScrollbarThumbDragLatency Original change's description: > Add explicit flag for compositor scrollbar injected gestures > > The original change to enable scrollbar latency for the composited > scrollbars incorrectly used an existing member to try and determine > whether a GestureScrollUpdate was the first one in an injected sequence > or not. is_first_gesture_scroll_update_ was incorrect because it is only > updated when input is actually dispatched to InputHandlerProxy, and the > flag is cleared for all GSUs before the location where it was being > read. > > This bug was missed because of incorrect tests. The > VerifyRecordedSamplesForHistogram method doesn't actually assert or > expect anything - the return value must be inspected. > > As part of fixing up the tests, I made a few other changes to get them > passing consistently across all platforms: > - turn on main thread scrollbar injection feature (in case it's ever > turned off we don't want the tests to start failing) > - enable mock scrollbars > - disable smooth scrolling > - don't run scrollbar tests on Android > > The composited scrollbar button test is disabled due to a bug in how > the mock theme reports its button sizes, which throws off the region > detection in ScrollbarLayerImplBase::IdentifyScrollbarPart (filed > crbug.com/974063 for this issue). > > Change-Id: Ie1a762a5f6ecc264d22f0256db68f141fc76b950 > > Bug: 954007 > Change-Id: Ib258e08e083e79da90ba2e4e4216e4879cf00cf7 > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1652741 > Commit-Queue: Daniel Libby <[email protected]> > Reviewed-by: David Bokan <[email protected]> > Cr-Commit-Position: refs/heads/master@{#669086} Change-Id: Icc743e48fa740fe27f0cb0cfa21b209a696f518c No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 954007 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1660114 Cr-Commit-Position: refs/heads/master@{#669150} CWE ID: CWE-281
InputHandlerProxy::InputHandlerProxy(cc::InputHandler* input_handler, InputHandlerProxyClient* client, bool force_input_to_main_thread) : client_(client), input_handler_(input_handler), synchronous_input_handler_(nullptr), allow_root_animate_(true), #if DCHECK_IS_ON() expect_scroll_update_end_(false), #endif gesture_scroll_on_impl_thread_(false), scroll_sequence_ignored_(false), smooth_scroll_enabled_(false), touch_result_(kEventDispositionUndefined), mouse_wheel_result_(kEventDispositionUndefined), current_overscroll_params_(nullptr), has_ongoing_compositor_scroll_or_pinch_(false), is_first_gesture_scroll_update_(false), tick_clock_(base::DefaultTickClock::GetInstance()), snap_fling_controller_(std::make_unique<cc::SnapFlingController>(this)), compositor_touch_action_enabled_( base::FeatureList::IsEnabled(features::kCompositorTouchAction)), force_input_to_main_thread_(force_input_to_main_thread) { DCHECK(client); input_handler_->BindToClient(this); cc::ScrollElasticityHelper* scroll_elasticity_helper = input_handler_->CreateScrollElasticityHelper(); if (scroll_elasticity_helper) { scroll_elasticity_controller_.reset( new InputScrollElasticityController(scroll_elasticity_helper)); } compositor_event_queue_ = std::make_unique<CompositorThreadEventQueue>(); scroll_predictor_ = std::make_unique<ScrollPredictor>( base::FeatureList::IsEnabled(features::kResamplingScrollEvents)); if (base::FeatureList::IsEnabled(features::kSkipTouchEventFilter) && GetFieldTrialParamValueByFeature( features::kSkipTouchEventFilter, features::kSkipTouchEventFilterFilteringProcessParamName) == features:: kSkipTouchEventFilterFilteringProcessParamValueBrowserAndRenderer) { skip_touch_filter_discrete_ = true; if (GetFieldTrialParamValueByFeature( features::kSkipTouchEventFilter, features::kSkipTouchEventFilterTypeParamName) == features::kSkipTouchEventFilterTypeParamValueAll) { skip_touch_filter_all_ = true; } } }
172,433
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset, ssize_t size, void *private) { ext4_io_end_t *io_end = iocb->private; struct workqueue_struct *wq; /* if not async direct IO or dio with 0 bytes write, just return */ if (!io_end || !size) return; ext_debug("ext4_end_io_dio(): io_end 0x%p" "for inode %lu, iocb 0x%p, offset %llu, size %llu\n", iocb->private, io_end->inode->i_ino, iocb, offset, size); /* if not aio dio with unwritten extents, just free io and return */ if (io_end->flag != EXT4_IO_UNWRITTEN){ ext4_free_io_end(io_end); iocb->private = NULL; return; } io_end->offset = offset; io_end->size = size; wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq; /* queue the work to convert unwritten extents to written */ queue_work(wq, &io_end->work); /* Add the io_end to per-inode completed aio dio list*/ list_add_tail(&io_end->list, &EXT4_I(io_end->inode)->i_completed_io_list); iocb->private = NULL; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset, ssize_t size, void *private) { ext4_io_end_t *io_end = iocb->private; struct workqueue_struct *wq; unsigned long flags; struct ext4_inode_info *ei; /* if not async direct IO or dio with 0 bytes write, just return */ if (!io_end || !size) return; ext_debug("ext4_end_io_dio(): io_end 0x%p" "for inode %lu, iocb 0x%p, offset %llu, size %llu\n", iocb->private, io_end->inode->i_ino, iocb, offset, size); /* if not aio dio with unwritten extents, just free io and return */ if (io_end->flag != EXT4_IO_UNWRITTEN){ ext4_free_io_end(io_end); iocb->private = NULL; return; } io_end->offset = offset; io_end->size = size; io_end->flag = EXT4_IO_UNWRITTEN; wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq; /* queue the work to convert unwritten extents to written */ queue_work(wq, &io_end->work); /* Add the io_end to per-inode completed aio dio list*/ ei = EXT4_I(io_end->inode); spin_lock_irqsave(&ei->i_completed_io_lock, flags); list_add_tail(&io_end->list, &ei->i_completed_io_list); spin_unlock_irqrestore(&ei->i_completed_io_lock, flags); iocb->private = NULL; }
167,540
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static double digitize(double value, int depth, int do_round) { /* 'value' is in the range 0 to 1, the result is the same value rounded to a * multiple of the digitization factor - 8 or 16 bits depending on both the * sample depth and the 'assume' setting. Digitization is normally by * rounding and 'do_round' should be 1, if it is 0 the digitized value will * be truncated. */ PNG_CONST unsigned int digitization_factor = (1U << depth) -1; /* Limiting the range is done as a convenience to the caller - it's easier to * do it once here than every time at the call site. */ if (value <= 0) value = 0; else if (value >= 1) value = 1; value *= digitization_factor; if (do_round) value += .5; return floor(value)/digitization_factor; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static double digitize(double value, int depth, int do_round) { /* 'value' is in the range 0 to 1, the result is the same value rounded to a * multiple of the digitization factor - 8 or 16 bits depending on both the * sample depth and the 'assume' setting. Digitization is normally by * rounding and 'do_round' should be 1, if it is 0 the digitized value will * be truncated. */ const unsigned int digitization_factor = (1U << depth) -1; /* Limiting the range is done as a convenience to the caller - it's easier to * do it once here than every time at the call site. */ if (value <= 0) value = 0; else if (value >= 1) value = 1; value *= digitization_factor; if (do_round) value += .5; return floor(value)/digitization_factor; }
173,608
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int klsi_105_get_line_state(struct usb_serial_port *port, unsigned long *line_state_p) { int rc; u8 *status_buf; __u16 status; dev_info(&port->serial->dev->dev, "sending SIO Poll request\n"); status_buf = kmalloc(KLSI_STATUSBUF_LEN, GFP_KERNEL); if (!status_buf) return -ENOMEM; status_buf[0] = 0xff; status_buf[1] = 0xff; rc = usb_control_msg(port->serial->dev, usb_rcvctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_POLL, USB_TYPE_VENDOR | USB_DIR_IN, 0, /* value */ 0, /* index */ status_buf, KLSI_STATUSBUF_LEN, 10000 ); if (rc < 0) dev_err(&port->dev, "Reading line status failed (error = %d)\n", rc); else { status = get_unaligned_le16(status_buf); dev_info(&port->serial->dev->dev, "read status %x %x\n", status_buf[0], status_buf[1]); *line_state_p = klsi_105_status2linestate(status); } kfree(status_buf); return rc; } Commit Message: USB: serial: kl5kusb105: fix line-state error handling The current implementation failed to detect short transfers when attempting to read the line state, and also, to make things worse, logged the content of the uninitialised heap transfer buffer. Fixes: abf492e7b3ae ("USB: kl5kusb105: fix DMA buffers on stack") Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable <[email protected]> Reviewed-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: Johan Hovold <[email protected]> CWE ID: CWE-532
static int klsi_105_get_line_state(struct usb_serial_port *port, unsigned long *line_state_p) { int rc; u8 *status_buf; __u16 status; dev_info(&port->serial->dev->dev, "sending SIO Poll request\n"); status_buf = kmalloc(KLSI_STATUSBUF_LEN, GFP_KERNEL); if (!status_buf) return -ENOMEM; status_buf[0] = 0xff; status_buf[1] = 0xff; rc = usb_control_msg(port->serial->dev, usb_rcvctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_POLL, USB_TYPE_VENDOR | USB_DIR_IN, 0, /* value */ 0, /* index */ status_buf, KLSI_STATUSBUF_LEN, 10000 ); if (rc != KLSI_STATUSBUF_LEN) { dev_err(&port->dev, "reading line status failed: %d\n", rc); if (rc >= 0) rc = -EIO; } else { status = get_unaligned_le16(status_buf); dev_info(&port->serial->dev->dev, "read status %x %x\n", status_buf[0], status_buf[1]); *line_state_p = klsi_105_status2linestate(status); } kfree(status_buf); return rc; }
168,389
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LocalFileSystem::deleteFileSystemInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, FileSystemType type, PassRefPtr<CallbackWrapper> callbacks) { if (!fileSystem()) { fileSystemNotAvailable(context, callbacks); return; } KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString()); fileSystem()->deleteFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release()); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void LocalFileSystem::deleteFileSystemInternal( PassRefPtrWillBeRawPtr<ExecutionContext> context, FileSystemType type, CallbackWrapper* callbacks) { if (!fileSystem()) { fileSystemNotAvailable(context, callbacks); return; } KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString()); fileSystem()->deleteFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release()); }
171,425
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn, struct xfrm_replay_state_esn **preplay_esn, struct nlattr *rta) { struct xfrm_replay_state_esn *p, *pp, *up; if (!rta) return 0; up = nla_data(rta); p = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL); if (!p) return -ENOMEM; pp = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL); if (!pp) { kfree(p); return -ENOMEM; } *replay_esn = p; *preplay_esn = pp; return 0; } Commit Message: xfrm_user: ensure user supplied esn replay window is valid The current code fails to ensure that the netlink message actually contains as many bytes as the header indicates. If a user creates a new state or updates an existing one but does not supply the bytes for the whole ESN replay window, the kernel copies random heap bytes into the replay bitmap, the ones happen to follow the XFRMA_REPLAY_ESN_VAL netlink attribute. This leads to following issues: 1. The replay window has random bits set confusing the replay handling code later on. 2. A malicious user could use this flaw to leak up to ~3.5kB of heap memory when she has access to the XFRM netlink interface (requires CAP_NET_ADMIN). Known users of the ESN replay window are strongSwan and Steffen's iproute2 patch (<http://patchwork.ozlabs.org/patch/85962/>). The latter uses the interface with a bitmap supplied while the former does not. strongSwan is therefore prone to run into issue 1. To fix both issues without breaking existing userland allow using the XFRMA_REPLAY_ESN_VAL netlink attribute with either an empty bitmap or a fully specified one. For the former case we initialize the in-kernel bitmap with zero, for the latter we copy the user supplied bitmap. For state updates the full bitmap must be supplied. To prevent overflows in the bitmap length calculation the maximum size of bmp_len is limited to 128 by this patch -- resulting in a maximum replay window of 4096 packets. This should be sufficient for all real life scenarios (RFC 4303 recommends a default replay window size of 64). Cc: Steffen Klassert <[email protected]> Cc: Martin Willi <[email protected]> Cc: Ben Hutchings <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn, struct xfrm_replay_state_esn **preplay_esn, struct nlattr *rta) { struct xfrm_replay_state_esn *p, *pp, *up; int klen, ulen; if (!rta) return 0; up = nla_data(rta); klen = xfrm_replay_state_esn_len(up); ulen = nla_len(rta) >= klen ? klen : sizeof(*up); p = kzalloc(klen, GFP_KERNEL); if (!p) return -ENOMEM; pp = kzalloc(klen, GFP_KERNEL); if (!pp) { kfree(p); return -ENOMEM; } memcpy(p, up, ulen); memcpy(pp, up, ulen); *replay_esn = p; *preplay_esn = pp; return 0; }
166,191
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HTMLFormElement::ScheduleFormSubmission(FormSubmission* submission) { DCHECK(submission->Method() == FormSubmission::kPostMethod || submission->Method() == FormSubmission::kGetMethod); DCHECK(submission->Data()); DCHECK(submission->Form()); if (submission->Action().IsEmpty()) return; if (GetDocument().IsSandboxed(kSandboxForms)) { GetDocument().AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Blocked form submission to '" + submission->Action().ElidedString() + "' because the form's frame is sandboxed and the 'allow-forms' " "permission is not set.")); return; } if (!GetDocument().GetContentSecurityPolicy()->AllowFormAction( submission->Action())) { return; } if (submission->Action().ProtocolIsJavaScript()) { GetDocument() .GetFrame() ->GetScriptController() .ExecuteScriptIfJavaScriptURL(submission->Action(), this); return; } Frame* target_frame = GetDocument().GetFrame()->FindFrameForNavigation( submission->Target(), *GetDocument().GetFrame(), submission->RequestURL()); if (!target_frame) { target_frame = GetDocument().GetFrame(); } else { submission->ClearTarget(); } if (!target_frame->GetPage()) return; UseCounter::Count(GetDocument(), WebFeature::kFormsSubmitted); if (MixedContentChecker::IsMixedFormAction(GetDocument().GetFrame(), submission->Action())) { UseCounter::Count(GetDocument().GetFrame(), WebFeature::kMixedContentFormsSubmitted); } if (target_frame->IsLocalFrame()) { ToLocalFrame(target_frame) ->GetNavigationScheduler() .ScheduleFormSubmission(&GetDocument(), submission); } else { FrameLoadRequest frame_load_request = submission->CreateFrameLoadRequest(&GetDocument()); ToRemoteFrame(target_frame)->Navigate(frame_load_request); } } Commit Message: Move user activation check to RemoteFrame::Navigate's callers. Currently RemoteFrame::Navigate is the user of Frame::HasTransientUserActivation that passes a RemoteFrame*, and it seems wrong because the user activation (user gesture) needed by the navigation should belong to the LocalFrame that initiated the navigation. Follow-up CLs after this one will update UserActivation code in Frame to take a LocalFrame* instead of a Frame*, and get rid of redundant IPCs. Bug: 811414 Change-Id: I771c1694043edb54374a44213d16715d9c7da704 Reviewed-on: https://chromium-review.googlesource.com/914736 Commit-Queue: Mustaq Ahmed <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#536728} CWE ID: CWE-190
void HTMLFormElement::ScheduleFormSubmission(FormSubmission* submission) { DCHECK(submission->Method() == FormSubmission::kPostMethod || submission->Method() == FormSubmission::kGetMethod); DCHECK(submission->Data()); DCHECK(submission->Form()); if (submission->Action().IsEmpty()) return; if (GetDocument().IsSandboxed(kSandboxForms)) { GetDocument().AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Blocked form submission to '" + submission->Action().ElidedString() + "' because the form's frame is sandboxed and the 'allow-forms' " "permission is not set.")); return; } if (!GetDocument().GetContentSecurityPolicy()->AllowFormAction( submission->Action())) { return; } if (submission->Action().ProtocolIsJavaScript()) { GetDocument() .GetFrame() ->GetScriptController() .ExecuteScriptIfJavaScriptURL(submission->Action(), this); return; } Frame* target_frame = GetDocument().GetFrame()->FindFrameForNavigation( submission->Target(), *GetDocument().GetFrame(), submission->RequestURL()); if (!target_frame) { target_frame = GetDocument().GetFrame(); } else { submission->ClearTarget(); } if (!target_frame->GetPage()) return; UseCounter::Count(GetDocument(), WebFeature::kFormsSubmitted); if (MixedContentChecker::IsMixedFormAction(GetDocument().GetFrame(), submission->Action())) { UseCounter::Count(GetDocument().GetFrame(), WebFeature::kMixedContentFormsSubmitted); } if (target_frame->IsLocalFrame()) { ToLocalFrame(target_frame) ->GetNavigationScheduler() .ScheduleFormSubmission(&GetDocument(), submission); } else { FrameLoadRequest frame_load_request = submission->CreateFrameLoadRequest(&GetDocument()); frame_load_request.GetResourceRequest().SetHasUserGesture( Frame::HasTransientUserActivation(GetDocument().GetFrame())); ToRemoteFrame(target_frame)->Navigate(frame_load_request); } }
173,032
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RilSapSocket::sendResponse(MsgHeader* hdr) { size_t encoded_size = 0; uint32_t written_size; size_t buffer_size = 0; pb_ostream_t ostream; bool success = false; pthread_mutex_lock(&write_lock); if ((success = pb_get_encoded_size(&encoded_size, MsgHeader_fields, hdr)) && encoded_size <= INT32_MAX && commandFd != -1) { buffer_size = encoded_size + sizeof(uint32_t); uint8_t buffer[buffer_size]; written_size = htonl((uint32_t) encoded_size); ostream = pb_ostream_from_buffer(buffer, buffer_size); pb_write(&ostream, (uint8_t *)&written_size, sizeof(written_size)); success = pb_encode(&ostream, MsgHeader_fields, hdr); if (success) { RLOGD("Size: %d (0x%x) Size as written: 0x%x", encoded_size, encoded_size, written_size); log_hex("onRequestComplete", &buffer[sizeof(written_size)], encoded_size); RLOGI("[%d] < SAP RESPONSE type: %d. id: %d. error: %d", hdr->token, hdr->type, hdr->id,hdr->error ); if ( 0 != blockingWrite_helper(commandFd, buffer, buffer_size)) { RLOGE("Error %d while writing to fd", errno); } else { RLOGD("Write successful"); } } else { RLOGE("Error while encoding response of type %d id %d buffer_size: %d: %s.", hdr->type, hdr->id, buffer_size, PB_GET_ERROR(&ostream)); } } else { RLOGE("Not sending response type %d: encoded_size: %u. commandFd: %d. encoded size result: %d", hdr->type, encoded_size, commandFd, success); } pthread_mutex_unlock(&write_lock); } Commit Message: Replace variable-length arrays on stack with malloc. Bug: 30202619 Change-Id: Ib95e08a1c009d88a4b4fd8d8fdba0641c6129008 (cherry picked from commit 943905bb9f99e3caa856b42c531e2be752da8834) CWE ID: CWE-264
void RilSapSocket::sendResponse(MsgHeader* hdr) { size_t encoded_size = 0; uint32_t written_size; size_t buffer_size = 0; pb_ostream_t ostream; bool success = false; pthread_mutex_lock(&write_lock); if ((success = pb_get_encoded_size(&encoded_size, MsgHeader_fields, hdr)) && encoded_size <= INT32_MAX && commandFd != -1) { buffer_size = encoded_size + sizeof(uint32_t); uint8_t* buffer = (uint8_t*)malloc(buffer_size); if (!buffer) { RLOGE("sendResponse: OOM"); pthread_mutex_unlock(&write_lock); return; } written_size = htonl((uint32_t) encoded_size); ostream = pb_ostream_from_buffer(buffer, buffer_size); pb_write(&ostream, (uint8_t *)&written_size, sizeof(written_size)); success = pb_encode(&ostream, MsgHeader_fields, hdr); if (success) { RLOGD("Size: %d (0x%x) Size as written: 0x%x", encoded_size, encoded_size, written_size); log_hex("onRequestComplete", &buffer[sizeof(written_size)], encoded_size); RLOGI("[%d] < SAP RESPONSE type: %d. id: %d. error: %d", hdr->token, hdr->type, hdr->id,hdr->error ); if ( 0 != blockingWrite_helper(commandFd, buffer, buffer_size)) { RLOGE("Error %d while writing to fd", errno); } else { RLOGD("Write successful"); } } else { RLOGE("Error while encoding response of type %d id %d buffer_size: %d: %s.", hdr->type, hdr->id, buffer_size, PB_GET_ERROR(&ostream)); } free(buffer); } else { RLOGE("Not sending response type %d: encoded_size: %u. commandFd: %d. encoded size result: %d", hdr->type, encoded_size, commandFd, success); } pthread_mutex_unlock(&write_lock); }
173,389
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void server_real_connect(SERVER_REC *server, IPADDR *ip, const char *unix_socket) { GIOChannel *handle; IPADDR *own_ip = NULL; const char *errmsg; char *errmsg2; char ipaddr[MAX_IP_LEN]; int port; g_return_if_fail(ip != NULL || unix_socket != NULL); signal_emit("server connecting", 2, server, ip); if (server->connrec->no_connect) return; if (ip != NULL) { own_ip = ip == NULL ? NULL : (IPADDR_IS_V6(ip) ? server->connrec->own_ip6 : server->connrec->own_ip4); port = server->connrec->proxy != NULL ? server->connrec->proxy_port : server->connrec->port; handle = server->connrec->use_ssl ? net_connect_ip_ssl(ip, port, own_ip, server->connrec->ssl_cert, server->connrec->ssl_pkey, server->connrec->ssl_cafile, server->connrec->ssl_capath, server->connrec->ssl_verify) : net_connect_ip(ip, port, own_ip); } else { handle = net_connect_unix(unix_socket); } if (handle == NULL) { /* failed */ errmsg = g_strerror(errno); errmsg2 = NULL; if (errno == EADDRNOTAVAIL) { if (own_ip != NULL) { /* show the IP which is causing the error */ net_ip2host(own_ip, ipaddr); errmsg2 = g_strconcat(errmsg, ": ", ipaddr, NULL); } server->no_reconnect = TRUE; } if (server->connrec->use_ssl && errno == ENOSYS) server->no_reconnect = TRUE; server->connection_lost = TRUE; server_connect_failed(server, errmsg2 ? errmsg2 : errmsg); g_free(errmsg2); } else { server->handle = net_sendbuffer_create(handle, 0); #ifdef HAVE_OPENSSL if (server->connrec->use_ssl) server_connect_callback_init_ssl(server, handle); else #endif server->connect_tag = g_input_add(handle, G_INPUT_WRITE | G_INPUT_READ, (GInputFunction) server_connect_callback_init, server); } } Commit Message: Check if an SSL certificate matches the hostname of the server we are connecting to git-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564 CWE ID: CWE-20
static void server_real_connect(SERVER_REC *server, IPADDR *ip, const char *unix_socket) { GIOChannel *handle; IPADDR *own_ip = NULL; const char *errmsg; char *errmsg2; char ipaddr[MAX_IP_LEN]; int port; g_return_if_fail(ip != NULL || unix_socket != NULL); signal_emit("server connecting", 2, server, ip); if (server->connrec->no_connect) return; if (ip != NULL) { own_ip = ip == NULL ? NULL : (IPADDR_IS_V6(ip) ? server->connrec->own_ip6 : server->connrec->own_ip4); port = server->connrec->proxy != NULL ? server->connrec->proxy_port : server->connrec->port; handle = server->connrec->use_ssl ? net_connect_ip_ssl(ip, port, server->connrec->address, own_ip, server->connrec->ssl_cert, server->connrec->ssl_pkey, server->connrec->ssl_cafile, server->connrec->ssl_capath, server->connrec->ssl_verify) : net_connect_ip(ip, port, own_ip); } else { handle = net_connect_unix(unix_socket); } if (handle == NULL) { /* failed */ errmsg = g_strerror(errno); errmsg2 = NULL; if (errno == EADDRNOTAVAIL) { if (own_ip != NULL) { /* show the IP which is causing the error */ net_ip2host(own_ip, ipaddr); errmsg2 = g_strconcat(errmsg, ": ", ipaddr, NULL); } server->no_reconnect = TRUE; } if (server->connrec->use_ssl && errno == ENOSYS) server->no_reconnect = TRUE; server->connection_lost = TRUE; server_connect_failed(server, errmsg2 ? errmsg2 : errmsg); g_free(errmsg2); } else { server->handle = net_sendbuffer_create(handle, 0); #ifdef HAVE_OPENSSL if (server->connrec->use_ssl) server_connect_callback_init_ssl(server, handle); else #endif server->connect_tag = g_input_add(handle, G_INPUT_WRITE | G_INPUT_READ, (GInputFunction) server_connect_callback_init, server); } }
165,520
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ClipboardMessageFilter::OnWriteObjectsSync( const ui::Clipboard::ObjectMap& objects, base::SharedMemoryHandle bitmap_handle) { DCHECK(base::SharedMemory::IsHandleValid(bitmap_handle)) << "Bad bitmap handle"; scoped_ptr<ui::Clipboard::ObjectMap> long_living_objects( new ui::Clipboard::ObjectMap(objects)); if (!ui::Clipboard::ReplaceSharedMemHandle( long_living_objects.get(), bitmap_handle, PeerHandle())) return; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&WriteObjectsOnUIThread, base::Owned(long_living_objects.release()))); } Commit Message: Refactor ui::Clipboard::ObjectMap sanitization in ClipboardMsgFilter. BUG=352395 [email protected] [email protected] Review URL: https://codereview.chromium.org/200523004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@257164 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ClipboardMessageFilter::OnWriteObjectsSync( const ui::Clipboard::ObjectMap& objects, base::SharedMemoryHandle bitmap_handle) { DCHECK(base::SharedMemory::IsHandleValid(bitmap_handle)) << "Bad bitmap handle"; scoped_ptr<ui::Clipboard::ObjectMap> long_living_objects( new ui::Clipboard::ObjectMap(objects)); SanitizeObjectMap(long_living_objects.get(), kAllowBitmap); if (!ui::Clipboard::ReplaceSharedMemHandle( long_living_objects.get(), bitmap_handle, PeerHandle())) return; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&WriteObjectsOnUIThread, base::Owned(long_living_objects.release()))); }
171,692
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static dma_addr_t dma_map_xdr(struct svcxprt_rdma *xprt, struct xdr_buf *xdr, u32 xdr_off, size_t len, int dir) { struct page *page; dma_addr_t dma_addr; if (xdr_off < xdr->head[0].iov_len) { /* This offset is in the head */ xdr_off += (unsigned long)xdr->head[0].iov_base & ~PAGE_MASK; page = virt_to_page(xdr->head[0].iov_base); } else { xdr_off -= xdr->head[0].iov_len; if (xdr_off < xdr->page_len) { /* This offset is in the page list */ xdr_off += xdr->page_base; page = xdr->pages[xdr_off >> PAGE_SHIFT]; xdr_off &= ~PAGE_MASK; } else { /* This offset is in the tail */ xdr_off -= xdr->page_len; xdr_off += (unsigned long) xdr->tail[0].iov_base & ~PAGE_MASK; page = virt_to_page(xdr->tail[0].iov_base); } } dma_addr = ib_dma_map_page(xprt->sc_cm_id->device, page, xdr_off, min_t(size_t, PAGE_SIZE, len), dir); return dma_addr; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
static dma_addr_t dma_map_xdr(struct svcxprt_rdma *xprt, /* The client provided a Write list in the Call message. Fill in * the segments in the first Write chunk in the Reply's transport * header with the number of bytes consumed in each segment. * Remaining chunks are returned unused. * * Assumptions: * - Client has provided only one Write chunk */ static void svc_rdma_xdr_encode_write_list(__be32 *rdma_resp, __be32 *wr_ch, unsigned int consumed) { unsigned int nsegs; __be32 *p, *q; /* RPC-over-RDMA V1 replies never have a Read list. */ p = rdma_resp + rpcrdma_fixed_maxsz + 1; q = wr_ch; while (*q != xdr_zero) { nsegs = xdr_encode_write_chunk(p, q, consumed); q += 2 + nsegs * rpcrdma_segment_maxsz; p += 2 + nsegs * rpcrdma_segment_maxsz; consumed = 0; } /* Terminate Write list */ *p++ = xdr_zero; /* Reply chunk discriminator; may be replaced later */ *p = xdr_zero; } /* The client provided a Reply chunk in the Call message. Fill in * the segments in the Reply chunk in the Reply message with the * number of bytes consumed in each segment. * * Assumptions: * - Reply can always fit in the provided Reply chunk */ static void svc_rdma_xdr_encode_reply_chunk(__be32 *rdma_resp, __be32 *rp_ch, unsigned int consumed) { __be32 *p; /* Find the Reply chunk in the Reply's xprt header. * RPC-over-RDMA V1 replies never have a Read list. */ p = rdma_resp + rpcrdma_fixed_maxsz + 1; /* Skip past Write list */ while (*p++ != xdr_zero) p += 1 + be32_to_cpup(p) * rpcrdma_segment_maxsz; xdr_encode_write_chunk(p, rp_ch, consumed); }
168,166
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftMPEG2::onQueueFilled(OMX_U32 portIndex) { UNUSED(portIndex); if (mOutputPortSettingsChange != NONE) { return; } List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); /* If input EOS is seen and decoder is not in flush mode, * set the decoder in flush mode. * There can be a case where EOS is sent along with last picture data * In that case, only after decoding that input data, decoder has to be * put in flush. This case is handled here */ if (mReceivedEOS && !mIsInFlush) { setFlushMode(); } while (!outQueue.empty()) { BufferInfo *inInfo; OMX_BUFFERHEADERTYPE *inHeader; BufferInfo *outInfo; OMX_BUFFERHEADERTYPE *outHeader; size_t timeStampIx; inInfo = NULL; inHeader = NULL; if (!mIsInFlush) { if (!inQueue.empty()) { inInfo = *inQueue.begin(); inHeader = inInfo->mHeader; } else { break; } } outInfo = *outQueue.begin(); outHeader = outInfo->mHeader; outHeader->nFlags = 0; outHeader->nTimeStamp = 0; outHeader->nOffset = 0; if (inHeader != NULL && (inHeader->nFlags & OMX_BUFFERFLAG_EOS)) { mReceivedEOS = true; if (inHeader->nFilledLen == 0) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); inHeader = NULL; setFlushMode(); } } if (mInitNeeded && !mIsInFlush) { bool portWillReset = false; handlePortSettingsChange(&portWillReset, mNewWidth, mNewHeight); CHECK_EQ(reInitDecoder(), (status_t)OK); return; } /* Get a free slot in timestamp array to hold input timestamp */ { size_t i; timeStampIx = 0; for (i = 0; i < MAX_TIME_STAMPS; i++) { if (!mTimeStampsValid[i]) { timeStampIx = i; break; } } if (inHeader != NULL) { mTimeStampsValid[timeStampIx] = true; mTimeStamps[timeStampIx] = inHeader->nTimeStamp; } } { ivd_video_decode_ip_t s_dec_ip; ivd_video_decode_op_t s_dec_op; WORD32 timeDelay, timeTaken; size_t sizeY, sizeUV; setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx); DUMP_TO_FILE(mInFile, s_dec_ip.pv_stream_buffer, s_dec_ip.u4_num_Bytes); if (s_dec_ip.u4_num_Bytes > 0) { char *ptr = (char *)s_dec_ip.pv_stream_buffer; } GETTIME(&mTimeStart, NULL); /* Compute time elapsed between end of previous decode() * to start of current decode() */ TIME_DIFF(mTimeEnd, mTimeStart, timeDelay); IV_API_CALL_STATUS_T status; status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); bool unsupportedDimensions = (IMPEG2D_UNSUPPORTED_DIMENSIONS == s_dec_op.u4_error_code); bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF)); GETTIME(&mTimeEnd, NULL); /* Compute time taken for decode() */ TIME_DIFF(mTimeStart, mTimeEnd, timeTaken); ALOGV("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay, s_dec_op.u4_num_bytes_consumed); if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) { mFlushNeeded = true; } if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) { /* If the input did not contain picture data, then ignore * the associated timestamp */ mTimeStampsValid[timeStampIx] = false; } if (unsupportedDimensions && !mFlushNeeded) { bool portWillReset = false; handlePortSettingsChange(&portWillReset, s_dec_op.u4_pic_wd, s_dec_op.u4_pic_ht); CHECK_EQ(reInitDecoder(), (status_t)OK); setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx); ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); return; } if (mChangingResolution && !s_dec_op.u4_output_present) { mChangingResolution = false; resetDecoder(); resetPlugin(); continue; } if (unsupportedDimensions || resChanged) { mChangingResolution = true; if (mFlushNeeded) { setFlushMode(); } if (unsupportedDimensions) { mNewWidth = s_dec_op.u4_pic_wd; mNewHeight = s_dec_op.u4_pic_ht; mInitNeeded = true; } continue; } if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) { uint32_t width = s_dec_op.u4_pic_wd; uint32_t height = s_dec_op.u4_pic_ht; bool portWillReset = false; handlePortSettingsChange(&portWillReset, width, height); if (portWillReset) { resetDecoder(); return; } } if (s_dec_op.u4_output_present) { size_t timeStampIdx; outHeader->nFilledLen = (mWidth * mHeight * 3) / 2; timeStampIdx = getMinTimestampIdx(mTimeStamps, mTimeStampsValid); outHeader->nTimeStamp = mTimeStamps[timeStampIdx]; mTimeStampsValid[timeStampIdx] = false; /* mWaitForI waits for the first I picture. Once made FALSE, it has to remain false till explicitly set to TRUE. */ mWaitForI = mWaitForI && !(IV_I_FRAME == s_dec_op.e_pic_type); if (mWaitForI) { s_dec_op.u4_output_present = false; } else { ALOGV("Output timestamp: %lld, res: %ux%u", (long long)outHeader->nTimeStamp, mWidth, mHeight); DUMP_TO_FILE(mOutFile, outHeader->pBuffer, outHeader->nFilledLen); outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } } else { /* If in flush mode and no output is returned by the codec, * then come out of flush mode */ mIsInFlush = false; /* If EOS was recieved on input port and there is no output * from the codec, then signal EOS on output port */ if (mReceivedEOS) { outHeader->nFilledLen = 0; outHeader->nFlags |= OMX_BUFFERFLAG_EOS; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; resetPlugin(); } } } if (inHeader != NULL) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } } } Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec Bug: 27833616 Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738 (cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d) CWE ID: CWE-20
void SoftMPEG2::onQueueFilled(OMX_U32 portIndex) { UNUSED(portIndex); if (mOutputPortSettingsChange != NONE) { return; } List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex); List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); /* If input EOS is seen and decoder is not in flush mode, * set the decoder in flush mode. * There can be a case where EOS is sent along with last picture data * In that case, only after decoding that input data, decoder has to be * put in flush. This case is handled here */ if (mReceivedEOS && !mIsInFlush) { setFlushMode(); } while (!outQueue.empty()) { BufferInfo *inInfo; OMX_BUFFERHEADERTYPE *inHeader; BufferInfo *outInfo; OMX_BUFFERHEADERTYPE *outHeader; size_t timeStampIx; inInfo = NULL; inHeader = NULL; if (!mIsInFlush) { if (!inQueue.empty()) { inInfo = *inQueue.begin(); inHeader = inInfo->mHeader; } else { break; } } outInfo = *outQueue.begin(); outHeader = outInfo->mHeader; outHeader->nFlags = 0; outHeader->nTimeStamp = 0; outHeader->nOffset = 0; if (inHeader != NULL && (inHeader->nFlags & OMX_BUFFERFLAG_EOS)) { mReceivedEOS = true; if (inHeader->nFilledLen == 0) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); inHeader = NULL; setFlushMode(); } } if (mInitNeeded && !mIsInFlush) { bool portWillReset = false; handlePortSettingsChange(&portWillReset, mNewWidth, mNewHeight); CHECK_EQ(reInitDecoder(), (status_t)OK); return; } /* Get a free slot in timestamp array to hold input timestamp */ { size_t i; timeStampIx = 0; for (i = 0; i < MAX_TIME_STAMPS; i++) { if (!mTimeStampsValid[i]) { timeStampIx = i; break; } } if (inHeader != NULL) { mTimeStampsValid[timeStampIx] = true; mTimeStamps[timeStampIx] = inHeader->nTimeStamp; } } { ivd_video_decode_ip_t s_dec_ip; ivd_video_decode_op_t s_dec_op; WORD32 timeDelay, timeTaken; size_t sizeY, sizeUV; if (!setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx)) { ALOGE("Decoder arg setup failed"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); return; } DUMP_TO_FILE(mInFile, s_dec_ip.pv_stream_buffer, s_dec_ip.u4_num_Bytes); if (s_dec_ip.u4_num_Bytes > 0) { char *ptr = (char *)s_dec_ip.pv_stream_buffer; } GETTIME(&mTimeStart, NULL); /* Compute time elapsed between end of previous decode() * to start of current decode() */ TIME_DIFF(mTimeEnd, mTimeStart, timeDelay); IV_API_CALL_STATUS_T status; status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); bool unsupportedDimensions = (IMPEG2D_UNSUPPORTED_DIMENSIONS == s_dec_op.u4_error_code); bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF)); GETTIME(&mTimeEnd, NULL); /* Compute time taken for decode() */ TIME_DIFF(mTimeStart, mTimeEnd, timeTaken); ALOGV("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay, s_dec_op.u4_num_bytes_consumed); if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) { mFlushNeeded = true; } if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) { /* If the input did not contain picture data, then ignore * the associated timestamp */ mTimeStampsValid[timeStampIx] = false; } if (unsupportedDimensions && !mFlushNeeded) { bool portWillReset = false; handlePortSettingsChange(&portWillReset, s_dec_op.u4_pic_wd, s_dec_op.u4_pic_ht); CHECK_EQ(reInitDecoder(), (status_t)OK); if (setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx)) { ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); } return; } if (mChangingResolution && !s_dec_op.u4_output_present) { mChangingResolution = false; resetDecoder(); resetPlugin(); continue; } if (unsupportedDimensions || resChanged) { mChangingResolution = true; if (mFlushNeeded) { setFlushMode(); } if (unsupportedDimensions) { mNewWidth = s_dec_op.u4_pic_wd; mNewHeight = s_dec_op.u4_pic_ht; mInitNeeded = true; } continue; } if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) { uint32_t width = s_dec_op.u4_pic_wd; uint32_t height = s_dec_op.u4_pic_ht; bool portWillReset = false; handlePortSettingsChange(&portWillReset, width, height); if (portWillReset) { resetDecoder(); return; } } if (s_dec_op.u4_output_present) { size_t timeStampIdx; outHeader->nFilledLen = (mWidth * mHeight * 3) / 2; timeStampIdx = getMinTimestampIdx(mTimeStamps, mTimeStampsValid); outHeader->nTimeStamp = mTimeStamps[timeStampIdx]; mTimeStampsValid[timeStampIdx] = false; /* mWaitForI waits for the first I picture. Once made FALSE, it has to remain false till explicitly set to TRUE. */ mWaitForI = mWaitForI && !(IV_I_FRAME == s_dec_op.e_pic_type); if (mWaitForI) { s_dec_op.u4_output_present = false; } else { ALOGV("Output timestamp: %lld, res: %ux%u", (long long)outHeader->nTimeStamp, mWidth, mHeight); DUMP_TO_FILE(mOutFile, outHeader->pBuffer, outHeader->nFilledLen); outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } } else { /* If in flush mode and no output is returned by the codec, * then come out of flush mode */ mIsInFlush = false; /* If EOS was recieved on input port and there is no output * from the codec, then signal EOS on output port */ if (mReceivedEOS) { outHeader->nFilledLen = 0; outHeader->nFlags |= OMX_BUFFERFLAG_EOS; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; resetPlugin(); } } } if (inHeader != NULL) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } } }
174,183
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xfs_attr3_leaf_flipflags( struct xfs_da_args *args) { struct xfs_attr_leafblock *leaf1; struct xfs_attr_leafblock *leaf2; struct xfs_attr_leaf_entry *entry1; struct xfs_attr_leaf_entry *entry2; struct xfs_attr_leaf_name_remote *name_rmt; struct xfs_buf *bp1; struct xfs_buf *bp2; int error; #ifdef DEBUG struct xfs_attr3_icleaf_hdr ichdr1; struct xfs_attr3_icleaf_hdr ichdr2; xfs_attr_leaf_name_local_t *name_loc; int namelen1, namelen2; char *name1, *name2; #endif /* DEBUG */ trace_xfs_attr_leaf_flipflags(args); /* * Read the block containing the "old" attr */ error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp1); if (error) return error; /* * Read the block containing the "new" attr, if it is different */ if (args->blkno2 != args->blkno) { error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno2, -1, &bp2); if (error) return error; } else { bp2 = bp1; } leaf1 = bp1->b_addr; entry1 = &xfs_attr3_leaf_entryp(leaf1)[args->index]; leaf2 = bp2->b_addr; entry2 = &xfs_attr3_leaf_entryp(leaf2)[args->index2]; #ifdef DEBUG xfs_attr3_leaf_hdr_from_disk(&ichdr1, leaf1); ASSERT(args->index < ichdr1.count); ASSERT(args->index >= 0); xfs_attr3_leaf_hdr_from_disk(&ichdr2, leaf2); ASSERT(args->index2 < ichdr2.count); ASSERT(args->index2 >= 0); if (entry1->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf1, args->index); namelen1 = name_loc->namelen; name1 = (char *)name_loc->nameval; } else { name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index); namelen1 = name_rmt->namelen; name1 = (char *)name_rmt->name; } if (entry2->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf2, args->index2); namelen2 = name_loc->namelen; name2 = (char *)name_loc->nameval; } else { name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2); namelen2 = name_rmt->namelen; name2 = (char *)name_rmt->name; } ASSERT(be32_to_cpu(entry1->hashval) == be32_to_cpu(entry2->hashval)); ASSERT(namelen1 == namelen2); ASSERT(memcmp(name1, name2, namelen1) == 0); #endif /* DEBUG */ ASSERT(entry1->flags & XFS_ATTR_INCOMPLETE); ASSERT((entry2->flags & XFS_ATTR_INCOMPLETE) == 0); entry1->flags &= ~XFS_ATTR_INCOMPLETE; xfs_trans_log_buf(args->trans, bp1, XFS_DA_LOGRANGE(leaf1, entry1, sizeof(*entry1))); if (args->rmtblkno) { ASSERT((entry1->flags & XFS_ATTR_LOCAL) == 0); name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index); name_rmt->valueblk = cpu_to_be32(args->rmtblkno); name_rmt->valuelen = cpu_to_be32(args->valuelen); xfs_trans_log_buf(args->trans, bp1, XFS_DA_LOGRANGE(leaf1, name_rmt, sizeof(*name_rmt))); } entry2->flags |= XFS_ATTR_INCOMPLETE; xfs_trans_log_buf(args->trans, bp2, XFS_DA_LOGRANGE(leaf2, entry2, sizeof(*entry2))); if ((entry2->flags & XFS_ATTR_LOCAL) == 0) { name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2); name_rmt->valueblk = 0; name_rmt->valuelen = 0; xfs_trans_log_buf(args->trans, bp2, XFS_DA_LOGRANGE(leaf2, name_rmt, sizeof(*name_rmt))); } /* * Commit the flag value change and start the next trans in series. */ error = xfs_trans_roll(&args->trans, args->dp); return error; } Commit Message: xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Brian Foster <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-19
xfs_attr3_leaf_flipflags( struct xfs_da_args *args) { struct xfs_attr_leafblock *leaf1; struct xfs_attr_leafblock *leaf2; struct xfs_attr_leaf_entry *entry1; struct xfs_attr_leaf_entry *entry2; struct xfs_attr_leaf_name_remote *name_rmt; struct xfs_buf *bp1; struct xfs_buf *bp2; int error; #ifdef DEBUG struct xfs_attr3_icleaf_hdr ichdr1; struct xfs_attr3_icleaf_hdr ichdr2; xfs_attr_leaf_name_local_t *name_loc; int namelen1, namelen2; char *name1, *name2; #endif /* DEBUG */ trace_xfs_attr_leaf_flipflags(args); /* * Read the block containing the "old" attr */ error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno, -1, &bp1); if (error) return error; /* * Read the block containing the "new" attr, if it is different */ if (args->blkno2 != args->blkno) { error = xfs_attr3_leaf_read(args->trans, args->dp, args->blkno2, -1, &bp2); if (error) return error; } else { bp2 = bp1; } leaf1 = bp1->b_addr; entry1 = &xfs_attr3_leaf_entryp(leaf1)[args->index]; leaf2 = bp2->b_addr; entry2 = &xfs_attr3_leaf_entryp(leaf2)[args->index2]; #ifdef DEBUG xfs_attr3_leaf_hdr_from_disk(&ichdr1, leaf1); ASSERT(args->index < ichdr1.count); ASSERT(args->index >= 0); xfs_attr3_leaf_hdr_from_disk(&ichdr2, leaf2); ASSERT(args->index2 < ichdr2.count); ASSERT(args->index2 >= 0); if (entry1->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf1, args->index); namelen1 = name_loc->namelen; name1 = (char *)name_loc->nameval; } else { name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index); namelen1 = name_rmt->namelen; name1 = (char *)name_rmt->name; } if (entry2->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf2, args->index2); namelen2 = name_loc->namelen; name2 = (char *)name_loc->nameval; } else { name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2); namelen2 = name_rmt->namelen; name2 = (char *)name_rmt->name; } ASSERT(be32_to_cpu(entry1->hashval) == be32_to_cpu(entry2->hashval)); ASSERT(namelen1 == namelen2); ASSERT(memcmp(name1, name2, namelen1) == 0); #endif /* DEBUG */ ASSERT(entry1->flags & XFS_ATTR_INCOMPLETE); ASSERT((entry2->flags & XFS_ATTR_INCOMPLETE) == 0); entry1->flags &= ~XFS_ATTR_INCOMPLETE; xfs_trans_log_buf(args->trans, bp1, XFS_DA_LOGRANGE(leaf1, entry1, sizeof(*entry1))); if (args->rmtblkno) { ASSERT((entry1->flags & XFS_ATTR_LOCAL) == 0); name_rmt = xfs_attr3_leaf_name_remote(leaf1, args->index); name_rmt->valueblk = cpu_to_be32(args->rmtblkno); name_rmt->valuelen = cpu_to_be32(args->rmtvaluelen); xfs_trans_log_buf(args->trans, bp1, XFS_DA_LOGRANGE(leaf1, name_rmt, sizeof(*name_rmt))); } entry2->flags |= XFS_ATTR_INCOMPLETE; xfs_trans_log_buf(args->trans, bp2, XFS_DA_LOGRANGE(leaf2, entry2, sizeof(*entry2))); if ((entry2->flags & XFS_ATTR_LOCAL) == 0) { name_rmt = xfs_attr3_leaf_name_remote(leaf2, args->index2); name_rmt->valueblk = 0; name_rmt->valuelen = 0; xfs_trans_log_buf(args->trans, bp2, XFS_DA_LOGRANGE(leaf2, name_rmt, sizeof(*name_rmt))); } /* * Commit the flag value change and start the next trans in series. */ error = xfs_trans_roll(&args->trans, args->dp); return error; }
166,735
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct key *find_keyring_by_name(const char *name, bool skip_perm_check) { struct key *keyring; int bucket; if (!name) return ERR_PTR(-EINVAL); bucket = keyring_hash(name); read_lock(&keyring_name_lock); if (keyring_name_hash[bucket].next) { /* search this hash bucket for a keyring with a matching name * that's readable and that hasn't been revoked */ list_for_each_entry(keyring, &keyring_name_hash[bucket], name_link ) { if (!kuid_has_mapping(current_user_ns(), keyring->user->uid)) continue; if (test_bit(KEY_FLAG_REVOKED, &keyring->flags)) continue; if (strcmp(keyring->description, name) != 0) continue; if (!skip_perm_check && key_permission(make_key_ref(keyring, 0), KEY_NEED_SEARCH) < 0) continue; /* we've got a match but we might end up racing with * key_cleanup() if the keyring is currently 'dead' * (ie. it has a zero usage count) */ if (!refcount_inc_not_zero(&keyring->usage)) continue; keyring->last_used_at = current_kernel_time().tv_sec; goto out; } } keyring = ERR_PTR(-ENOKEY); out: read_unlock(&keyring_name_lock); return keyring; } Commit Message: KEYS: prevent creating a different user's keyrings It was possible for an unprivileged user to create the user and user session keyrings for another user. For example: sudo -u '#3000' sh -c 'keyctl add keyring _uid.4000 "" @u keyctl add keyring _uid_ses.4000 "" @u sleep 15' & sleep 1 sudo -u '#4000' keyctl describe @u sudo -u '#4000' keyctl describe @us This is problematic because these "fake" keyrings won't have the right permissions. In particular, the user who created them first will own them and will have full access to them via the possessor permissions, which can be used to compromise the security of a user's keys: -4: alswrv-----v------------ 3000 0 keyring: _uid.4000 -5: alswrv-----v------------ 3000 0 keyring: _uid_ses.4000 Fix it by marking user and user session keyrings with a flag KEY_FLAG_UID_KEYRING. Then, when searching for a user or user session keyring by name, skip all keyrings that don't have the flag set. Fixes: 69664cf16af4 ("keys: don't generate user and user session keyrings unless they're accessed") Cc: <[email protected]> [v2.6.26+] Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> CWE ID:
struct key *find_keyring_by_name(const char *name, bool skip_perm_check) struct key *find_keyring_by_name(const char *name, bool uid_keyring) { struct key *keyring; int bucket; if (!name) return ERR_PTR(-EINVAL); bucket = keyring_hash(name); read_lock(&keyring_name_lock); if (keyring_name_hash[bucket].next) { /* search this hash bucket for a keyring with a matching name * that's readable and that hasn't been revoked */ list_for_each_entry(keyring, &keyring_name_hash[bucket], name_link ) { if (!kuid_has_mapping(current_user_ns(), keyring->user->uid)) continue; if (test_bit(KEY_FLAG_REVOKED, &keyring->flags)) continue; if (strcmp(keyring->description, name) != 0) continue; if (uid_keyring) { if (!test_bit(KEY_FLAG_UID_KEYRING, &keyring->flags)) continue; } else { if (key_permission(make_key_ref(keyring, 0), KEY_NEED_SEARCH) < 0) continue; } /* we've got a match but we might end up racing with * key_cleanup() if the keyring is currently 'dead' * (ie. it has a zero usage count) */ if (!refcount_inc_not_zero(&keyring->usage)) continue; keyring->last_used_at = current_kernel_time().tv_sec; goto out; } } keyring = ERR_PTR(-ENOKEY); out: read_unlock(&keyring_name_lock); return keyring; }
169,375
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SpdyWriteQueue::Clear() { CHECK(!removing_writes_); removing_writes_ = true; for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) { for (std::deque<PendingWrite>::iterator it = queue_[i].begin(); it != queue_[i].end(); ++it) { delete it->frame_producer; } queue_[i].clear(); } removing_writes_ = false; } Commit Message: These can post callbacks which re-enter into SpdyWriteQueue. BUG=369539 Review URL: https://codereview.chromium.org/265933007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268730 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void SpdyWriteQueue::Clear() { CHECK(!removing_writes_); removing_writes_ = true; std::vector<SpdyBufferProducer*> erased_buffer_producers; for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) { for (std::deque<PendingWrite>::iterator it = queue_[i].begin(); it != queue_[i].end(); ++it) { erased_buffer_producers.push_back(it->frame_producer); } queue_[i].clear(); } removing_writes_ = false; STLDeleteElements(&erased_buffer_producers); // Invokes callbacks. }
171,673
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PepperMediaDeviceManager* PepperPlatformVideoCapture::GetMediaDeviceManager() { RenderFrameImpl* const render_frame = RenderFrameImpl::FromRoutingID(render_frame_id_); return render_frame ? PepperMediaDeviceManager::GetForRenderFrame(render_frame) : NULL; } Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399
PepperMediaDeviceManager* PepperPlatformVideoCapture::GetMediaDeviceManager() { RenderFrameImpl* const render_frame = RenderFrameImpl::FromRoutingID(render_frame_id_); return render_frame ? PepperMediaDeviceManager::GetForRenderFrame(render_frame).get() : NULL; }
171,610
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_module_get_supported_key_sizes) { int i, count = 0; int *key_sizes; MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) array_init(return_value); key_sizes = mcrypt_module_get_algo_supported_key_sizes(module, dir, &count); for (i = 0; i < count; i++) { add_index_long(return_value, i, key_sizes[i]); } mcrypt_free(key_sizes); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_get_supported_key_sizes) { int i, count = 0; int *key_sizes; MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) array_init(return_value); key_sizes = mcrypt_module_get_algo_supported_key_sizes(module, dir, &count); for (i = 0; i < count; i++) { add_index_long(return_value, i, key_sizes[i]); } mcrypt_free(key_sizes); }
167,101
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: auth_password(Authctxt *authctxt, const char *password) { struct passwd * pw = authctxt->pw; int result, ok = authctxt->valid; #if defined(USE_SHADOW) && defined(HAS_SHADOW_EXPIRE) static int expire_checked = 0; #endif #ifndef HAVE_CYGWIN if (pw->pw_uid == 0 && options.permit_root_login != PERMIT_YES) ok = 0; #endif if (*password == '\0' && options.permit_empty_passwd == 0) return 0; #ifdef KRB5 if (options.kerberos_authentication == 1) { int ret = auth_krb5_password(authctxt, password); if (ret == 1 || ret == 0) return ret && ok; /* Fall back to ordinary passwd authentication. */ } #endif #ifdef HAVE_CYGWIN { HANDLE hToken = cygwin_logon_user(pw, password); if (hToken == INVALID_HANDLE_VALUE) return 0; cygwin_set_impersonation_token(hToken); return ok; } #endif #ifdef USE_PAM if (options.use_pam) return (sshpam_auth_passwd(authctxt, password) && ok); #endif #if defined(USE_SHADOW) && defined(HAS_SHADOW_EXPIRE) if (!expire_checked) { expire_checked = 1; if (auth_shadow_pwexpired(authctxt)) authctxt->force_pwchange = 1; } #endif result = sys_auth_passwd(authctxt, password); if (authctxt->force_pwchange) disable_forwarding(); return (result && ok); } Commit Message: upstream commit Skip passwords longer than 1k in length so clients can't easily DoS sshd by sending very long passwords, causing it to spend CPU hashing them. feedback djm@, ok markus@. Brought to our attention by tomas.kuthan at oracle.com, shilei-c at 360.cn and coredump at autistici.org Upstream-ID: d0af7d4a2190b63ba1d38eec502bc4be0be9e333 CWE ID: CWE-20
auth_password(Authctxt *authctxt, const char *password) { struct passwd * pw = authctxt->pw; int result, ok = authctxt->valid; #if defined(USE_SHADOW) && defined(HAS_SHADOW_EXPIRE) static int expire_checked = 0; #endif if (strlen(password) > MAX_PASSWORD_LEN) return 0; #ifndef HAVE_CYGWIN if (pw->pw_uid == 0 && options.permit_root_login != PERMIT_YES) ok = 0; #endif if (*password == '\0' && options.permit_empty_passwd == 0) return 0; #ifdef KRB5 if (options.kerberos_authentication == 1) { int ret = auth_krb5_password(authctxt, password); if (ret == 1 || ret == 0) return ret && ok; /* Fall back to ordinary passwd authentication. */ } #endif #ifdef HAVE_CYGWIN { HANDLE hToken = cygwin_logon_user(pw, password); if (hToken == INVALID_HANDLE_VALUE) return 0; cygwin_set_impersonation_token(hToken); return ok; } #endif #ifdef USE_PAM if (options.use_pam) return (sshpam_auth_passwd(authctxt, password) && ok); #endif #if defined(USE_SHADOW) && defined(HAS_SHADOW_EXPIRE) if (!expire_checked) { expire_checked = 1; if (auth_shadow_pwexpired(authctxt)) authctxt->force_pwchange = 1; } #endif result = sys_auth_passwd(authctxt, password); if (authctxt->force_pwchange) disable_forwarding(); return (result && ok); }
166,998
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: XGetFeedbackControl( register Display *dpy, XDevice *dev, int *num_feedbacks) { XFeedbackState *Feedback = NULL; XFeedbackState *Sav = NULL; xFeedbackState *f = NULL; xFeedbackState *sav = NULL; xGetFeedbackControlReq *req; xGetFeedbackControlReply rep; XExtDisplayInfo *info = XInput_find_display(dpy); LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return NULL; GetReq(GetFeedbackControl, req); req->reqType = info->codes->major_opcode; req->ReqType = X_GetFeedbackControl; req->deviceid = dev->device_id; if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) goto out; if (rep.length > 0) { unsigned long nbytes; size_t size = 0; int i; *num_feedbacks = rep.num_feedbacks; if (rep.length < (INT_MAX >> 2)) { nbytes = rep.length << 2; f = Xmalloc(nbytes); } if (!f) { _XEatDataWords(dpy, rep.length); goto out; goto out; } sav = f; _XRead(dpy, (char *)f, nbytes); for (i = 0; i < *num_feedbacks; i++) { if (f->length > nbytes) goto out; nbytes -= f->length; break; case PtrFeedbackClass: size += sizeof(XPtrFeedbackState); break; case IntegerFeedbackClass: size += sizeof(XIntegerFeedbackState); break; case StringFeedbackClass: { xStringFeedbackState *strf = (xStringFeedbackState *) f; case StringFeedbackClass: { xStringFeedbackState *strf = (xStringFeedbackState *) f; size += sizeof(XStringFeedbackState) + (strf->num_syms_supported * sizeof(KeySym)); } size += sizeof(XBellFeedbackState); break; default: size += f->length; break; } if (size > INT_MAX) goto out; f = (xFeedbackState *) ((char *)f + f->length); } Feedback = Xmalloc(size); if (!Feedback) goto out; Sav = Feedback; f = sav; for (i = 0; i < *num_feedbacks; i++) { switch (f->class) { case KbdFeedbackClass: { xKbdFeedbackState *k; XKbdFeedbackState *K; k = (xKbdFeedbackState *) f; K = (XKbdFeedbackState *) Feedback; K->class = k->class; K->length = sizeof(XKbdFeedbackState); K->id = k->id; K->click = k->click; K->percent = k->percent; K->pitch = k->pitch; K->duration = k->duration; K->led_mask = k->led_mask; K->global_auto_repeat = k->global_auto_repeat; memcpy((char *)&K->auto_repeats[0], (char *)&k->auto_repeats[0], 32); break; } case PtrFeedbackClass: { xPtrFeedbackState *p; XPtrFeedbackState *P; p = (xPtrFeedbackState *) f; P = (XPtrFeedbackState *) Feedback; P->class = p->class; P->length = sizeof(XPtrFeedbackState); P->id = p->id; P->accelNum = p->accelNum; P->accelDenom = p->accelDenom; P->threshold = p->threshold; break; } case IntegerFeedbackClass: { xIntegerFeedbackState *ifs; XIntegerFeedbackState *I; ifs = (xIntegerFeedbackState *) f; I = (XIntegerFeedbackState *) Feedback; I->class = ifs->class; I->length = sizeof(XIntegerFeedbackState); I->id = ifs->id; I->resolution = ifs->resolution; I->minVal = ifs->min_value; I->maxVal = ifs->max_value; break; } case StringFeedbackClass: { xStringFeedbackState *s; XStringFeedbackState *S; s = (xStringFeedbackState *) f; S = (XStringFeedbackState *) Feedback; S->class = s->class; S->length = sizeof(XStringFeedbackState) + (s->num_syms_supported * sizeof(KeySym)); S->id = s->id; S->max_symbols = s->max_symbols; S->num_syms_supported = s->num_syms_supported; S->syms_supported = (KeySym *) (S + 1); memcpy((char *)S->syms_supported, (char *)(s + 1), (S->num_syms_supported * sizeof(KeySym))); break; } case LedFeedbackClass: { xLedFeedbackState *l; XLedFeedbackState *L; l = (xLedFeedbackState *) f; L = (XLedFeedbackState *) Feedback; L->class = l->class; L->length = sizeof(XLedFeedbackState); L->id = l->id; L->led_values = l->led_values; L->led_mask = l->led_mask; break; } case BellFeedbackClass: { xBellFeedbackState *b; XBellFeedbackState *B; b = (xBellFeedbackState *) f; B = (XBellFeedbackState *) Feedback; B->class = b->class; B->length = sizeof(XBellFeedbackState); B->id = b->id; B->percent = b->percent; B->pitch = b->pitch; B->duration = b->duration; break; } default: break; } f = (xFeedbackState *) ((char *)f + f->length); Feedback = (XFeedbackState *) ((char *)Feedback + Feedback->length); } } out: XFree((char *)sav); UnlockDisplay(dpy); SyncHandle(); return (Sav); } Commit Message: CWE ID: CWE-284
XGetFeedbackControl( register Display *dpy, XDevice *dev, int *num_feedbacks) { XFeedbackState *Feedback = NULL; XFeedbackState *Sav = NULL; xFeedbackState *f = NULL; xFeedbackState *sav = NULL; char *end = NULL; xGetFeedbackControlReq *req; xGetFeedbackControlReply rep; XExtDisplayInfo *info = XInput_find_display(dpy); LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return NULL; GetReq(GetFeedbackControl, req); req->reqType = info->codes->major_opcode; req->ReqType = X_GetFeedbackControl; req->deviceid = dev->device_id; if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) goto out; if (rep.length > 0) { unsigned long nbytes; size_t size = 0; int i; *num_feedbacks = rep.num_feedbacks; if (rep.length < (INT_MAX >> 2)) { nbytes = rep.length << 2; f = Xmalloc(nbytes); } if (!f) { _XEatDataWords(dpy, rep.length); goto out; goto out; } sav = f; end = (char *)f + nbytes; _XRead(dpy, (char *)f, nbytes); for (i = 0; i < *num_feedbacks; i++) { if ((char *)f + sizeof(*f) > end || f->length == 0 || f->length > nbytes) goto out; nbytes -= f->length; break; case PtrFeedbackClass: size += sizeof(XPtrFeedbackState); break; case IntegerFeedbackClass: size += sizeof(XIntegerFeedbackState); break; case StringFeedbackClass: { xStringFeedbackState *strf = (xStringFeedbackState *) f; case StringFeedbackClass: { xStringFeedbackState *strf = (xStringFeedbackState *) f; if ((char *)f + sizeof(*strf) > end) goto out; size += sizeof(XStringFeedbackState) + (strf->num_syms_supported * sizeof(KeySym)); } size += sizeof(XBellFeedbackState); break; default: size += f->length; break; } if (size > INT_MAX) goto out; f = (xFeedbackState *) ((char *)f + f->length); } Feedback = Xmalloc(size); if (!Feedback) goto out; Sav = Feedback; f = sav; for (i = 0; i < *num_feedbacks; i++) { switch (f->class) { case KbdFeedbackClass: { xKbdFeedbackState *k; XKbdFeedbackState *K; k = (xKbdFeedbackState *) f; K = (XKbdFeedbackState *) Feedback; K->class = k->class; K->length = sizeof(XKbdFeedbackState); K->id = k->id; K->click = k->click; K->percent = k->percent; K->pitch = k->pitch; K->duration = k->duration; K->led_mask = k->led_mask; K->global_auto_repeat = k->global_auto_repeat; memcpy((char *)&K->auto_repeats[0], (char *)&k->auto_repeats[0], 32); break; } case PtrFeedbackClass: { xPtrFeedbackState *p; XPtrFeedbackState *P; p = (xPtrFeedbackState *) f; P = (XPtrFeedbackState *) Feedback; P->class = p->class; P->length = sizeof(XPtrFeedbackState); P->id = p->id; P->accelNum = p->accelNum; P->accelDenom = p->accelDenom; P->threshold = p->threshold; break; } case IntegerFeedbackClass: { xIntegerFeedbackState *ifs; XIntegerFeedbackState *I; ifs = (xIntegerFeedbackState *) f; I = (XIntegerFeedbackState *) Feedback; I->class = ifs->class; I->length = sizeof(XIntegerFeedbackState); I->id = ifs->id; I->resolution = ifs->resolution; I->minVal = ifs->min_value; I->maxVal = ifs->max_value; break; } case StringFeedbackClass: { xStringFeedbackState *s; XStringFeedbackState *S; s = (xStringFeedbackState *) f; S = (XStringFeedbackState *) Feedback; S->class = s->class; S->length = sizeof(XStringFeedbackState) + (s->num_syms_supported * sizeof(KeySym)); S->id = s->id; S->max_symbols = s->max_symbols; S->num_syms_supported = s->num_syms_supported; S->syms_supported = (KeySym *) (S + 1); memcpy((char *)S->syms_supported, (char *)(s + 1), (S->num_syms_supported * sizeof(KeySym))); break; } case LedFeedbackClass: { xLedFeedbackState *l; XLedFeedbackState *L; l = (xLedFeedbackState *) f; L = (XLedFeedbackState *) Feedback; L->class = l->class; L->length = sizeof(XLedFeedbackState); L->id = l->id; L->led_values = l->led_values; L->led_mask = l->led_mask; break; } case BellFeedbackClass: { xBellFeedbackState *b; XBellFeedbackState *B; b = (xBellFeedbackState *) f; B = (XBellFeedbackState *) Feedback; B->class = b->class; B->length = sizeof(XBellFeedbackState); B->id = b->id; B->percent = b->percent; B->pitch = b->pitch; B->duration = b->duration; break; } default: break; } f = (xFeedbackState *) ((char *)f + f->length); Feedback = (XFeedbackState *) ((char *)Feedback + Feedback->length); } } out: XFree((char *)sav); UnlockDisplay(dpy); SyncHandle(); return (Sav); }
164,919
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CrosMock::SetSpeechSynthesisLibraryExpectations() { InSequence s; EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking()) .WillOnce(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_)) .WillOnce(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking()) .Times(AnyNumber()) .WillRepeatedly(Return(true)); EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking()) .WillOnce(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_)) .WillOnce(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking()) .WillOnce(Return(true)) .WillOnce(Return(true)) .WillOnce(Return(false)) .RetiresOnSaturation(); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void CrosMock::SetSpeechSynthesisLibraryExpectations() { InSequence s; EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking()) .WillOnce(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(*mock_speech_synthesis_library_, SetSpeakProperties(_)) .WillOnce(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_)) .WillOnce(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking()) .WillOnce(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking()) .WillOnce(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(*mock_speech_synthesis_library_, SetSpeakProperties(_)) .WillOnce(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_)) .WillOnce(Return(true)) .RetiresOnSaturation(); EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking()) .WillOnce(Return(true)) .WillOnce(Return(true)) .WillOnce(Return(false)) .RetiresOnSaturation(); }
170,372
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int sfgets(void) { struct pollfd pfd; int pollret; ssize_t readnb; signed char seen_r = 0; static size_t scanned; static size_t readnbd; if (scanned > (size_t) 0U) { /* support pipelining */ readnbd -= scanned; memmove(cmd, cmd + scanned, readnbd); /* safe */ scanned = (size_t) 0U; } pfd.fd = clientfd; #ifdef __APPLE_CC__ pfd.events = POLLIN | POLLERR | POLLHUP; #else pfd.events = POLLIN | POLLPRI | POLLERR | POLLHUP; #endif while (scanned < cmdsize) { if (scanned >= readnbd) { /* nothing left in the buffer */ pfd.revents = 0; while ((pollret = poll(&pfd, 1U, idletime * 1000UL)) < 0 && errno == EINTR); if (pollret == 0) { return -1; } if (pollret <= 0 || (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0) { return -2; } if ((pfd.revents & (POLLIN | POLLPRI)) == 0) { continue; } if (readnbd >= cmdsize) { break; } #ifdef WITH_TLS if (tls_cnx != NULL) { while ((readnb = SSL_read (tls_cnx, cmd + readnbd, cmdsize - readnbd)) < (ssize_t) 0 && errno == EINTR); } else #endif { while ((readnb = read(clientfd, cmd + readnbd, cmdsize - readnbd)) < (ssize_t) 0 && errno == EINTR); } if (readnb <= (ssize_t) 0) { return -2; } readnbd += readnb; if (readnbd > cmdsize) { return -2; } } #ifdef RFC_CONFORMANT_LINES if (seen_r != 0) { #endif if (cmd[scanned] == '\n') { #ifndef RFC_CONFORMANT_LINES if (seen_r != 0) { #endif cmd[scanned - 1U] = 0; #ifndef RFC_CONFORMANT_LINES } else { cmd[scanned] = 0; } #endif if (++scanned >= readnbd) { /* non-pipelined command */ scanned = readnbd = (size_t) 0U; } return 0; } seen_r = 0; #ifdef RFC_CONFORMANT_LINES } #endif if (ISCTRLCODE(cmd[scanned])) { if (cmd[scanned] == '\r') { seen_r = 1; } #ifdef RFC_CONFORMANT_PARSER /* disabled by default, intentionnaly */ else if (cmd[scanned] == 0) { cmd[scanned] = '\n'; } #else /* replace control chars with _ */ cmd[scanned] = '_'; #endif } scanned++; } die(421, LOG_WARNING, MSG_LINE_TOO_LONG); /* don't remove this */ return 0; /* to please GCC */ } Commit Message: Flush the command buffer after switching to TLS. Fixes a flaw similar to CVE-2011-0411. CWE ID: CWE-399
int sfgets(void) { struct pollfd pfd; int pollret; ssize_t readnb; signed char seen_r = 0; if (scanned > (size_t) 0U) { /* support pipelining */ readnbd -= scanned; memmove(cmd, cmd + scanned, readnbd); /* safe */ scanned = (size_t) 0U; } pfd.fd = clientfd; #ifdef __APPLE_CC__ pfd.events = POLLIN | POLLERR | POLLHUP; #else pfd.events = POLLIN | POLLPRI | POLLERR | POLLHUP; #endif while (scanned < cmdsize) { if (scanned >= readnbd) { /* nothing left in the buffer */ pfd.revents = 0; while ((pollret = poll(&pfd, 1U, idletime * 1000UL)) < 0 && errno == EINTR); if (pollret == 0) { return -1; } if (pollret <= 0 || (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0) { return -2; } if ((pfd.revents & (POLLIN | POLLPRI)) == 0) { continue; } if (readnbd >= cmdsize) { break; } #ifdef WITH_TLS if (tls_cnx != NULL) { while ((readnb = SSL_read (tls_cnx, cmd + readnbd, cmdsize - readnbd)) < (ssize_t) 0 && errno == EINTR); } else #endif { while ((readnb = read(clientfd, cmd + readnbd, cmdsize - readnbd)) < (ssize_t) 0 && errno == EINTR); } if (readnb <= (ssize_t) 0) { return -2; } readnbd += readnb; if (readnbd > cmdsize) { return -2; } } #ifdef RFC_CONFORMANT_LINES if (seen_r != 0) { #endif if (cmd[scanned] == '\n') { #ifndef RFC_CONFORMANT_LINES if (seen_r != 0) { #endif cmd[scanned - 1U] = 0; #ifndef RFC_CONFORMANT_LINES } else { cmd[scanned] = 0; } #endif if (++scanned >= readnbd) { /* non-pipelined command */ scanned = readnbd = (size_t) 0U; } return 0; } seen_r = 0; #ifdef RFC_CONFORMANT_LINES } #endif if (ISCTRLCODE(cmd[scanned])) { if (cmd[scanned] == '\r') { seen_r = 1; } #ifdef RFC_CONFORMANT_PARSER /* disabled by default, intentionnaly */ else if (cmd[scanned] == 0) { cmd[scanned] = '\n'; } #else /* replace control chars with _ */ cmd[scanned] = '_'; #endif } scanned++; } die(421, LOG_WARNING, MSG_LINE_TOO_LONG); /* don't remove this */ return 0; /* to please GCC */ }
165,526
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 char magick[12]; Image *image; IndexPacket index; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, number_planes_filled, one, pixel_info_length; ssize_t count, offset, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Determine if this a RLE file. */ count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,"\122\314",2) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Read image header. */ image->page.x=ReadBlobLSBShort(image); image->page.y=ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->matte=flags & 0x04 ? MagickTrue : MagickFalse; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 22) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || ((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } colormap=(unsigned char *) NULL; if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) *p++=(unsigned char) ScaleQuantumToChar(ScaleShortToQuantum( ReadBlobLSBShort(image))); } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate RLE pixels. */ if (image->matte != MagickFalse) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; number_planes_filled=(number_planes % 2 == 0) ? number_planes : number_planes+1; if ((number_pixels*number_planes_filled) != (size_t) (number_pixels* number_planes_filled)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* MagickMax(number_planes_filled,4)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info_length=image->columns*image->rows* MagickMax(number_planes_filled,4); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,pixel_info_length); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->matte == MagickFalse) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if ((offset < 0) || (offset+((size_t) operand*number_planes) > pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); operand++; offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; if ((offset < 0) || (offset+((size_t) operand*number_planes) > pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { if (IsValidColormapIndex(image,*p & mask,&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { if (IsValidColormapIndex(image,(size_t) (x*map_length+ (*p & mask)),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p); image->colormap[i].green=ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->matte == MagickFalse) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsValidColormapIndex(image,*p++,&index,exception) == MagickFalse) break; SetPixelRed(q,image->colormap[(ssize_t) index].red); if (IsValidColormapIndex(image,*p++,&index,exception) == MagickFalse) break; SetPixelGreen(q,image->colormap[(ssize_t) index].green); if (IsValidColormapIndex(image,*p++,&index,exception) == MagickFalse) break; SetPixelBlue(q,image->colormap[(ssize_t) index].blue); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelPacket *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,"\122\314",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,"\122\314",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: Check for EOF conditions for RLE image format CWE ID: CWE-20
static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 #define ThrowRLEException(exception,message) \ { \ if (colormap != (unsigned char *) NULL) \ colormap=(unsigned char *) RelinquishMagickMemory(colormap); \ if (pixel_info != (MemoryInfo *) NULL) \ pixel_info=RelinquishVirtualMemory(pixel_info); \ ThrowReaderException((exception),(message)); \ } char magick[12]; Image *image; IndexPacket index; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, number_planes_filled, one, pixel_info_length; ssize_t count, offset, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Determine if this a RLE file. */ colormap=(unsigned char *) NULL; pixel_info=(MemoryInfo *) NULL; count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,"\122\314",2) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Read image header. */ image->page.x=(ssize_t) ReadBlobLSBShort(image); image->page.y=(ssize_t) ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->matte=flags & 0x04 ? MagickTrue : MagickFalse; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 22) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || ((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); colormap=(unsigned char *) NULL; if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) { *p++=(unsigned char) ScaleQuantumToChar(ScaleShortToQuantum( ReadBlobLSBShort(image))); if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate RLE pixels. */ if (image->matte != MagickFalse) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; number_planes_filled=(number_planes % 2 == 0) ? number_planes : number_planes+1; if ((number_pixels*number_planes_filled) != (size_t) (number_pixels* number_planes_filled)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* MagickMax(number_planes_filled,4)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info_length=image->columns*image->rows* MagickMax(number_planes_filled,4); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,pixel_info_length); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->matte == MagickFalse) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane); operand++; if ((offset < 0) || ((offset+operand*number_planes) > (ssize_t) pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); operand++; offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane); if ((offset < 0) || ((offset+operand*number_planes) > (ssize_t) pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { if (IsValidColormapIndex(image,(ssize_t) (*p & mask),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { if (IsValidColormapIndex(image,(ssize_t) (x*map_length+ (*p & mask)),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p); image->colormap[i].green=ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->matte == MagickFalse) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsValidColormapIndex(image,(ssize_t) *p++,&index,exception) == MagickFalse) break; SetPixelRed(q,image->colormap[(ssize_t) index].red); if (IsValidColormapIndex(image,(ssize_t) *p++,&index,exception) == MagickFalse) break; SetPixelGreen(q,image->colormap[(ssize_t) index].green); if (IsValidColormapIndex(image,(ssize_t) *p++,&index,exception) == MagickFalse) break; SetPixelBlue(q,image->colormap[(ssize_t) index].blue); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelPacket *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,"\122\314",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,"\122\314",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,122
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { struct task_struct *tsk; struct mm_struct *mm; int fault, sig, code; if (notify_page_fault(regs, fsr)) return 0; tsk = current; mm = tsk->mm; /* * If we're in an interrupt or have no user * context, we must not take the fault.. */ if (in_atomic() || !mm) goto no_context; /* * As per x86, we may deadlock here. However, since the kernel only * validly references user space from well defined areas of the code, * we can bug out early if this is from code which shouldn't. */ if (!down_read_trylock(&mm->mmap_sem)) { if (!user_mode(regs) && !search_exception_tables(regs->ARM_pc)) goto no_context; down_read(&mm->mmap_sem); } else { /* * The above down_read_trylock() might have succeeded in * which case, we'll have missed the might_sleep() from * down_read() */ might_sleep(); #ifdef CONFIG_DEBUG_VM if (!user_mode(regs) && !search_exception_tables(regs->ARM_pc)) goto no_context; #endif } fault = __do_page_fault(mm, addr, fsr, tsk); up_read(&mm->mmap_sem); perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, addr); if (fault & VM_FAULT_MAJOR) perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0, regs, addr); else if (fault & VM_FAULT_MINOR) perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0, regs, addr); /* * Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR */ if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP | VM_FAULT_BADACCESS)))) return 0; if (fault & VM_FAULT_OOM) { /* * We ran out of memory, call the OOM killer, and return to * userspace (which will retry the fault, or kill us if we * got oom-killed) */ pagefault_out_of_memory(); return 0; } /* * If we are in kernel mode at this point, we * have no context to handle this fault with. */ if (!user_mode(regs)) goto no_context; if (fault & VM_FAULT_SIGBUS) { /* * We had some memory, but were unable to * successfully fix up this page fault. */ sig = SIGBUS; code = BUS_ADRERR; } else { /* * Something tried to access memory that * isn't in our memory map.. */ sig = SIGSEGV; code = fault == VM_FAULT_BADACCESS ? SEGV_ACCERR : SEGV_MAPERR; } __do_user_fault(tsk, addr, fsr, sig, code, regs); return 0; no_context: __do_kernel_fault(mm, addr, fsr, regs); return 0; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { struct task_struct *tsk; struct mm_struct *mm; int fault, sig, code; if (notify_page_fault(regs, fsr)) return 0; tsk = current; mm = tsk->mm; /* * If we're in an interrupt or have no user * context, we must not take the fault.. */ if (in_atomic() || !mm) goto no_context; /* * As per x86, we may deadlock here. However, since the kernel only * validly references user space from well defined areas of the code, * we can bug out early if this is from code which shouldn't. */ if (!down_read_trylock(&mm->mmap_sem)) { if (!user_mode(regs) && !search_exception_tables(regs->ARM_pc)) goto no_context; down_read(&mm->mmap_sem); } else { /* * The above down_read_trylock() might have succeeded in * which case, we'll have missed the might_sleep() from * down_read() */ might_sleep(); #ifdef CONFIG_DEBUG_VM if (!user_mode(regs) && !search_exception_tables(regs->ARM_pc)) goto no_context; #endif } fault = __do_page_fault(mm, addr, fsr, tsk); up_read(&mm->mmap_sem); perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, addr); if (fault & VM_FAULT_MAJOR) perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, addr); else if (fault & VM_FAULT_MINOR) perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, addr); /* * Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR */ if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP | VM_FAULT_BADACCESS)))) return 0; if (fault & VM_FAULT_OOM) { /* * We ran out of memory, call the OOM killer, and return to * userspace (which will retry the fault, or kill us if we * got oom-killed) */ pagefault_out_of_memory(); return 0; } /* * If we are in kernel mode at this point, we * have no context to handle this fault with. */ if (!user_mode(regs)) goto no_context; if (fault & VM_FAULT_SIGBUS) { /* * We had some memory, but were unable to * successfully fix up this page fault. */ sig = SIGBUS; code = BUS_ADRERR; } else { /* * Something tried to access memory that * isn't in our memory map.. */ sig = SIGSEGV; code = fault == VM_FAULT_BADACCESS ? SEGV_ACCERR : SEGV_MAPERR; } __do_user_fault(tsk, addr, fsr, sig, code, regs); return 0; no_context: __do_kernel_fault(mm, addr, fsr, regs); return 0; }
165,779
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void TreeNodesAdded(TreeModel* model, TreeModelNode* parent, int start, int count) { added_count_++; } Commit Message: Add OVERRIDE to ui::TreeModelObserver overridden methods. BUG=None TEST=None [email protected] Review URL: http://codereview.chromium.org/7046093 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88827 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
virtual void TreeNodesAdded(TreeModel* model, TreeModelNode* parent, virtual void TreeNodesAdded(TreeModel* model, TreeModelNode* parent, int start, int count) OVERRIDE { added_count_++; }
170,470
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: UpdateLibrary* CrosLibrary::GetUpdateLibrary() { return update_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
UpdateLibrary* CrosLibrary::GetUpdateLibrary() {
170,634
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FindBarController::UpdateFindBarForCurrentResult() { FindManager* find_manager = tab_contents_->GetFindManager(); const FindNotificationDetails& find_result = find_manager->find_result(); if (find_result.number_of_matches() > -1) { if (last_reported_matchcount_ > 0 && find_result.number_of_matches() == 1 && !find_result.final_update()) return; // Don't let interim result override match count. last_reported_matchcount_ = find_result.number_of_matches(); } find_bar_->UpdateUIForFindResult(find_result, find_manager->find_text()); } Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature. BUG=71097 TEST=zero visible change Review URL: http://codereview.chromium.org/6480117 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void FindBarController::UpdateFindBarForCurrentResult() { FindTabHelper* find_tab_helper = tab_contents_->find_tab_helper(); const FindNotificationDetails& find_result = find_tab_helper->find_result(); if (find_result.number_of_matches() > -1) { if (last_reported_matchcount_ > 0 && find_result.number_of_matches() == 1 && !find_result.final_update()) return; // Don't let interim result override match count. last_reported_matchcount_ = find_result.number_of_matches(); } find_bar_->UpdateUIForFindResult(find_result, find_tab_helper->find_text()); }
170,662
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(move_uploaded_file) { char *path, *new_path; int path_len, new_path_len; zend_bool successful = 0; #ifndef PHP_WIN32 int oldmask; int ret; #endif if (!SG(rfc1867_uploaded_files)) { RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &path, &path_len, &new_path, &new_path_len) == FAILURE) { return; } if (!zend_hash_exists(SG(rfc1867_uploaded_files), path, path_len + 1)) { RETURN_FALSE; } if (php_check_open_basedir(new_path TSRMLS_CC)) { RETURN_FALSE; } if (VCWD_RENAME(path, new_path) == 0) { successful = 1; #ifndef PHP_WIN32 oldmask = umask(077); umask(oldmask); ret = VCWD_CHMOD(new_path, 0666 & ~oldmask); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); } #endif } else if (php_copy_file_ex(path, new_path, STREAM_DISABLE_OPEN_BASEDIR TSRMLS_CC) == SUCCESS) { VCWD_UNLINK(path); successful = 1; } if (successful) { zend_hash_del(SG(rfc1867_uploaded_files), path, path_len + 1); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to move '%s' to '%s'", path, new_path); } RETURN_BOOL(successful); } Commit Message: CWE ID: CWE-264
PHP_FUNCTION(move_uploaded_file) { char *path, *new_path; int path_len, new_path_len; zend_bool successful = 0; #ifndef PHP_WIN32 int oldmask; int ret; #endif if (!SG(rfc1867_uploaded_files)) { RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sp", &path, &path_len, &new_path, &new_path_len) == FAILURE) { return; } if (!zend_hash_exists(SG(rfc1867_uploaded_files), path, path_len + 1)) { RETURN_FALSE; } if (php_check_open_basedir(new_path TSRMLS_CC)) { RETURN_FALSE; } if (VCWD_RENAME(path, new_path) == 0) { successful = 1; #ifndef PHP_WIN32 oldmask = umask(077); umask(oldmask); ret = VCWD_CHMOD(new_path, 0666 & ~oldmask); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); } #endif } else if (php_copy_file_ex(path, new_path, STREAM_DISABLE_OPEN_BASEDIR TSRMLS_CC) == SUCCESS) { VCWD_UNLINK(path); successful = 1; } if (successful) { zend_hash_del(SG(rfc1867_uploaded_files), path, path_len + 1); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to move '%s' to '%s'", path, new_path); } RETURN_BOOL(successful); }
164,751
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const { if (interstitial_page_) return interstitial_page_->GetView(); if (render_frame_host_) return render_frame_host_->GetView(); return nullptr; } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const { if (delegate_->GetInterstitialForRenderManager()) return delegate_->GetInterstitialForRenderManager()->GetView(); if (render_frame_host_) return render_frame_host_->GetView(); return nullptr; }
172,322
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int validate_camera_metadata_structure(const camera_metadata_t *metadata, const size_t *expected_size) { if (metadata == NULL) { ALOGE("%s: metadata is null!", __FUNCTION__); return ERROR; } { static const struct { const char *name; size_t alignment; } alignments[] = { { .name = "camera_metadata", .alignment = METADATA_ALIGNMENT }, { .name = "camera_metadata_buffer_entry", .alignment = ENTRY_ALIGNMENT }, { .name = "camera_metadata_data", .alignment = DATA_ALIGNMENT }, }; for (size_t i = 0; i < sizeof(alignments)/sizeof(alignments[0]); ++i) { uintptr_t aligned_ptr = ALIGN_TO(metadata, alignments[i].alignment); if ((uintptr_t)metadata != aligned_ptr) { ALOGE("%s: Metadata pointer is not aligned (actual %p, " "expected %p) to type %s", __FUNCTION__, metadata, (void*)aligned_ptr, alignments[i].name); return ERROR; } } } /** * Check that the metadata contents are correct */ if (expected_size != NULL && metadata->size > *expected_size) { ALOGE("%s: Metadata size (%" PRIu32 ") should be <= expected size (%zu)", __FUNCTION__, metadata->size, *expected_size); return ERROR; } if (metadata->entry_count > metadata->entry_capacity) { ALOGE("%s: Entry count (%" PRIu32 ") should be <= entry capacity " "(%" PRIu32 ")", __FUNCTION__, metadata->entry_count, metadata->entry_capacity); return ERROR; } const metadata_uptrdiff_t entries_end = metadata->entries_start + metadata->entry_capacity; if (entries_end < metadata->entries_start || // overflow check entries_end > metadata->data_start) { ALOGE("%s: Entry start + capacity (%" PRIu32 ") should be <= data start " "(%" PRIu32 ")", __FUNCTION__, (metadata->entries_start + metadata->entry_capacity), metadata->data_start); return ERROR; } const metadata_uptrdiff_t data_end = metadata->data_start + metadata->data_capacity; if (data_end < metadata->data_start || // overflow check data_end > metadata->size) { ALOGE("%s: Data start + capacity (%" PRIu32 ") should be <= total size " "(%" PRIu32 ")", __FUNCTION__, (metadata->data_start + metadata->data_capacity), metadata->size); return ERROR; } const metadata_size_t entry_count = metadata->entry_count; camera_metadata_buffer_entry_t *entries = get_entries(metadata); for (size_t i = 0; i < entry_count; ++i) { if ((uintptr_t)&entries[i] != ALIGN_TO(&entries[i], ENTRY_ALIGNMENT)) { ALOGE("%s: Entry index %zu had bad alignment (address %p)," " expected alignment %zu", __FUNCTION__, i, &entries[i], ENTRY_ALIGNMENT); return ERROR; } camera_metadata_buffer_entry_t entry = entries[i]; if (entry.type >= NUM_TYPES) { ALOGE("%s: Entry index %zu had a bad type %d", __FUNCTION__, i, entry.type); return ERROR; } uint32_t tag_section = entry.tag >> 16; int tag_type = get_camera_metadata_tag_type(entry.tag); if (tag_type != (int)entry.type && tag_section < VENDOR_SECTION) { ALOGE("%s: Entry index %zu had tag type %d, but the type was %d", __FUNCTION__, i, tag_type, entry.type); return ERROR; } size_t data_size; if (validate_and_calculate_camera_metadata_entry_data_size(&data_size, entry.type, entry.count) != OK) { ALOGE("%s: Entry data size is invalid. type: %u count: %u", __FUNCTION__, entry.type, entry.count); return ERROR; } if (data_size != 0) { camera_metadata_data_t *data = (camera_metadata_data_t*) (get_data(metadata) + entry.data.offset); if ((uintptr_t)data != ALIGN_TO(data, DATA_ALIGNMENT)) { ALOGE("%s: Entry index %zu had bad data alignment (address %p)," " expected align %zu, (tag name %s, data size %zu)", __FUNCTION__, i, data, DATA_ALIGNMENT, get_camera_metadata_tag_name(entry.tag) ?: "unknown", data_size); return ERROR; } size_t data_entry_end = entry.data.offset + data_size; if (data_entry_end < entry.data.offset || // overflow check data_entry_end > metadata->data_capacity) { ALOGE("%s: Entry index %zu data ends (%zu) beyond the capacity " "%" PRIu32, __FUNCTION__, i, data_entry_end, metadata->data_capacity); return ERROR; } } else if (entry.count == 0) { if (entry.data.offset != 0) { ALOGE("%s: Entry index %zu had 0 items, but offset was non-0 " "(%" PRIu32 "), tag name: %s", __FUNCTION__, i, entry.data.offset, get_camera_metadata_tag_name(entry.tag) ?: "unknown"); return ERROR; } } // else data stored inline, so we look at value which can be anything. } return OK; } Commit Message: Camera metadata: Check for inconsistent data count Resolve merge conflict for nyc-release Also check for overflow of data/entry count on append. Bug: 30591838 Change-Id: Ibf4c3c6e236cdb28234f3125055d95ef0a2416a2 CWE ID: CWE-264
int validate_camera_metadata_structure(const camera_metadata_t *metadata, const size_t *expected_size) { if (metadata == NULL) { ALOGE("%s: metadata is null!", __FUNCTION__); return ERROR; } { static const struct { const char *name; size_t alignment; } alignments[] = { { .name = "camera_metadata", .alignment = METADATA_ALIGNMENT }, { .name = "camera_metadata_buffer_entry", .alignment = ENTRY_ALIGNMENT }, { .name = "camera_metadata_data", .alignment = DATA_ALIGNMENT }, }; for (size_t i = 0; i < sizeof(alignments)/sizeof(alignments[0]); ++i) { uintptr_t aligned_ptr = ALIGN_TO(metadata, alignments[i].alignment); if ((uintptr_t)metadata != aligned_ptr) { ALOGE("%s: Metadata pointer is not aligned (actual %p, " "expected %p) to type %s", __FUNCTION__, metadata, (void*)aligned_ptr, alignments[i].name); return ERROR; } } } /** * Check that the metadata contents are correct */ if (expected_size != NULL && metadata->size > *expected_size) { ALOGE("%s: Metadata size (%" PRIu32 ") should be <= expected size (%zu)", __FUNCTION__, metadata->size, *expected_size); return ERROR; } if (metadata->entry_count > metadata->entry_capacity) { ALOGE("%s: Entry count (%" PRIu32 ") should be <= entry capacity " "(%" PRIu32 ")", __FUNCTION__, metadata->entry_count, metadata->entry_capacity); return ERROR; } if (metadata->data_count > metadata->data_capacity) { ALOGE("%s: Data count (%" PRIu32 ") should be <= data capacity " "(%" PRIu32 ")", __FUNCTION__, metadata->data_count, metadata->data_capacity); android_errorWriteLog(SN_EVENT_LOG_ID, "30591838"); return ERROR; } const metadata_uptrdiff_t entries_end = metadata->entries_start + metadata->entry_capacity; if (entries_end < metadata->entries_start || // overflow check entries_end > metadata->data_start) { ALOGE("%s: Entry start + capacity (%" PRIu32 ") should be <= data start " "(%" PRIu32 ")", __FUNCTION__, (metadata->entries_start + metadata->entry_capacity), metadata->data_start); return ERROR; } const metadata_uptrdiff_t data_end = metadata->data_start + metadata->data_capacity; if (data_end < metadata->data_start || // overflow check data_end > metadata->size) { ALOGE("%s: Data start + capacity (%" PRIu32 ") should be <= total size " "(%" PRIu32 ")", __FUNCTION__, (metadata->data_start + metadata->data_capacity), metadata->size); return ERROR; } const metadata_size_t entry_count = metadata->entry_count; camera_metadata_buffer_entry_t *entries = get_entries(metadata); for (size_t i = 0; i < entry_count; ++i) { if ((uintptr_t)&entries[i] != ALIGN_TO(&entries[i], ENTRY_ALIGNMENT)) { ALOGE("%s: Entry index %zu had bad alignment (address %p)," " expected alignment %zu", __FUNCTION__, i, &entries[i], ENTRY_ALIGNMENT); return ERROR; } camera_metadata_buffer_entry_t entry = entries[i]; if (entry.type >= NUM_TYPES) { ALOGE("%s: Entry index %zu had a bad type %d", __FUNCTION__, i, entry.type); return ERROR; } uint32_t tag_section = entry.tag >> 16; int tag_type = get_camera_metadata_tag_type(entry.tag); if (tag_type != (int)entry.type && tag_section < VENDOR_SECTION) { ALOGE("%s: Entry index %zu had tag type %d, but the type was %d", __FUNCTION__, i, tag_type, entry.type); return ERROR; } size_t data_size; if (validate_and_calculate_camera_metadata_entry_data_size(&data_size, entry.type, entry.count) != OK) { ALOGE("%s: Entry data size is invalid. type: %u count: %u", __FUNCTION__, entry.type, entry.count); return ERROR; } if (data_size != 0) { camera_metadata_data_t *data = (camera_metadata_data_t*) (get_data(metadata) + entry.data.offset); if ((uintptr_t)data != ALIGN_TO(data, DATA_ALIGNMENT)) { ALOGE("%s: Entry index %zu had bad data alignment (address %p)," " expected align %zu, (tag name %s, data size %zu)", __FUNCTION__, i, data, DATA_ALIGNMENT, get_camera_metadata_tag_name(entry.tag) ?: "unknown", data_size); return ERROR; } size_t data_entry_end = entry.data.offset + data_size; if (data_entry_end < entry.data.offset || // overflow check data_entry_end > metadata->data_capacity) { ALOGE("%s: Entry index %zu data ends (%zu) beyond the capacity " "%" PRIu32, __FUNCTION__, i, data_entry_end, metadata->data_capacity); return ERROR; } } else if (entry.count == 0) { if (entry.data.offset != 0) { ALOGE("%s: Entry index %zu had 0 items, but offset was non-0 " "(%" PRIu32 "), tag name: %s", __FUNCTION__, i, entry.data.offset, get_camera_metadata_tag_name(entry.tag) ?: "unknown"); return ERROR; } } // else data stored inline, so we look at value which can be anything. } return OK; }
173,397
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothOptionsHandler::DisplayPasskey( chromeos::BluetoothDevice* device, int passkey, int entered) { } Commit Message: Implement methods for pairing of bluetooth devices. BUG=chromium:100392,chromium:102139 TEST= Review URL: http://codereview.chromium.org/8495018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void BluetoothOptionsHandler::DisplayPasskey( chromeos::BluetoothDevice* device, int passkey, int entered) { DictionaryValue params; params.SetString("pairing", "bluetoothRemotePasskey"); params.SetInteger("passkey", passkey); params.SetInteger("entered", entered); SendDeviceNotification(device, &params); }
170,967
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; int fname_len, alias_len = 0, arch_len, entry_len, is_data; #if PHP_VERSION_ID < 50300 long flags = 0; #else long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; #endif long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC); if (is_data) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->arc.archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "%s", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Phar creation or opening failed"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "PharData class can only be used for non-executable tar and zip archives"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Phar class can only be used for executable tar and zip archives"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->arc.archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname); } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, fname, fname_len, 0); INIT_PZVAL(&arg2); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2); if (!phar_data->is_persistent) { phar_obj->arc.archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif /* HAVE_SPL */ } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; int fname_len, alias_len = 0, arch_len, entry_len, is_data; #if PHP_VERSION_ID < 50300 long flags = 0; #else long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; #endif long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC); if (is_data) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->arc.archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "%s", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Phar creation or opening failed"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "PharData class can only be used for non-executable tar and zip archives"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Phar class can only be used for executable tar and zip archives"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->arc.archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname); } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, fname, fname_len, 0); INIT_PZVAL(&arg2); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2); if (!phar_data->is_persistent) { phar_obj->arc.archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif /* HAVE_SPL */ }
165,291
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void icmp6_send(struct sk_buff *skb, u8 type, u8 code, __u32 info, const struct in6_addr *force_saddr) { struct net *net = dev_net(skb->dev); struct inet6_dev *idev = NULL; struct ipv6hdr *hdr = ipv6_hdr(skb); struct sock *sk; struct ipv6_pinfo *np; const struct in6_addr *saddr = NULL; struct dst_entry *dst; struct icmp6hdr tmp_hdr; struct flowi6 fl6; struct icmpv6_msg msg; struct sockcm_cookie sockc_unused = {0}; struct ipcm6_cookie ipc6; int iif = 0; int addr_type = 0; int len; int err = 0; u32 mark = IP6_REPLY_MARK(net, skb->mark); if ((u8 *)hdr < skb->head || (skb_network_header(skb) + sizeof(*hdr)) > skb_tail_pointer(skb)) return; /* * Make sure we respect the rules * i.e. RFC 1885 2.4(e) * Rule (e.1) is enforced by not using icmp6_send * in any code that processes icmp errors. */ addr_type = ipv6_addr_type(&hdr->daddr); if (ipv6_chk_addr(net, &hdr->daddr, skb->dev, 0) || ipv6_chk_acast_addr_src(net, skb->dev, &hdr->daddr)) saddr = &hdr->daddr; /* * Dest addr check */ if (addr_type & IPV6_ADDR_MULTICAST || skb->pkt_type != PACKET_HOST) { if (type != ICMPV6_PKT_TOOBIG && !(type == ICMPV6_PARAMPROB && code == ICMPV6_UNK_OPTION && (opt_unrec(skb, info)))) return; saddr = NULL; } addr_type = ipv6_addr_type(&hdr->saddr); /* * Source addr check */ if (__ipv6_addr_needs_scope_id(addr_type)) iif = skb->dev->ifindex; else iif = l3mdev_master_ifindex(skb_dst(skb)->dev); /* * Must not send error if the source does not uniquely * identify a single node (RFC2463 Section 2.4). * We check unspecified / multicast addresses here, * and anycast addresses will be checked later. */ if ((addr_type == IPV6_ADDR_ANY) || (addr_type & IPV6_ADDR_MULTICAST)) { net_dbg_ratelimited("icmp6_send: addr_any/mcast source [%pI6c > %pI6c]\n", &hdr->saddr, &hdr->daddr); return; } /* * Never answer to a ICMP packet. */ if (is_ineligible(skb)) { net_dbg_ratelimited("icmp6_send: no reply to icmp error [%pI6c > %pI6c]\n", &hdr->saddr, &hdr->daddr); return; } mip6_addr_swap(skb); memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_ICMPV6; fl6.daddr = hdr->saddr; if (force_saddr) saddr = force_saddr; if (saddr) fl6.saddr = *saddr; fl6.flowi6_mark = mark; fl6.flowi6_oif = iif; fl6.fl6_icmp_type = type; fl6.fl6_icmp_code = code; security_skb_classify_flow(skb, flowi6_to_flowi(&fl6)); sk = icmpv6_xmit_lock(net); if (!sk) return; sk->sk_mark = mark; np = inet6_sk(sk); if (!icmpv6_xrlim_allow(sk, type, &fl6)) goto out; tmp_hdr.icmp6_type = type; tmp_hdr.icmp6_code = code; tmp_hdr.icmp6_cksum = 0; tmp_hdr.icmp6_pointer = htonl(info); if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) fl6.flowi6_oif = np->mcast_oif; else if (!fl6.flowi6_oif) fl6.flowi6_oif = np->ucast_oif; ipc6.tclass = np->tclass; fl6.flowlabel = ip6_make_flowinfo(ipc6.tclass, fl6.flowlabel); dst = icmpv6_route_lookup(net, skb, sk, &fl6); if (IS_ERR(dst)) goto out; ipc6.hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst); ipc6.dontfrag = np->dontfrag; ipc6.opt = NULL; msg.skb = skb; msg.offset = skb_network_offset(skb); msg.type = type; len = skb->len - msg.offset; len = min_t(unsigned int, len, IPV6_MIN_MTU - sizeof(struct ipv6hdr) - sizeof(struct icmp6hdr)); if (len < 0) { net_dbg_ratelimited("icmp: len problem [%pI6c > %pI6c]\n", &hdr->saddr, &hdr->daddr); goto out_dst_release; } rcu_read_lock(); idev = __in6_dev_get(skb->dev); err = ip6_append_data(sk, icmpv6_getfrag, &msg, len + sizeof(struct icmp6hdr), sizeof(struct icmp6hdr), &ipc6, &fl6, (struct rt6_info *)dst, MSG_DONTWAIT, &sockc_unused); if (err) { ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTERRORS); ip6_flush_pending_frames(sk); } else { err = icmpv6_push_pending_frames(sk, &fl6, &tmp_hdr, len + sizeof(struct icmp6hdr)); } rcu_read_unlock(); out_dst_release: dst_release(dst); out: icmpv6_xmit_unlock(sk); } Commit Message: net: handle no dst on skb in icmp6_send Andrey reported the following while fuzzing the kernel with syzkaller: kasan: CONFIG_KASAN_INLINE enabled kasan: GPF could be caused by NULL-ptr deref or user memory access general protection fault: 0000 [#1] SMP KASAN Modules linked in: CPU: 0 PID: 3859 Comm: a.out Not tainted 4.9.0-rc6+ #429 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 task: ffff8800666d4200 task.stack: ffff880067348000 RIP: 0010:[<ffffffff833617ec>] [<ffffffff833617ec>] icmp6_send+0x5fc/0x1e30 net/ipv6/icmp.c:451 RSP: 0018:ffff88006734f2c0 EFLAGS: 00010206 RAX: ffff8800666d4200 RBX: 0000000000000000 RCX: 0000000000000000 RDX: 0000000000000000 RSI: dffffc0000000000 RDI: 0000000000000018 RBP: ffff88006734f630 R08: ffff880064138418 R09: 0000000000000003 R10: dffffc0000000000 R11: 0000000000000005 R12: 0000000000000000 R13: ffffffff84e7e200 R14: ffff880064138484 R15: ffff8800641383c0 FS: 00007fb3887a07c0(0000) GS:ffff88006cc00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 0000000020000000 CR3: 000000006b040000 CR4: 00000000000006f0 Stack: ffff8800666d4200 ffff8800666d49f8 ffff8800666d4200 ffffffff84c02460 ffff8800666d4a1a 1ffff1000ccdaa2f ffff88006734f498 0000000000000046 ffff88006734f440 ffffffff832f4269 ffff880064ba7456 0000000000000000 Call Trace: [<ffffffff83364ddc>] icmpv6_param_prob+0x2c/0x40 net/ipv6/icmp.c:557 [< inline >] ip6_tlvopt_unknown net/ipv6/exthdrs.c:88 [<ffffffff83394405>] ip6_parse_tlv+0x555/0x670 net/ipv6/exthdrs.c:157 [<ffffffff8339a759>] ipv6_parse_hopopts+0x199/0x460 net/ipv6/exthdrs.c:663 [<ffffffff832ee773>] ipv6_rcv+0xfa3/0x1dc0 net/ipv6/ip6_input.c:191 ... icmp6_send / icmpv6_send is invoked for both rx and tx paths. In both cases the dst->dev should be preferred for determining the L3 domain if the dst has been set on the skb. Fallback to the skb->dev if it has not. This covers the case reported here where icmp6_send is invoked on Rx before the route lookup. Fixes: 5d41ce29e ("net: icmp6_send should use dst dev to determine L3 domain") Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: David Ahern <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static void icmp6_send(struct sk_buff *skb, u8 type, u8 code, __u32 info, const struct in6_addr *force_saddr) { struct net *net = dev_net(skb->dev); struct inet6_dev *idev = NULL; struct ipv6hdr *hdr = ipv6_hdr(skb); struct sock *sk; struct ipv6_pinfo *np; const struct in6_addr *saddr = NULL; struct dst_entry *dst; struct icmp6hdr tmp_hdr; struct flowi6 fl6; struct icmpv6_msg msg; struct sockcm_cookie sockc_unused = {0}; struct ipcm6_cookie ipc6; int iif = 0; int addr_type = 0; int len; int err = 0; u32 mark = IP6_REPLY_MARK(net, skb->mark); if ((u8 *)hdr < skb->head || (skb_network_header(skb) + sizeof(*hdr)) > skb_tail_pointer(skb)) return; /* * Make sure we respect the rules * i.e. RFC 1885 2.4(e) * Rule (e.1) is enforced by not using icmp6_send * in any code that processes icmp errors. */ addr_type = ipv6_addr_type(&hdr->daddr); if (ipv6_chk_addr(net, &hdr->daddr, skb->dev, 0) || ipv6_chk_acast_addr_src(net, skb->dev, &hdr->daddr)) saddr = &hdr->daddr; /* * Dest addr check */ if (addr_type & IPV6_ADDR_MULTICAST || skb->pkt_type != PACKET_HOST) { if (type != ICMPV6_PKT_TOOBIG && !(type == ICMPV6_PARAMPROB && code == ICMPV6_UNK_OPTION && (opt_unrec(skb, info)))) return; saddr = NULL; } addr_type = ipv6_addr_type(&hdr->saddr); /* * Source addr check */ if (__ipv6_addr_needs_scope_id(addr_type)) iif = skb->dev->ifindex; else { dst = skb_dst(skb); iif = l3mdev_master_ifindex(dst ? dst->dev : skb->dev); } /* * Must not send error if the source does not uniquely * identify a single node (RFC2463 Section 2.4). * We check unspecified / multicast addresses here, * and anycast addresses will be checked later. */ if ((addr_type == IPV6_ADDR_ANY) || (addr_type & IPV6_ADDR_MULTICAST)) { net_dbg_ratelimited("icmp6_send: addr_any/mcast source [%pI6c > %pI6c]\n", &hdr->saddr, &hdr->daddr); return; } /* * Never answer to a ICMP packet. */ if (is_ineligible(skb)) { net_dbg_ratelimited("icmp6_send: no reply to icmp error [%pI6c > %pI6c]\n", &hdr->saddr, &hdr->daddr); return; } mip6_addr_swap(skb); memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_ICMPV6; fl6.daddr = hdr->saddr; if (force_saddr) saddr = force_saddr; if (saddr) fl6.saddr = *saddr; fl6.flowi6_mark = mark; fl6.flowi6_oif = iif; fl6.fl6_icmp_type = type; fl6.fl6_icmp_code = code; security_skb_classify_flow(skb, flowi6_to_flowi(&fl6)); sk = icmpv6_xmit_lock(net); if (!sk) return; sk->sk_mark = mark; np = inet6_sk(sk); if (!icmpv6_xrlim_allow(sk, type, &fl6)) goto out; tmp_hdr.icmp6_type = type; tmp_hdr.icmp6_code = code; tmp_hdr.icmp6_cksum = 0; tmp_hdr.icmp6_pointer = htonl(info); if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) fl6.flowi6_oif = np->mcast_oif; else if (!fl6.flowi6_oif) fl6.flowi6_oif = np->ucast_oif; ipc6.tclass = np->tclass; fl6.flowlabel = ip6_make_flowinfo(ipc6.tclass, fl6.flowlabel); dst = icmpv6_route_lookup(net, skb, sk, &fl6); if (IS_ERR(dst)) goto out; ipc6.hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst); ipc6.dontfrag = np->dontfrag; ipc6.opt = NULL; msg.skb = skb; msg.offset = skb_network_offset(skb); msg.type = type; len = skb->len - msg.offset; len = min_t(unsigned int, len, IPV6_MIN_MTU - sizeof(struct ipv6hdr) - sizeof(struct icmp6hdr)); if (len < 0) { net_dbg_ratelimited("icmp: len problem [%pI6c > %pI6c]\n", &hdr->saddr, &hdr->daddr); goto out_dst_release; } rcu_read_lock(); idev = __in6_dev_get(skb->dev); err = ip6_append_data(sk, icmpv6_getfrag, &msg, len + sizeof(struct icmp6hdr), sizeof(struct icmp6hdr), &ipc6, &fl6, (struct rt6_info *)dst, MSG_DONTWAIT, &sockc_unused); if (err) { ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTERRORS); ip6_flush_pending_frames(sk); } else { err = icmpv6_push_pending_frames(sk, &fl6, &tmp_hdr, len + sizeof(struct icmp6hdr)); } rcu_read_unlock(); out_dst_release: dst_release(dst); out: icmpv6_xmit_unlock(sk); }
166,842
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewAura::SetSurfaceNotInUseByCompositor(ui::Compositor*) { if (current_surface_ || !host_->is_hidden()) return; current_surface_in_use_by_compositor_ = false; AdjustSurfaceProtection(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewAura::SetSurfaceNotInUseByCompositor(ui::Compositor*) {
171,385
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Track::Info::Clear() { delete[] nameAsUTF8; nameAsUTF8 = NULL; delete[] language; language = NULL; delete[] codecId; codecId = NULL; delete[] codecPrivate; codecPrivate = NULL; codecPrivateSize = 0; delete[] codecNameAsUTF8; codecNameAsUTF8 = NULL; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Track::Info::Clear() if (dst) // should be NULL already return -1; const char* const src = this->*str;
174,247
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void detect_allow_debuggers(int argc, char **argv) { int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--allow-debuggers") == 0) { arg_allow_debuggers = 1; break; } if (strcmp(argv[i], "--") == 0) break; if (strncmp(argv[i], "--", 2) != 0) break; } } Commit Message: security fix CWE ID:
static void detect_allow_debuggers(int argc, char **argv) { int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--allow-debuggers") == 0) { // check kernel version struct utsname u; int rv = uname(&u); if (rv != 0) errExit("uname"); int major; int minor; if (2 != sscanf(u.release, "%d.%d", &major, &minor)) { fprintf(stderr, "Error: cannot extract Linux kernel version: %s\n", u.version); exit(1); } if (major < 4 || (major == 4 && minor < 8)) { fprintf(stderr, "Error: --allow-debuggers is disabled on Linux kernels prior to 4.8. " "A bug in ptrace call allows a full bypass of the seccomp filter. " "Your current kernel version is %d.%d.\n", major, minor); exit(1); } arg_allow_debuggers = 1; break; } if (strcmp(argv[i], "--") == 0) break; if (strncmp(argv[i], "--", 2) != 0) break; } }
168,419
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothDeviceChromeOS::SetPasskey(uint32 passkey) { if (!agent_.get() || passkey_callback_.is_null()) return; passkey_callback_.Run(SUCCESS, passkey); passkey_callback_.Reset(); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::SetPasskey(uint32 passkey) { if (!pairing_context_.get()) return; pairing_context_->SetPasskey(passkey); }
171,239
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void unset_active_map(const vpx_codec_enc_cfg_t *cfg, vpx_codec_ctx_t *codec) { vpx_active_map_t map = {0}; map.rows = (cfg->g_h + 15) / 16; map.cols = (cfg->g_w + 15) / 16; map.active_map = NULL; if (vpx_codec_control(codec, VP8E_SET_ACTIVEMAP, &map)) die_codec(codec, "Failed to set active map"); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static void unset_active_map(const vpx_codec_enc_cfg_t *cfg, vpx_codec_ctx_t *codec) { vpx_active_map_t map = {0, 0, 0}; map.rows = (cfg->g_h + 15) / 16; map.cols = (cfg->g_w + 15) / 16; map.active_map = NULL; if (vpx_codec_control(codec, VP8E_SET_ACTIVEMAP, &map)) die_codec(codec, "Failed to set active map"); }
174,485
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ssl3_read_n(SSL *s, int n, int max, int extend) { /* If extend == 0, obtain new n-byte packet; if extend == 1, increase * packet by another n bytes. * The packet will be in the sub-array of s->s3->rbuf.buf specified * by s->packet and s->packet_length. * (If s->read_ahead is set, 'max' bytes may be stored in rbuf * [plus s->packet_length bytes if extend == 1].) */ int i,len,left; long align=0; unsigned char *pkt; SSL3_BUFFER *rb; if (n <= 0) return n; rb = &(s->s3->rbuf); if (rb->buf == NULL) if (!ssl3_setup_read_buffer(s)) return -1; left = rb->left; #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 align = (long)rb->buf + SSL3_RT_HEADER_LENGTH; align = (-align)&(SSL3_ALIGN_PAYLOAD-1); #endif if (!extend) { /* start with empty packet ... */ if (left == 0) rb->offset = align; else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) { /* check if next packet length is large * enough to justify payload alignment... */ pkt = rb->buf + rb->offset; if (pkt[0] == SSL3_RT_APPLICATION_DATA && (pkt[3]<<8|pkt[4]) >= 128) { /* Note that even if packet is corrupted * and its length field is insane, we can * only be led to wrong decision about * whether memmove will occur or not. * Header values has no effect on memmove * arguments and therefore no buffer * overrun can be triggered. */ memmove (rb->buf+align,pkt,left); rb->offset = align; } } s->packet = rb->buf + rb->offset; s->packet_length = 0; /* ... now we can act as if 'extend' was set */ } /* For DTLS/UDP reads should not span multiple packets * because the read operation returns the whole packet * at once (as long as it fits into the buffer). */ if (SSL_IS_DTLS(s)) { if (left > 0 && n > left) n = left; } /* if there is enough in the buffer from a previous read, take some */ if (left >= n) { s->packet_length+=n; rb->left=left-n; rb->offset+=n; return(n); } /* else we need to read more data */ len = s->packet_length; pkt = rb->buf+align; /* Move any available bytes to front of buffer: * 'len' bytes already pointed to by 'packet', * 'left' extra ones at the end */ if (s->packet != pkt) /* len > 0 */ { memmove(pkt, s->packet, len+left); s->packet = pkt; rb->offset = len + align; } if (n > (int)(rb->len - rb->offset)) /* does not happen */ { SSLerr(SSL_F_SSL3_READ_N,ERR_R_INTERNAL_ERROR); return -1; } if (!s->read_ahead) /* ignore max parameter */ max = n; else { if (max < n) max = n; if (max > (int)(rb->len - rb->offset)) max = rb->len - rb->offset; } while (left < n) { /* Now we have len+left bytes at the front of s->s3->rbuf.buf * and need to read in more until we have len+n (up to * len+max if possible) */ clear_sys_error(); if (s->rbio != NULL) { s->rwstate=SSL_READING; i=BIO_read(s->rbio,pkt+len+left, max-left); } else { SSLerr(SSL_F_SSL3_READ_N,SSL_R_READ_BIO_NOT_SET); i = -1; } if (i <= 0) { rb->left = left; if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) if (len+left == 0) ssl3_release_read_buffer(s); return(i); } left+=i; /* reads should *never* span multiple packets for DTLS because * the underlying transport protocol is message oriented as opposed * to byte oriented as in the TLS case. */ if (SSL_IS_DTLS(s)) { if (n > left) n = left; /* makes the while condition false */ } } /* done reading, now the book-keeping */ rb->offset += n; rb->left = left - n; s->packet_length += n; s->rwstate=SSL_NOTHING; return(n); } Commit Message: Fix crash in dtls1_get_record whilst in the listen state where you get two separate reads performed - one for the header and one for the body of the handshake record. CVE-2014-3571 Reviewed-by: Matt Caswell <[email protected]> CWE ID:
int ssl3_read_n(SSL *s, int n, int max, int extend) { /* If extend == 0, obtain new n-byte packet; if extend == 1, increase * packet by another n bytes. * The packet will be in the sub-array of s->s3->rbuf.buf specified * by s->packet and s->packet_length. * (If s->read_ahead is set, 'max' bytes may be stored in rbuf * [plus s->packet_length bytes if extend == 1].) */ int i,len,left; long align=0; unsigned char *pkt; SSL3_BUFFER *rb; if (n <= 0) return n; rb = &(s->s3->rbuf); if (rb->buf == NULL) if (!ssl3_setup_read_buffer(s)) return -1; left = rb->left; #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 align = (long)rb->buf + SSL3_RT_HEADER_LENGTH; align = (-align)&(SSL3_ALIGN_PAYLOAD-1); #endif if (!extend) { /* start with empty packet ... */ if (left == 0) rb->offset = align; else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) { /* check if next packet length is large * enough to justify payload alignment... */ pkt = rb->buf + rb->offset; if (pkt[0] == SSL3_RT_APPLICATION_DATA && (pkt[3]<<8|pkt[4]) >= 128) { /* Note that even if packet is corrupted * and its length field is insane, we can * only be led to wrong decision about * whether memmove will occur or not. * Header values has no effect on memmove * arguments and therefore no buffer * overrun can be triggered. */ memmove (rb->buf+align,pkt,left); rb->offset = align; } } s->packet = rb->buf + rb->offset; s->packet_length = 0; /* ... now we can act as if 'extend' was set */ } /* For DTLS/UDP reads should not span multiple packets * because the read operation returns the whole packet * at once (as long as it fits into the buffer). */ if (SSL_IS_DTLS(s)) { if (left == 0 && extend) return 0; if (left > 0 && n > left) n = left; } /* if there is enough in the buffer from a previous read, take some */ if (left >= n) { s->packet_length+=n; rb->left=left-n; rb->offset+=n; return(n); } /* else we need to read more data */ len = s->packet_length; pkt = rb->buf+align; /* Move any available bytes to front of buffer: * 'len' bytes already pointed to by 'packet', * 'left' extra ones at the end */ if (s->packet != pkt) /* len > 0 */ { memmove(pkt, s->packet, len+left); s->packet = pkt; rb->offset = len + align; } if (n > (int)(rb->len - rb->offset)) /* does not happen */ { SSLerr(SSL_F_SSL3_READ_N,ERR_R_INTERNAL_ERROR); return -1; } if (!s->read_ahead) /* ignore max parameter */ max = n; else { if (max < n) max = n; if (max > (int)(rb->len - rb->offset)) max = rb->len - rb->offset; } while (left < n) { /* Now we have len+left bytes at the front of s->s3->rbuf.buf * and need to read in more until we have len+n (up to * len+max if possible) */ clear_sys_error(); if (s->rbio != NULL) { s->rwstate=SSL_READING; i=BIO_read(s->rbio,pkt+len+left, max-left); } else { SSLerr(SSL_F_SSL3_READ_N,SSL_R_READ_BIO_NOT_SET); i = -1; } if (i <= 0) { rb->left = left; if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) if (len+left == 0) ssl3_release_read_buffer(s); return(i); } left+=i; /* reads should *never* span multiple packets for DTLS because * the underlying transport protocol is message oriented as opposed * to byte oriented as in the TLS case. */ if (SSL_IS_DTLS(s)) { if (n > left) n = left; /* makes the while condition false */ } } /* done reading, now the book-keeping */ rb->offset += n; rb->left = left - n; s->packet_length += n; s->rwstate=SSL_NOTHING; return(n); }
169,936
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool WebMediaPlayerImpl::HasSingleSecurityOrigin() const { if (data_source_) return data_source_->HasSingleOrigin(); return true; } Commit Message: Fix HasSingleSecurityOrigin for HLS HLS manifests can request segments from a different origin than the original manifest's origin. We do not inspect HLS manifests within Chromium, and instead delegate to Android's MediaPlayer. This means we need to be conservative, and always assume segments might come from a different origin. HasSingleSecurityOrigin should always return false when decoding HLS. Bug: 864283 Change-Id: Ie16849ac6f29ae7eaa9caf342ad0509a226228ef Reviewed-on: https://chromium-review.googlesource.com/1142691 Reviewed-by: Dale Curtis <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Commit-Queue: Thomas Guilbert <[email protected]> Cr-Commit-Position: refs/heads/master@{#576378} CWE ID: CWE-346
bool WebMediaPlayerImpl::HasSingleSecurityOrigin() const { if (demuxer_found_hls_) { // HLS manifests might pull segments from a different origin. We can't know // for sure, so we conservatively say no here. return false; } if (data_source_) return data_source_->HasSingleOrigin(); return true; }
173,178
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const char *string_of_NPPVariable(int variable) { const char *str; switch (variable) { #define _(VAL) case VAL: str = #VAL; break; _(NPPVpluginNameString); _(NPPVpluginDescriptionString); _(NPPVpluginWindowBool); _(NPPVpluginTransparentBool); _(NPPVjavaClass); _(NPPVpluginWindowSize); _(NPPVpluginTimerInterval); _(NPPVpluginScriptableInstance); _(NPPVpluginScriptableIID); _(NPPVjavascriptPushCallerBool); _(NPPVpluginKeepLibraryInMemory); _(NPPVpluginNeedsXEmbed); _(NPPVpluginScriptableNPObject); _(NPPVformValue); #undef _ default: switch (variable & 0xff) { #define _(VAL, VAR) case VAL: str = #VAR; break _(10, NPPVpluginScriptableInstance); #undef _ default: str = "<unknown variable>"; break; } break; } return str; } Commit Message: Support all the new variables added CWE ID: CWE-264
const char *string_of_NPPVariable(int variable) { const char *str; switch (variable) { #define _(VAL) case VAL: str = #VAL; break; _(NPPVpluginNameString); _(NPPVpluginDescriptionString); _(NPPVpluginWindowBool); _(NPPVpluginTransparentBool); _(NPPVjavaClass); _(NPPVpluginWindowSize); _(NPPVpluginTimerInterval); _(NPPVpluginScriptableInstance); _(NPPVpluginScriptableIID); _(NPPVjavascriptPushCallerBool); _(NPPVpluginKeepLibraryInMemory); _(NPPVpluginNeedsXEmbed); _(NPPVpluginScriptableNPObject); _(NPPVformValue); _(NPPVpluginUrlRequestsDisplayedBool); _(NPPVpluginWantsAllNetworkStreams); _(NPPVpluginNativeAccessibleAtkPlugId); _(NPPVpluginCancelSrcStream); _(NPPVSupportsAdvancedKeyHandling); #undef _ default: switch (variable & 0xff) { #define _(VAL, VAR) case VAL: str = #VAR; break _(10, NPPVpluginScriptableInstance); #undef _ default: str = "<unknown variable>"; break; } break; } return str; }
165,866
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gfx::Rect AutofillPopupBaseView::CalculateClippingBounds() const { if (parent_widget_) return parent_widget_->GetClientAreaBoundsInScreen(); return PopupViewCommon().GetWindowBounds(delegate_->container_view()); } Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature. Bug: 906135,831603 Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499 Reviewed-on: https://chromium-review.googlesource.com/c/1387124 Reviewed-by: Robert Kaplow <[email protected]> Reviewed-by: Vasilii Sukhanov <[email protected]> Reviewed-by: Fabio Tirelo <[email protected]> Reviewed-by: Tommy Martino <[email protected]> Commit-Queue: Mathieu Perreault <[email protected]> Cr-Commit-Position: refs/heads/master@{#621360} CWE ID: CWE-416
gfx::Rect AutofillPopupBaseView::CalculateClippingBounds() const {
172,093
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static unsigned long randomize_stack_top(unsigned long stack_top) { unsigned int random_variable = 0; if ((current->flags & PF_RANDOMIZE) && !(current->personality & ADDR_NO_RANDOMIZE)) { random_variable = get_random_int() & STACK_RND_MASK; random_variable <<= PAGE_SHIFT; } #ifdef CONFIG_STACK_GROWSUP return PAGE_ALIGN(stack_top) + random_variable; #else return PAGE_ALIGN(stack_top) - random_variable; #endif } Commit Message: x86, mm/ASLR: Fix stack randomization on 64-bit systems The issue is that the stack for processes is not properly randomized on 64 bit architectures due to an integer overflow. The affected function is randomize_stack_top() in file "fs/binfmt_elf.c": static unsigned long randomize_stack_top(unsigned long stack_top) { unsigned int random_variable = 0; if ((current->flags & PF_RANDOMIZE) && !(current->personality & ADDR_NO_RANDOMIZE)) { random_variable = get_random_int() & STACK_RND_MASK; random_variable <<= PAGE_SHIFT; } return PAGE_ALIGN(stack_top) + random_variable; return PAGE_ALIGN(stack_top) - random_variable; } Note that, it declares the "random_variable" variable as "unsigned int". Since the result of the shifting operation between STACK_RND_MASK (which is 0x3fffff on x86_64, 22 bits) and PAGE_SHIFT (which is 12 on x86_64): random_variable <<= PAGE_SHIFT; then the two leftmost bits are dropped when storing the result in the "random_variable". This variable shall be at least 34 bits long to hold the (22+12) result. These two dropped bits have an impact on the entropy of process stack. Concretely, the total stack entropy is reduced by four: from 2^28 to 2^30 (One fourth of expected entropy). This patch restores back the entropy by correcting the types involved in the operations in the functions randomize_stack_top() and stack_maxrandom_size(). The successful fix can be tested with: $ for i in `seq 1 10`; do cat /proc/self/maps | grep stack; done 7ffeda566000-7ffeda587000 rw-p 00000000 00:00 0 [stack] 7fff5a332000-7fff5a353000 rw-p 00000000 00:00 0 [stack] 7ffcdb7a1000-7ffcdb7c2000 rw-p 00000000 00:00 0 [stack] 7ffd5e2c4000-7ffd5e2e5000 rw-p 00000000 00:00 0 [stack] ... Once corrected, the leading bytes should be between 7ffc and 7fff, rather than always being 7fff. Signed-off-by: Hector Marco-Gisbert <[email protected]> Signed-off-by: Ismael Ripoll <[email protected]> [ Rebased, fixed 80 char bugs, cleaned up commit message, added test example and CVE ] Signed-off-by: Kees Cook <[email protected]> Cc: <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Al Viro <[email protected]> Fixes: CVE-2015-1593 Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Borislav Petkov <[email protected]> CWE ID: CWE-264
static unsigned long randomize_stack_top(unsigned long stack_top) { unsigned long random_variable = 0; if ((current->flags & PF_RANDOMIZE) && !(current->personality & ADDR_NO_RANDOMIZE)) { random_variable = (unsigned long) get_random_int(); random_variable &= STACK_RND_MASK; random_variable <<= PAGE_SHIFT; } #ifdef CONFIG_STACK_GROWSUP return PAGE_ALIGN(stack_top) + random_variable; #else return PAGE_ALIGN(stack_top) - random_variable; #endif }
166,696
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: UINT32 UIPC_Read(tUIPC_CH_ID ch_id, UINT16 *p_msg_evt, UINT8 *p_buf, UINT32 len) { int n; int n_read = 0; int fd = uipc_main.ch[ch_id].fd; struct pollfd pfd; UNUSED(p_msg_evt); if (ch_id >= UIPC_CH_NUM) { BTIF_TRACE_ERROR("UIPC_Read : invalid ch id %d", ch_id); return 0; } if (fd == UIPC_DISCONNECTED) { BTIF_TRACE_ERROR("UIPC_Read : channel %d closed", ch_id); return 0; } while (n_read < (int)len) { pfd.fd = fd; pfd.events = POLLIN|POLLHUP; /* make sure there is data prior to attempting read to avoid blocking a read for more than poll timeout */ if (poll(&pfd, 1, uipc_main.ch[ch_id].read_poll_tmo_ms) == 0) { BTIF_TRACE_EVENT("poll timeout (%d ms)", uipc_main.ch[ch_id].read_poll_tmo_ms); break; } if (pfd.revents & (POLLHUP|POLLNVAL) ) { BTIF_TRACE_EVENT("poll : channel detached remotely"); UIPC_LOCK(); uipc_close_locked(ch_id); UIPC_UNLOCK(); return 0; } n = recv(fd, p_buf+n_read, len-n_read, 0); if (n == 0) { BTIF_TRACE_EVENT("UIPC_Read : channel detached remotely"); UIPC_LOCK(); uipc_close_locked(ch_id); UIPC_UNLOCK(); return 0; } if (n < 0) { BTIF_TRACE_EVENT("UIPC_Read : read failed (%s)", strerror(errno)); return 0; } n_read+=n; } return n_read; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
UINT32 UIPC_Read(tUIPC_CH_ID ch_id, UINT16 *p_msg_evt, UINT8 *p_buf, UINT32 len) { int n; int n_read = 0; int fd = uipc_main.ch[ch_id].fd; struct pollfd pfd; UNUSED(p_msg_evt); if (ch_id >= UIPC_CH_NUM) { BTIF_TRACE_ERROR("UIPC_Read : invalid ch id %d", ch_id); return 0; } if (fd == UIPC_DISCONNECTED) { BTIF_TRACE_ERROR("UIPC_Read : channel %d closed", ch_id); return 0; } while (n_read < (int)len) { pfd.fd = fd; pfd.events = POLLIN|POLLHUP; /* make sure there is data prior to attempting read to avoid blocking a read for more than poll timeout */ if (TEMP_FAILURE_RETRY(poll(&pfd, 1, uipc_main.ch[ch_id].read_poll_tmo_ms)) == 0) { BTIF_TRACE_EVENT("poll timeout (%d ms)", uipc_main.ch[ch_id].read_poll_tmo_ms); break; } if (pfd.revents & (POLLHUP|POLLNVAL) ) { BTIF_TRACE_EVENT("poll : channel detached remotely"); UIPC_LOCK(); uipc_close_locked(ch_id); UIPC_UNLOCK(); return 0; } n = TEMP_FAILURE_RETRY(recv(fd, p_buf+n_read, len-n_read, 0)); if (n == 0) { BTIF_TRACE_EVENT("UIPC_Read : channel detached remotely"); UIPC_LOCK(); uipc_close_locked(ch_id); UIPC_UNLOCK(); return 0; } if (n < 0) { BTIF_TRACE_EVENT("UIPC_Read : read failed (%s)", strerror(errno)); return 0; } n_read+=n; } return n_read; }
173,493
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithSequenceArg(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); sequence<ScriptProfile>* sequenceArg(toNativeArray<ScriptProfile>(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->methodWithSequenceArg(sequenceArg); return JSValue::encode(jsUndefined()); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithSequenceArg(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); sequence<ScriptProfile>* sequenceArg(toNativeArray<ScriptProfile>(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->methodWithSequenceArg(sequenceArg); return JSValue::encode(jsUndefined()); }
170,596
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadRGBImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *canvas_image, *image; MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length; ssize_t count, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); if (image_info->interlace != PartitionInterlace) { status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Create virtual canvas to support cropping (i.e. image.rgb[100x100+10+20]). */ canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse, exception); (void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod); quantum_info=AcquireQuantumInfo(image_info,canvas_image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); quantum_type=RGBQuantum; if (LocaleCompare(image_info->magick,"RGBA") == 0) { quantum_type=RGBAQuantum; image->matte=MagickTrue; } if (LocaleCompare(image_info->magick,"RGBO") == 0) { quantum_type=RGBOQuantum; image->matte=MagickTrue; } if (image_info->number_scenes != 0) while (image->scene < image_info->scene) { /* Skip to next image. */ image->scene++; length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) break; } } count=0; length=0; scene=0; do { /* Read pixels to virtual canvas image then push to image. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: RGBRGBRGBRGBRGBRGB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=QueueAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } count=ReadBlob(image,length,pixels); } break; } case LineInterlace: { static QuantumType quantum_types[4] = { RedQuantum, GreenQuantum, BlueQuantum, AlphaQuantum }; /* Line interlacing: RRR...GGG...BBB...RRR...GGG...BBB... */ if (LocaleCompare(image_info->magick,"RGBO") == 0) quantum_types[3]=OpacityQuantum; if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } for (i=0; i < (ssize_t) (image->matte != MagickFalse ? 4 : 3); i++) { quantum_type=quantum_types[i]; q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { switch (quantum_type) { case RedQuantum: { SetPixelRed(q,GetPixelRed(p)); break; } case GreenQuantum: { SetPixelGreen(q,GetPixelGreen(p)); break; } case BlueQuantum: { SetPixelBlue(q,GetPixelBlue(p)); break; } case OpacityQuantum: { SetPixelOpacity(q,GetPixelOpacity(p)); break; } case AlphaQuantum: { SetPixelAlpha(q,GetPixelAlpha(p)); break; } default: break; } p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,6); if (status == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,6); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image, canvas_image->extract_info.x,0,canvas_image->columns,1, exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,6); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,6,6); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: RRRRRR..., GGGGGG..., BBBBBB... */ AppendImageFormat("R",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("G",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,GreenQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("B",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,BlueQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,5); if (status == MagickFalse) break; } } (void) CloseBlob(image); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,5); if (status == MagickFalse) break; } break; } } SetQuantumImageType(image,quantum_type); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (count == (ssize_t) length) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } scene++; } while (count == (ssize_t) length); quantum_info=DestroyQuantumInfo(quantum_info); InheritException(&image->exception,&canvas_image->exception); canvas_image=DestroyImage(canvas_image); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadRGBImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *canvas_image, *image; MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t length; ssize_t count, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); if (image_info->interlace != PartitionInterlace) { status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Create virtual canvas to support cropping (i.e. image.rgb[100x100+10+20]). */ canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse, exception); (void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod); quantum_info=AcquireQuantumInfo(image_info,canvas_image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); quantum_type=RGBQuantum; if (LocaleCompare(image_info->magick,"RGBA") == 0) { quantum_type=RGBAQuantum; image->matte=MagickTrue; } if (LocaleCompare(image_info->magick,"RGBO") == 0) { quantum_type=RGBOQuantum; image->matte=MagickTrue; } if (image_info->number_scenes != 0) while (image->scene < image_info->scene) { /* Skip to next image. */ image->scene++; length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) break; } } count=0; length=0; scene=0; do { /* Read pixels to virtual canvas image then push to image. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: RGBRGBRGBRGBRGBRGB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=QueueAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } count=ReadBlob(image,length,pixels); } break; } case LineInterlace: { static QuantumType quantum_types[4] = { RedQuantum, GreenQuantum, BlueQuantum, AlphaQuantum }; /* Line interlacing: RRR...GGG...BBB...RRR...GGG...BBB... */ if (LocaleCompare(image_info->magick,"RGBO") == 0) quantum_types[3]=OpacityQuantum; if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } for (i=0; i < (ssize_t) (image->matte != MagickFalse ? 4 : 3); i++) { quantum_type=quantum_types[i]; q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { switch (quantum_type) { case RedQuantum: { SetPixelRed(q,GetPixelRed(p)); break; } case GreenQuantum: { SetPixelGreen(q,GetPixelGreen(p)); break; } case BlueQuantum: { SetPixelBlue(q,GetPixelBlue(p)); break; } case OpacityQuantum: { SetPixelOpacity(q,GetPixelOpacity(p)); break; } case AlphaQuantum: { SetPixelAlpha(q,GetPixelAlpha(p)); break; } default: break; } p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,6); if (status == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,6); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image, canvas_image->extract_info.x,0,canvas_image->columns,1, exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,6); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,6,6); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: RRRRRR..., GGGGGG..., BBBBBB... */ AppendImageFormat("R",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("G",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,GreenQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("B",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,BlueQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,5); if (status == MagickFalse) break; } } (void) CloseBlob(image); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,5); if (status == MagickFalse) break; } break; } } SetQuantumImageType(image,quantum_type); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (count == (ssize_t) length) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } scene++; } while (count == (ssize_t) length); quantum_info=DestroyQuantumInfo(quantum_info); InheritException(&image->exception,&canvas_image->exception); canvas_image=DestroyImage(canvas_image); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,597
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) length; j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info,exception); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/350 CWE ID: CWE-787
ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) length; j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info,exception); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); }
168,405
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG t1,t2; BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; mul_add_c(a[0],b[0],c1,c2,c3); r[0]=c1; c1=0; mul_add_c(a[0],b[1],c2,c3,c1); mul_add_c(a[1],b[0],c2,c3,c1); r[1]=c2; c2=0; mul_add_c(a[2],b[0],c3,c1,c2); mul_add_c(a[1],b[1],c3,c1,c2); mul_add_c(a[0],b[2],c3,c1,c2); r[2]=c3; c3=0; mul_add_c(a[0],b[3],c1,c2,c3); mul_add_c(a[1],b[2],c1,c2,c3); mul_add_c(a[2],b[1],c1,c2,c3); mul_add_c(a[3],b[0],c1,c2,c3); r[3]=c1; c1=0; mul_add_c(a[3],b[1],c2,c3,c1); mul_add_c(a[2],b[2],c2,c3,c1); mul_add_c(a[1],b[3],c2,c3,c1); r[4]=c2; c2=0; mul_add_c(a[2],b[3],c3,c1,c2); mul_add_c(a[3],b[2],c3,c1,c2); r[5]=c3; c3=0; mul_add_c(a[3],b[3],c1,c2,c3); r[6]=c1; r[7]=c2; } Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <[email protected]> CWE ID: CWE-310
void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; mul_add_c(a[0],b[0],c1,c2,c3); r[0]=c1; c1=0; mul_add_c(a[0],b[1],c2,c3,c1); mul_add_c(a[1],b[0],c2,c3,c1); r[1]=c2; c2=0; mul_add_c(a[2],b[0],c3,c1,c2); mul_add_c(a[1],b[1],c3,c1,c2); mul_add_c(a[0],b[2],c3,c1,c2); r[2]=c3; c3=0; mul_add_c(a[0],b[3],c1,c2,c3); mul_add_c(a[1],b[2],c1,c2,c3); mul_add_c(a[2],b[1],c1,c2,c3); mul_add_c(a[3],b[0],c1,c2,c3); r[3]=c1; c1=0; mul_add_c(a[3],b[1],c2,c3,c1); mul_add_c(a[2],b[2],c2,c3,c1); mul_add_c(a[1],b[3],c2,c3,c1); r[4]=c2; c2=0; mul_add_c(a[2],b[3],c3,c1,c2); mul_add_c(a[3],b[2],c3,c1,c2); r[5]=c3; c3=0; mul_add_c(a[3],b[3],c1,c2,c3); r[6]=c1; r[7]=c2; }
166,828
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ihevcd_create(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op) { ihevcd_cxa_create_op_t *ps_create_op; WORD32 ret; codec_t *ps_codec; ps_create_op = (ihevcd_cxa_create_op_t *)pv_api_op; ps_create_op->s_ivd_create_op_t.u4_error_code = 0; ret = ihevcd_allocate_static_bufs(&ps_codec_obj, pv_api_ip, pv_api_op); /* If allocation of some buffer fails, then free buffers allocated till then */ if((IV_FAIL == ret) && (NULL != ps_codec_obj)) { ihevcd_free_static_bufs(ps_codec_obj); ps_create_op->s_ivd_create_op_t.u4_error_code = IVD_MEM_ALLOC_FAILED; ps_create_op->s_ivd_create_op_t.u4_error_code = 1 << IVD_FATALERROR; return IV_FAIL; } ps_codec = (codec_t *)ps_codec_obj->pv_codec_handle; ret = ihevcd_init(ps_codec); TRACE_INIT(NULL); STATS_INIT(); return ret; } Commit Message: Decoder: Handle ps_codec_obj memory allocation failure gracefully If memory allocation for ps_codec_obj fails, return gracefully with an error code. All other allocation failures are handled correctly. Bug: 68299873 Test: before/after with always-failing malloc Change-Id: I5e6c07b147b13df81e65476851662d4b55d33b83 (cherry picked from commit a966e2a65dd901151ce7f4481d0084840c9a0f7e) CWE ID: CWE-770
WORD32 ihevcd_create(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op) { ihevcd_cxa_create_ip_t *ps_create_ip; ihevcd_cxa_create_op_t *ps_create_op; WORD32 ret; codec_t *ps_codec; ps_create_ip = (ihevcd_cxa_create_ip_t *)pv_api_ip; ps_create_op = (ihevcd_cxa_create_op_t *)pv_api_op; ps_create_op->s_ivd_create_op_t.u4_error_code = 0; ps_codec_obj = NULL; ret = ihevcd_allocate_static_bufs(&ps_codec_obj, pv_api_ip, pv_api_op); /* If allocation of some buffer fails, then free buffers allocated till then */ if(IV_FAIL == ret) { if(NULL != ps_codec_obj) { if(ps_codec_obj->pv_codec_handle) { ihevcd_free_static_bufs(ps_codec_obj); } else { void (*pf_aligned_free)(void *pv_mem_ctxt, void *pv_buf); void *pv_mem_ctxt; pf_aligned_free = ps_create_ip->s_ivd_create_ip_t.pf_aligned_free; pv_mem_ctxt = ps_create_ip->s_ivd_create_ip_t.pv_mem_ctxt; pf_aligned_free(pv_mem_ctxt, ps_codec_obj); } } ps_create_op->s_ivd_create_op_t.u4_error_code = IVD_MEM_ALLOC_FAILED; ps_create_op->s_ivd_create_op_t.u4_error_code = 1 << IVD_FATALERROR; return IV_FAIL; } ps_codec = (codec_t *)ps_codec_obj->pv_codec_handle; ret = ihevcd_init(ps_codec); TRACE_INIT(NULL); STATS_INIT(); return ret; }
174,111
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void inet_sock_destruct(struct sock *sk) { struct inet_sock *inet = inet_sk(sk); __skb_queue_purge(&sk->sk_receive_queue); __skb_queue_purge(&sk->sk_error_queue); sk_mem_reclaim(sk); if (sk->sk_type == SOCK_STREAM && sk->sk_state != TCP_CLOSE) { pr_err("Attempt to release TCP socket in state %d %p\n", sk->sk_state, sk); return; } if (!sock_flag(sk, SOCK_DEAD)) { pr_err("Attempt to release alive inet socket %p\n", sk); return; } WARN_ON(atomic_read(&sk->sk_rmem_alloc)); WARN_ON(atomic_read(&sk->sk_wmem_alloc)); WARN_ON(sk->sk_wmem_queued); WARN_ON(sk->sk_forward_alloc); kfree(inet->opt); dst_release(rcu_dereference_check(sk->sk_dst_cache, 1)); sk_refcnt_debug_dec(sk); } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
void inet_sock_destruct(struct sock *sk) { struct inet_sock *inet = inet_sk(sk); __skb_queue_purge(&sk->sk_receive_queue); __skb_queue_purge(&sk->sk_error_queue); sk_mem_reclaim(sk); if (sk->sk_type == SOCK_STREAM && sk->sk_state != TCP_CLOSE) { pr_err("Attempt to release TCP socket in state %d %p\n", sk->sk_state, sk); return; } if (!sock_flag(sk, SOCK_DEAD)) { pr_err("Attempt to release alive inet socket %p\n", sk); return; } WARN_ON(atomic_read(&sk->sk_rmem_alloc)); WARN_ON(atomic_read(&sk->sk_wmem_alloc)); WARN_ON(sk->sk_wmem_queued); WARN_ON(sk->sk_forward_alloc); kfree(rcu_dereference_protected(inet->inet_opt, 1)); dst_release(rcu_dereference_check(sk->sk_dst_cache, 1)); sk_refcnt_debug_dec(sk); }
165,545
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static authz_status lua_authz_check(request_rec *r, const char *require_line, const void *parsed_require_line) { apr_pool_t *pool; ap_lua_vm_spec *spec; lua_State *L; ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config, &lua_module); const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config, &lua_module); const lua_authz_provider_spec *prov_spec = parsed_require_line; int result; int nargs = 0; spec = create_vm_spec(&pool, r, cfg, server_cfg, prov_spec->file_name, NULL, 0, prov_spec->function_name, "authz provider"); L = ap_lua_get_lua_state(pool, spec, r); if (L == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02314) "Unable to compile VM for authz provider %s", prov_spec->name); return AUTHZ_GENERAL_ERROR; } lua_getglobal(L, prov_spec->function_name); if (!lua_isfunction(L, -1)) { ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02319) "Unable to find entry function '%s' in %s (not a valid function)", prov_spec->function_name, prov_spec->file_name); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } ap_lua_run_lua_request(L, r); if (prov_spec->args) { int i; if (!lua_checkstack(L, prov_spec->args->nelts)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02315) "Error: authz provider %s: too many arguments", prov_spec->name); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } for (i = 0; i < prov_spec->args->nelts; i++) { const char *arg = APR_ARRAY_IDX(prov_spec->args, i, const char *); lua_pushstring(L, arg); } nargs = prov_spec->args->nelts; } if (lua_pcall(L, 1 + nargs, 1, 0)) { const char *err = lua_tostring(L, -1); ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02316) "Error executing authz provider %s: %s", prov_spec->name, err); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } if (!lua_isnumber(L, -1)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02317) "Error: authz provider %s did not return integer", prov_spec->name); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } result = lua_tointeger(L, -1); ap_lua_release_state(L, spec, r); switch (result) { case AUTHZ_DENIED: case AUTHZ_GRANTED: case AUTHZ_NEUTRAL: case AUTHZ_GENERAL_ERROR: case AUTHZ_DENIED_NO_USER: return result; default: ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02318) "Error: authz provider %s: invalid return value %d", prov_spec->name, result); } return AUTHZ_GENERAL_ERROR; } Commit Message: Merge r1642499 from trunk: *) SECURITY: CVE-2014-8109 (cve.mitre.org) mod_lua: Fix handling of the Require line when a LuaAuthzProvider is used in multiple Require directives with different arguments. PR57204 [Edward Lu <Chaosed0 gmail.com>] Submitted By: Edward Lu Committed By: covener Submitted by: covener Reviewed/backported by: jim git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1642861 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-264
static authz_status lua_authz_check(request_rec *r, const char *require_line, const void *parsed_require_line) { apr_pool_t *pool; ap_lua_vm_spec *spec; lua_State *L; ap_lua_server_cfg *server_cfg = ap_get_module_config(r->server->module_config, &lua_module); const ap_lua_dir_cfg *cfg = ap_get_module_config(r->per_dir_config, &lua_module); const lua_authz_provider_func *prov_func = parsed_require_line; const lua_authz_provider_spec *prov_spec = prov_func->spec; int result; int nargs = 0; spec = create_vm_spec(&pool, r, cfg, server_cfg, prov_spec->file_name, NULL, 0, prov_spec->function_name, "authz provider"); L = ap_lua_get_lua_state(pool, spec, r); if (L == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02314) "Unable to compile VM for authz provider %s", prov_spec->name); return AUTHZ_GENERAL_ERROR; } lua_getglobal(L, prov_spec->function_name); if (!lua_isfunction(L, -1)) { ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(02319) "Unable to find entry function '%s' in %s (not a valid function)", prov_spec->function_name, prov_spec->file_name); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } ap_lua_run_lua_request(L, r); if (prov_func->args) { int i; if (!lua_checkstack(L, prov_func->args->nelts)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02315) "Error: authz provider %s: too many arguments", prov_spec->name); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } for (i = 0; i < prov_func->args->nelts; i++) { const char *arg = APR_ARRAY_IDX(prov_func->args, i, const char *); lua_pushstring(L, arg); } nargs = prov_func->args->nelts; } if (lua_pcall(L, 1 + nargs, 1, 0)) { const char *err = lua_tostring(L, -1); ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02316) "Error executing authz provider %s: %s", prov_spec->name, err); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } if (!lua_isnumber(L, -1)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02317) "Error: authz provider %s did not return integer", prov_spec->name); ap_lua_release_state(L, spec, r); return AUTHZ_GENERAL_ERROR; } result = lua_tointeger(L, -1); ap_lua_release_state(L, spec, r); switch (result) { case AUTHZ_DENIED: case AUTHZ_GRANTED: case AUTHZ_NEUTRAL: case AUTHZ_GENERAL_ERROR: case AUTHZ_DENIED_NO_USER: return result; default: ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02318) "Error: authz provider %s: invalid return value %d", prov_spec->name, result); } return AUTHZ_GENERAL_ERROR; }
166,250
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: kvp_respond_to_host(char *key, char *value, int error) { struct hv_kvp_msg *kvp_msg; struct hv_kvp_msg_enumerate *kvp_data; char *key_name; struct icmsg_hdr *icmsghdrp; int keylen, valuelen; u32 buf_len; struct vmbus_channel *channel; u64 req_id; /* * If a transaction is not active; log and return. */ if (!kvp_transaction.active) { /* * This is a spurious call! */ pr_warn("KVP: Transaction not active\n"); return; } /* * Copy the global state for completing the transaction. Note that * only one transaction can be active at a time. */ buf_len = kvp_transaction.recv_len; channel = kvp_transaction.recv_channel; req_id = kvp_transaction.recv_req_id; kvp_transaction.active = false; if (channel->onchannel_callback == NULL) /* * We have raced with util driver being unloaded; * silently return. */ return; icmsghdrp = (struct icmsg_hdr *) &recv_buffer[sizeof(struct vmbuspipe_hdr)]; kvp_msg = (struct hv_kvp_msg *) &recv_buffer[sizeof(struct vmbuspipe_hdr) + sizeof(struct icmsg_hdr)]; kvp_data = &kvp_msg->kvp_data; key_name = key; /* * If the error parameter is set, terminate the host's enumeration. */ if (error) { /* * We don't support this index or the we have timedout; * terminate the host-side iteration by returning an error. */ icmsghdrp->status = HV_E_FAIL; goto response_done; } /* * The windows host expects the key/value pair to be encoded * in utf16. */ keylen = utf8s_to_utf16s(key_name, strlen(key_name), (wchar_t *)kvp_data->data.key); kvp_data->data.key_size = 2*(keylen + 1); /* utf16 encoding */ valuelen = utf8s_to_utf16s(value, strlen(value), (wchar_t *)kvp_data->data.value); kvp_data->data.value_size = 2*(valuelen + 1); /* utf16 encoding */ kvp_data->data.value_type = REG_SZ; /* all our values are strings */ icmsghdrp->status = HV_S_OK; response_done: icmsghdrp->icflags = ICMSGHDRFLAG_TRANSACTION | ICMSGHDRFLAG_RESPONSE; vmbus_sendpacket(channel, recv_buffer, buf_len, req_id, VM_PKT_DATA_INBAND, 0); } Commit Message: NLS: improve UTF8 -> UTF16 string conversion routine The utf8s_to_utf16s conversion routine needs to be improved. Unlike its utf16s_to_utf8s sibling, it doesn't accept arguments specifying the maximum length of the output buffer or the endianness of its 16-bit output. This patch (as1501) adds the two missing arguments, and adjusts the only two places in the kernel where the function is called. A follow-on patch will add a third caller that does utilize the new capabilities. The two conversion routines are still annoyingly inconsistent in the way they handle invalid byte combinations. But that's a subject for a different patch. Signed-off-by: Alan Stern <[email protected]> CC: Clemens Ladisch <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119
kvp_respond_to_host(char *key, char *value, int error) { struct hv_kvp_msg *kvp_msg; struct hv_kvp_msg_enumerate *kvp_data; char *key_name; struct icmsg_hdr *icmsghdrp; int keylen, valuelen; u32 buf_len; struct vmbus_channel *channel; u64 req_id; /* * If a transaction is not active; log and return. */ if (!kvp_transaction.active) { /* * This is a spurious call! */ pr_warn("KVP: Transaction not active\n"); return; } /* * Copy the global state for completing the transaction. Note that * only one transaction can be active at a time. */ buf_len = kvp_transaction.recv_len; channel = kvp_transaction.recv_channel; req_id = kvp_transaction.recv_req_id; kvp_transaction.active = false; if (channel->onchannel_callback == NULL) /* * We have raced with util driver being unloaded; * silently return. */ return; icmsghdrp = (struct icmsg_hdr *) &recv_buffer[sizeof(struct vmbuspipe_hdr)]; kvp_msg = (struct hv_kvp_msg *) &recv_buffer[sizeof(struct vmbuspipe_hdr) + sizeof(struct icmsg_hdr)]; kvp_data = &kvp_msg->kvp_data; key_name = key; /* * If the error parameter is set, terminate the host's enumeration. */ if (error) { /* * We don't support this index or the we have timedout; * terminate the host-side iteration by returning an error. */ icmsghdrp->status = HV_E_FAIL; goto response_done; } /* * The windows host expects the key/value pair to be encoded * in utf16. */ keylen = utf8s_to_utf16s(key_name, strlen(key_name), UTF16_HOST_ENDIAN, (wchar_t *) kvp_data->data.key, HV_KVP_EXCHANGE_MAX_KEY_SIZE / 2); kvp_data->data.key_size = 2*(keylen + 1); /* utf16 encoding */ valuelen = utf8s_to_utf16s(value, strlen(value), UTF16_HOST_ENDIAN, (wchar_t *) kvp_data->data.value, HV_KVP_EXCHANGE_MAX_VALUE_SIZE / 2); kvp_data->data.value_size = 2*(valuelen + 1); /* utf16 encoding */ kvp_data->data.value_type = REG_SZ; /* all our values are strings */ icmsghdrp->status = HV_S_OK; response_done: icmsghdrp->icflags = ICMSGHDRFLAG_TRANSACTION | ICMSGHDRFLAG_RESPONSE; vmbus_sendpacket(channel, recv_buffer, buf_len, req_id, VM_PKT_DATA_INBAND, 0); }
166,123
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int prctl_set_vma_anon_name(unsigned long start, unsigned long end, unsigned long arg) { unsigned long tmp; struct vm_area_struct * vma, *prev; int unmapped_error = 0; int error = -EINVAL; /* * If the interval [start,end) covers some unmapped address * ranges, just ignore them, but return -ENOMEM at the end. * - this matches the handling in madvise. */ vma = find_vma_prev(current->mm, start, &prev); if (vma && start > vma->vm_start) prev = vma; for (;;) { /* Still start < end. */ error = -ENOMEM; if (!vma) return error; /* Here start < (end|vma->vm_end). */ if (start < vma->vm_start) { unmapped_error = -ENOMEM; start = vma->vm_start; if (start >= end) return error; } /* Here vma->vm_start <= start < (end|vma->vm_end) */ tmp = vma->vm_end; if (end < tmp) tmp = end; /* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */ error = prctl_update_vma_anon_name(vma, &prev, start, end, (const char __user *)arg); if (error) return error; start = tmp; if (prev && start < prev->vm_end) start = prev->vm_end; error = unmapped_error; if (start >= end) return error; if (prev) vma = prev->vm_next; else /* madvise_remove dropped mmap_sem */ vma = find_vma(current->mm, start); } } Commit Message: mm: fix prctl_set_vma_anon_name prctl_set_vma_anon_name could attempt to set the name across two vmas at the same time due to a typo, which might corrupt the vma list. Fix it to use tmp instead of end to limit the name setting to a single vma at a time. Change-Id: Ie32d8ddb0fd547efbeedd6528acdab5ca5b308b4 Reported-by: Jed Davis <[email protected]> Signed-off-by: Colin Cross <[email protected]> CWE ID: CWE-264
static int prctl_set_vma_anon_name(unsigned long start, unsigned long end, unsigned long arg) { unsigned long tmp; struct vm_area_struct * vma, *prev; int unmapped_error = 0; int error = -EINVAL; /* * If the interval [start,end) covers some unmapped address * ranges, just ignore them, but return -ENOMEM at the end. * - this matches the handling in madvise. */ vma = find_vma_prev(current->mm, start, &prev); if (vma && start > vma->vm_start) prev = vma; for (;;) { /* Still start < end. */ error = -ENOMEM; if (!vma) return error; /* Here start < (end|vma->vm_end). */ if (start < vma->vm_start) { unmapped_error = -ENOMEM; start = vma->vm_start; if (start >= end) return error; } /* Here vma->vm_start <= start < (end|vma->vm_end) */ tmp = vma->vm_end; if (end < tmp) tmp = end; /* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */ error = prctl_update_vma_anon_name(vma, &prev, start, tmp, (const char __user *)arg); if (error) return error; start = tmp; if (prev && start < prev->vm_end) start = prev->vm_end; error = unmapped_error; if (start >= end) return error; if (prev) vma = prev->vm_next; else /* madvise_remove dropped mmap_sem */ vma = find_vma(current->mm, start); } }
173,972
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int bzrtp_packetParser(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, const uint8_t * input, uint16_t inputLength, bzrtpPacket_t *zrtpPacket) { int i; /* now allocate and fill the correct message structure according to the message type */ /* messageContent points to the begining of the ZRTP message */ uint8_t *messageContent = (uint8_t *)(input+ZRTP_PACKET_HEADER_LENGTH+ZRTP_MESSAGE_HEADER_LENGTH); switch (zrtpPacket->messageType) { case MSGTYPE_HELLO : { /* allocate a Hello message structure */ bzrtpHelloMessage_t *messageData; messageData = (bzrtpHelloMessage_t *)malloc(sizeof(bzrtpHelloMessage_t)); /* fill it */ memcpy(messageData->version, messageContent, 4); messageContent +=4; memcpy(messageData->clientIdentifier, messageContent, 16); messageContent +=16; memcpy(messageData->H3, messageContent, 32); messageContent +=32; memcpy(messageData->ZID, messageContent, 12); messageContent +=12; messageData->S = ((*messageContent)>>6)&0x01; messageData->M = ((*messageContent)>>5)&0x01; messageData->P = ((*messageContent)>>4)&0x01; messageContent +=1; messageData->hc = MIN((*messageContent)&0x0F, 7); messageContent +=1; messageData->cc = MIN(((*messageContent)>>4)&0x0F, 7); messageData->ac = MIN((*messageContent)&0x0F, 7); messageContent +=1; messageData->kc = MIN(((*messageContent)>>4)&0x0F, 7); messageData->sc = MIN((*messageContent)&0x0F, 7); messageContent +=1; /* Check message length according to value in hc, cc, ac, kc and sc */ if (zrtpPacket->messageLength != ZRTP_HELLOMESSAGE_FIXED_LENGTH + 4*((uint16_t)(messageData->hc)+(uint16_t)(messageData->cc)+(uint16_t)(messageData->ac)+(uint16_t)(messageData->kc)+(uint16_t)(messageData->sc))) { free(messageData); return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } /* parse the variable length part: algorithms types */ for (i=0; i<messageData->hc; i++) { messageData->supportedHash[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_HASH_TYPE); messageContent +=4; } for (i=0; i<messageData->cc; i++) { messageData->supportedCipher[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_CIPHERBLOCK_TYPE); messageContent +=4; } for (i=0; i<messageData->ac; i++) { messageData->supportedAuthTag[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_AUTHTAG_TYPE); messageContent +=4; } for (i=0; i<messageData->kc; i++) { messageData->supportedKeyAgreement[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_KEYAGREEMENT_TYPE); messageContent +=4; } for (i=0; i<messageData->sc; i++) { messageData->supportedSas[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_SAS_TYPE); messageContent +=4; } addMandatoryCryptoTypesIfNeeded(ZRTP_HASH_TYPE, messageData->supportedHash, &messageData->hc); addMandatoryCryptoTypesIfNeeded(ZRTP_CIPHERBLOCK_TYPE, messageData->supportedCipher, &messageData->cc); addMandatoryCryptoTypesIfNeeded(ZRTP_AUTHTAG_TYPE, messageData->supportedAuthTag, &messageData->ac); addMandatoryCryptoTypesIfNeeded(ZRTP_KEYAGREEMENT_TYPE, messageData->supportedKeyAgreement, &messageData->kc); addMandatoryCryptoTypesIfNeeded(ZRTP_SAS_TYPE, messageData->supportedSas, &messageData->sc); memcpy(messageData->MAC, messageContent, 8); /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; /* the parsed Hello packet must be saved as it may be used to generate commit message or the total_hash */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ } break; /* MSGTYPE_HELLO */ case MSGTYPE_HELLOACK : { /* check message length */ if (zrtpPacket->messageLength != ZRTP_HELLOACKMESSAGE_FIXED_LENGTH) { return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } } break; /* MSGTYPE_HELLOACK */ case MSGTYPE_COMMIT: { uint8_t checkH3[32]; uint8_t checkMAC[32]; bzrtpHelloMessage_t *peerHelloMessageData; uint16_t variableLength = 0; /* allocate a commit message structure */ bzrtpCommitMessage_t *messageData; messageData = (bzrtpCommitMessage_t *)malloc(sizeof(bzrtpCommitMessage_t)); /* fill the structure */ memcpy(messageData->H2, messageContent, 32); messageContent +=32; /* We have now H2, check it matches the H3 we had in the hello message H3=SHA256(H2) and that the Hello message MAC is correct */ if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Hello message in this channel, this commit shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData; /* Check H3 = SHA256(H2) */ bctoolbox_sha256(messageData->H2, 32, 32, checkH3); if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the hello MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(messageData->H2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } memcpy(messageData->ZID, messageContent, 12); messageContent +=12; messageData->hashAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_HASH_TYPE); messageContent += 4; messageData->cipherAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_CIPHERBLOCK_TYPE); messageContent += 4; messageData->authTagAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_AUTHTAG_TYPE); messageContent += 4; messageData->keyAgreementAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_KEYAGREEMENT_TYPE); messageContent += 4; /* commit message length depends on the key agreement type choosen (and set in the zrtpContext->keyAgreementAlgo) */ switch(messageData->keyAgreementAlgo) { case ZRTP_KEYAGREEMENT_DH2k : case ZRTP_KEYAGREEMENT_EC25 : case ZRTP_KEYAGREEMENT_DH3k : case ZRTP_KEYAGREEMENT_EC38 : case ZRTP_KEYAGREEMENT_EC52 : variableLength = 32; /* hvi is 32 bytes length in DH Commit message format */ break; case ZRTP_KEYAGREEMENT_Prsh : variableLength = 24; /* nonce (16 bytes) and keyID(8 bytes) are 24 bytes length in preshared Commit message format */ break; case ZRTP_KEYAGREEMENT_Mult : variableLength = 16; /* nonce is 24 bytes length in multistream Commit message format */ break; default: free(messageData); return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } if (zrtpPacket->messageLength != ZRTP_COMMITMESSAGE_FIXED_LENGTH + variableLength) { free(messageData); return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } messageData->sasAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_SAS_TYPE); messageContent += 4; /* if it is a multistream or preshared commit, get the 16 bytes nonce */ if ((messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) { memcpy(messageData->nonce, messageContent, 16); messageContent +=16; /* and the keyID for preshared commit only */ if (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) { memcpy(messageData->keyID, messageContent, 8); messageContent +=8; } } else { /* it's a DH commit message, get the hvi */ memcpy(messageData->hvi, messageContent, 32); messageContent +=32; } /* get the MAC and attach the message data to the packet structure */ memcpy(messageData->MAC, messageContent, 8); zrtpPacket->messageData = (void *)messageData; /* the parsed commit packet must be saved as it is used to generate the total_hash */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ } break; /* MSGTYPE_COMMIT */ case MSGTYPE_DHPART1 : case MSGTYPE_DHPART2 : { bzrtpDHPartMessage_t *messageData; /*check message length, depends on the selected key agreement algo set in zrtpContext */ uint16_t pvLength = computeKeyAgreementPrivateValueLength(zrtpChannelContext->keyAgreementAlgo); if (pvLength == 0) { return BZRTP_PARSER_ERROR_INVALIDCONTEXT; } if (zrtpPacket->messageLength != ZRTP_DHPARTMESSAGE_FIXED_LENGTH+pvLength) { return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } /* allocate a DHPart message structure and pv */ messageData = (bzrtpDHPartMessage_t *)malloc(sizeof(bzrtpDHPartMessage_t)); messageData->pv = (uint8_t *)malloc(pvLength*sizeof(uint8_t)); /* fill the structure */ memcpy(messageData->H1, messageContent, 32); messageContent +=32; /* We have now H1, check it matches the H2 we had in the commit message H2=SHA256(H1) and that the Commit message MAC is correct */ if ( zrtpChannelContext->role == RESPONDER) { /* do it only if we are responder (we received a commit packet) */ uint8_t checkH2[32]; uint8_t checkMAC[32]; bzrtpCommitMessage_t *peerCommitMessageData; if (zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Commit message in this channel, this DHPart2 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageData; /* Check H2 = SHA256(H1) */ bctoolbox_sha256(messageData->H1, 32, 32, checkH2); if (memcmp(checkH2, peerCommitMessageData->H2, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the Commit MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(messageData->H1, 32, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerCommitMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } else { /* if we are initiator(we didn't received any commit message and then no H2), we must check that H3=SHA256(SHA256(H1)) and the Hello message MAC */ uint8_t checkH2[32]; uint8_t checkH3[32]; uint8_t checkMAC[32]; bzrtpHelloMessage_t *peerHelloMessageData; if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Hello message in this channel, this DHPart1 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData; /* Check H3 = SHA256(SHA256(H1)) */ bctoolbox_sha256(messageData->H1, 32, 32, checkH2); bctoolbox_sha256(checkH2, 32, 32, checkH3); if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the hello MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(checkH2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } memcpy(messageData->rs1ID, messageContent, 8); messageContent +=8; memcpy(messageData->rs2ID, messageContent, 8); messageContent +=8; memcpy(messageData->auxsecretID, messageContent, 8); messageContent +=8; memcpy(messageData->pbxsecretID, messageContent, 8); messageContent +=8; memcpy(messageData->pv, messageContent, pvLength); messageContent +=pvLength; memcpy(messageData->MAC, messageContent, 8); /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; /* the parsed commit packet must be saved as it is used to generate the total_hash */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ } break; /* MSGTYPE_DHPART1 and MSGTYPE_DHPART2 */ case MSGTYPE_CONFIRM1: case MSGTYPE_CONFIRM2: { uint8_t *confirmMessageKey = NULL; uint8_t *confirmMessageMacKey = NULL; bzrtpConfirmMessage_t *messageData; uint16_t cipherTextLength; uint8_t computedHmac[8]; uint8_t *confirmPlainMessageBuffer; uint8_t *confirmPlainMessage; /* we shall first decrypt and validate the message, check we have the keys to do it */ if (zrtpChannelContext->role == RESPONDER) { /* responder uses initiator's keys to decrypt */ if ((zrtpChannelContext->zrtpkeyi == NULL) || (zrtpChannelContext->mackeyi == NULL)) { return BZRTP_PARSER_ERROR_INVALIDCONTEXT; } confirmMessageKey = zrtpChannelContext->zrtpkeyi; confirmMessageMacKey = zrtpChannelContext->mackeyi; } if (zrtpChannelContext->role == INITIATOR) { /* the iniator uses responder's keys to decrypt */ if ((zrtpChannelContext->zrtpkeyr == NULL) || (zrtpChannelContext->mackeyr == NULL)) { return BZRTP_PARSER_ERROR_INVALIDCONTEXT; } confirmMessageKey = zrtpChannelContext->zrtpkeyr; confirmMessageMacKey = zrtpChannelContext->mackeyr; } /* allocate a confirm message structure */ messageData = (bzrtpConfirmMessage_t *)malloc(sizeof(bzrtpConfirmMessage_t)); /* get the mac and the IV */ memcpy(messageData->confirm_mac, messageContent, 8); messageContent +=8; memcpy(messageData->CFBIV, messageContent, 16); messageContent +=16; /* get the cipher text length */ cipherTextLength = zrtpPacket->messageLength - ZRTP_MESSAGE_HEADER_LENGTH - 24; /* confirm message is header, confirm_mac(8 bytes), CFB IV(16 bytes), encrypted part */ /* validate the mac over the cipher text */ zrtpChannelContext->hmacFunction(confirmMessageMacKey, zrtpChannelContext->hashLength, messageContent, cipherTextLength, 8, computedHmac); if (memcmp(computedHmac, messageData->confirm_mac, 8) != 0) { /* confirm_mac doesn't match */ free(messageData); return BZRTP_PARSER_ERROR_UNMATCHINGCONFIRMMAC; } /* get plain message */ confirmPlainMessageBuffer = (uint8_t *)malloc(cipherTextLength*sizeof(uint8_t)); zrtpChannelContext->cipherDecryptionFunction(confirmMessageKey, messageData->CFBIV, messageContent, cipherTextLength, confirmPlainMessageBuffer); confirmPlainMessage = confirmPlainMessageBuffer; /* point into the allocated buffer */ /* parse it */ memcpy(messageData->H0, confirmPlainMessage, 32); confirmPlainMessage +=33; /* +33 because next 8 bits are unused */ /* Hash chain checking: if we are in multichannel or shared mode, we had not DHPart and then no H1 */ if (zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh || zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult) { /* compute the H1=SHA256(H0) we never received */ uint8_t checkH1[32]; bctoolbox_sha256(messageData->H0, 32, 32, checkH1); /* if we are responder, we received a commit packet with H2 then check that H2=SHA256(H1) and that the commit message MAC keyed with H1 match */ if ( zrtpChannelContext->role == RESPONDER) { uint8_t checkH2[32]; uint8_t checkMAC[32]; bzrtpCommitMessage_t *peerCommitMessageData; if (zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Commit message in this channel, this Confirm2 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageData; /* Check H2 = SHA256(H1) */ bctoolbox_sha256(checkH1, 32, 32, checkH2); if (memcmp(checkH2, peerCommitMessageData->H2, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the Commit MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(checkH1, 32, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerCommitMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } else { /* if we are initiator(we didn't received any commit message and then no H2), we must check that H3=SHA256(SHA256(H1)) and the Hello message MAC */ uint8_t checkH2[32]; uint8_t checkH3[32]; uint8_t checkMAC[32]; bzrtpHelloMessage_t *peerHelloMessageData; if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Hello message in this channel, this Confirm1 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData; /* Check H3 = SHA256(SHA256(H1)) */ bctoolbox_sha256(checkH1, 32, 32, checkH2); bctoolbox_sha256(checkH2, 32, 32, checkH3); if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the hello MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(checkH2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } } else { /* we are in DHM mode */ /* We have now H0, check it matches the H1 we had in the DHPart message H1=SHA256(H0) and that the DHPart message MAC is correct */ uint8_t checkH1[32]; uint8_t checkMAC[32]; bzrtpDHPartMessage_t *peerDHPartMessageData; if (zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no DHPART message in this channel, this confirm shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerDHPartMessageData = (bzrtpDHPartMessage_t *)zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageData; /* Check H1 = SHA256(H0) */ bctoolbox_sha256(messageData->H0, 32, 32, checkH1); if (memcmp(checkH1, peerDHPartMessageData->H1, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the DHPart message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(messageData->H0, 32, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerDHPartMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } messageData->sig_len = ((uint16_t)(confirmPlainMessage[0]&0x01))<<8 | (((uint16_t)confirmPlainMessage[1])&0x00FF); confirmPlainMessage += 2; messageData->E = ((*confirmPlainMessage)&0x08)>>3; messageData->V = ((*confirmPlainMessage)&0x04)>>2; messageData->A = ((*confirmPlainMessage)&0x02)>>1; messageData->D = (*confirmPlainMessage)&0x01; confirmPlainMessage += 1; messageData->cacheExpirationInterval = (((uint32_t)confirmPlainMessage[0])<<24) | (((uint32_t)confirmPlainMessage[1])<<16) | (((uint32_t)confirmPlainMessage[2])<<8) | ((uint32_t)confirmPlainMessage[3]); confirmPlainMessage += 4; /* if sig_len indicate a signature, parse it */ if (messageData->sig_len>0) { memcpy(messageData->signatureBlockType, confirmPlainMessage, 4); confirmPlainMessage += 4; /* allocate memory for the signature block, sig_len is in words(32 bits) and includes the signature block type word */ messageData->signatureBlock = (uint8_t *)malloc(4*(messageData->sig_len-1)*sizeof(uint8_t)); memcpy(messageData->signatureBlock, confirmPlainMessage, 4*(messageData->sig_len-1)); } else { messageData->signatureBlock = NULL; } /* free plain buffer */ free(confirmPlainMessageBuffer); /* the parsed commit packet must be saved as it is used to check correct packet repetition */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; } break; /* MSGTYPE_CONFIRM1 and MSGTYPE_CONFIRM2 */ case MSGTYPE_CONF2ACK: /* nothing to do for this one */ break; /* MSGTYPE_CONF2ACK */ case MSGTYPE_PING: { /* allocate a ping message structure */ bzrtpPingMessage_t *messageData; messageData = (bzrtpPingMessage_t *)malloc(sizeof(bzrtpPingMessage_t)); /* fill the structure */ memcpy(messageData->version, messageContent, 4); messageContent +=4; memcpy(messageData->endpointHash, messageContent, 8); /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; } break; /* MSGTYPE_PING */ } return 0; } Commit Message: Add ZRTP Commit packet hvi check on DHPart2 packet reception CWE ID: CWE-254
int bzrtp_packetParser(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, const uint8_t * input, uint16_t inputLength, bzrtpPacket_t *zrtpPacket) { int i; /* now allocate and fill the correct message structure according to the message type */ /* messageContent points to the begining of the ZRTP message */ uint8_t *messageContent = (uint8_t *)(input+ZRTP_PACKET_HEADER_LENGTH+ZRTP_MESSAGE_HEADER_LENGTH); switch (zrtpPacket->messageType) { case MSGTYPE_HELLO : { /* allocate a Hello message structure */ bzrtpHelloMessage_t *messageData; messageData = (bzrtpHelloMessage_t *)malloc(sizeof(bzrtpHelloMessage_t)); /* fill it */ memcpy(messageData->version, messageContent, 4); messageContent +=4; memcpy(messageData->clientIdentifier, messageContent, 16); messageContent +=16; memcpy(messageData->H3, messageContent, 32); messageContent +=32; memcpy(messageData->ZID, messageContent, 12); messageContent +=12; messageData->S = ((*messageContent)>>6)&0x01; messageData->M = ((*messageContent)>>5)&0x01; messageData->P = ((*messageContent)>>4)&0x01; messageContent +=1; messageData->hc = MIN((*messageContent)&0x0F, 7); messageContent +=1; messageData->cc = MIN(((*messageContent)>>4)&0x0F, 7); messageData->ac = MIN((*messageContent)&0x0F, 7); messageContent +=1; messageData->kc = MIN(((*messageContent)>>4)&0x0F, 7); messageData->sc = MIN((*messageContent)&0x0F, 7); messageContent +=1; /* Check message length according to value in hc, cc, ac, kc and sc */ if (zrtpPacket->messageLength != ZRTP_HELLOMESSAGE_FIXED_LENGTH + 4*((uint16_t)(messageData->hc)+(uint16_t)(messageData->cc)+(uint16_t)(messageData->ac)+(uint16_t)(messageData->kc)+(uint16_t)(messageData->sc))) { free(messageData); return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } /* parse the variable length part: algorithms types */ for (i=0; i<messageData->hc; i++) { messageData->supportedHash[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_HASH_TYPE); messageContent +=4; } for (i=0; i<messageData->cc; i++) { messageData->supportedCipher[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_CIPHERBLOCK_TYPE); messageContent +=4; } for (i=0; i<messageData->ac; i++) { messageData->supportedAuthTag[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_AUTHTAG_TYPE); messageContent +=4; } for (i=0; i<messageData->kc; i++) { messageData->supportedKeyAgreement[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_KEYAGREEMENT_TYPE); messageContent +=4; } for (i=0; i<messageData->sc; i++) { messageData->supportedSas[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_SAS_TYPE); messageContent +=4; } addMandatoryCryptoTypesIfNeeded(ZRTP_HASH_TYPE, messageData->supportedHash, &messageData->hc); addMandatoryCryptoTypesIfNeeded(ZRTP_CIPHERBLOCK_TYPE, messageData->supportedCipher, &messageData->cc); addMandatoryCryptoTypesIfNeeded(ZRTP_AUTHTAG_TYPE, messageData->supportedAuthTag, &messageData->ac); addMandatoryCryptoTypesIfNeeded(ZRTP_KEYAGREEMENT_TYPE, messageData->supportedKeyAgreement, &messageData->kc); addMandatoryCryptoTypesIfNeeded(ZRTP_SAS_TYPE, messageData->supportedSas, &messageData->sc); memcpy(messageData->MAC, messageContent, 8); /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; /* the parsed Hello packet must be saved as it may be used to generate commit message or the total_hash */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ } break; /* MSGTYPE_HELLO */ case MSGTYPE_HELLOACK : { /* check message length */ if (zrtpPacket->messageLength != ZRTP_HELLOACKMESSAGE_FIXED_LENGTH) { return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } } break; /* MSGTYPE_HELLOACK */ case MSGTYPE_COMMIT: { uint8_t checkH3[32]; uint8_t checkMAC[32]; bzrtpHelloMessage_t *peerHelloMessageData; uint16_t variableLength = 0; /* allocate a commit message structure */ bzrtpCommitMessage_t *messageData; messageData = (bzrtpCommitMessage_t *)malloc(sizeof(bzrtpCommitMessage_t)); /* fill the structure */ memcpy(messageData->H2, messageContent, 32); messageContent +=32; /* We have now H2, check it matches the H3 we had in the hello message H3=SHA256(H2) and that the Hello message MAC is correct */ if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Hello message in this channel, this commit shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData; /* Check H3 = SHA256(H2) */ bctoolbox_sha256(messageData->H2, 32, 32, checkH3); if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the hello MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(messageData->H2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } memcpy(messageData->ZID, messageContent, 12); messageContent +=12; messageData->hashAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_HASH_TYPE); messageContent += 4; messageData->cipherAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_CIPHERBLOCK_TYPE); messageContent += 4; messageData->authTagAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_AUTHTAG_TYPE); messageContent += 4; messageData->keyAgreementAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_KEYAGREEMENT_TYPE); messageContent += 4; /* commit message length depends on the key agreement type choosen (and set in the zrtpContext->keyAgreementAlgo) */ switch(messageData->keyAgreementAlgo) { case ZRTP_KEYAGREEMENT_DH2k : case ZRTP_KEYAGREEMENT_EC25 : case ZRTP_KEYAGREEMENT_DH3k : case ZRTP_KEYAGREEMENT_EC38 : case ZRTP_KEYAGREEMENT_EC52 : variableLength = 32; /* hvi is 32 bytes length in DH Commit message format */ break; case ZRTP_KEYAGREEMENT_Prsh : variableLength = 24; /* nonce (16 bytes) and keyID(8 bytes) are 24 bytes length in preshared Commit message format */ break; case ZRTP_KEYAGREEMENT_Mult : variableLength = 16; /* nonce is 24 bytes length in multistream Commit message format */ break; default: free(messageData); return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } if (zrtpPacket->messageLength != ZRTP_COMMITMESSAGE_FIXED_LENGTH + variableLength) { free(messageData); return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } messageData->sasAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_SAS_TYPE); messageContent += 4; /* if it is a multistream or preshared commit, get the 16 bytes nonce */ if ((messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) { memcpy(messageData->nonce, messageContent, 16); messageContent +=16; /* and the keyID for preshared commit only */ if (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) { memcpy(messageData->keyID, messageContent, 8); messageContent +=8; } } else { /* it's a DH commit message, get the hvi */ memcpy(messageData->hvi, messageContent, 32); messageContent +=32; } /* get the MAC and attach the message data to the packet structure */ memcpy(messageData->MAC, messageContent, 8); zrtpPacket->messageData = (void *)messageData; /* the parsed commit packet must be saved as it is used to generate the total_hash */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ } break; /* MSGTYPE_COMMIT */ case MSGTYPE_DHPART1 : case MSGTYPE_DHPART2 : { bzrtpDHPartMessage_t *messageData; /*check message length, depends on the selected key agreement algo set in zrtpContext */ uint16_t pvLength = computeKeyAgreementPrivateValueLength(zrtpChannelContext->keyAgreementAlgo); if (pvLength == 0) { return BZRTP_PARSER_ERROR_INVALIDCONTEXT; } if (zrtpPacket->messageLength != ZRTP_DHPARTMESSAGE_FIXED_LENGTH+pvLength) { return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } /* allocate a DHPart message structure and pv */ messageData = (bzrtpDHPartMessage_t *)malloc(sizeof(bzrtpDHPartMessage_t)); messageData->pv = (uint8_t *)malloc(pvLength*sizeof(uint8_t)); /* fill the structure */ memcpy(messageData->H1, messageContent, 32); messageContent +=32; /* We have now H1, check it matches the H2 we had in the commit message H2=SHA256(H1) and that the Commit message MAC is correct */ if ( zrtpChannelContext->role == RESPONDER) { /* do it only if we are responder (we received a commit packet) */ uint8_t checkH2[32]; uint8_t checkMAC[32]; bzrtpCommitMessage_t *peerCommitMessageData; if (zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Commit message in this channel, this DHPart2 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageData; /* Check H2 = SHA256(H1) */ bctoolbox_sha256(messageData->H1, 32, 32, checkH2); if (memcmp(checkH2, peerCommitMessageData->H2, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the Commit MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(messageData->H1, 32, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerCommitMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } /* Check the hvi received in the commit message - RFC section 4.4.1.1*/ /* First compute the expected hvi */ /* hvi = hash(initiator's DHPart2 message(current zrtpPacket)) || responder's Hello message) using the agreed hash function truncated to 256 bits */ /* create a string with the messages concatenated */ { uint8_t computedHvi[32]; uint16_t HelloMessageLength = zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength; uint16_t DHPartHelloMessageStringLength = zrtpPacket->messageLength + HelloMessageLength; uint8_t *DHPartHelloMessageString = (uint8_t *)malloc(DHPartHelloMessageStringLength*sizeof(uint8_t)); memcpy(DHPartHelloMessageString, input+ZRTP_PACKET_HEADER_LENGTH, zrtpPacket->messageLength); memcpy(DHPartHelloMessageString+zrtpPacket->messageLength, zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, HelloMessageLength); zrtpChannelContext->hashFunction(DHPartHelloMessageString, DHPartHelloMessageStringLength, 32, computedHvi); free(DHPartHelloMessageString); /* Compare computed and received hvi */ if (memcmp(computedHvi, peerCommitMessageData->hvi, 32)!=0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHVI; } } } else { /* if we are initiator(we didn't received any commit message and then no H2), we must check that H3=SHA256(SHA256(H1)) and the Hello message MAC */ uint8_t checkH2[32]; uint8_t checkH3[32]; uint8_t checkMAC[32]; bzrtpHelloMessage_t *peerHelloMessageData; if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Hello message in this channel, this DHPart1 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData; /* Check H3 = SHA256(SHA256(H1)) */ bctoolbox_sha256(messageData->H1, 32, 32, checkH2); bctoolbox_sha256(checkH2, 32, 32, checkH3); if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the hello MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(checkH2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } memcpy(messageData->rs1ID, messageContent, 8); messageContent +=8; memcpy(messageData->rs2ID, messageContent, 8); messageContent +=8; memcpy(messageData->auxsecretID, messageContent, 8); messageContent +=8; memcpy(messageData->pbxsecretID, messageContent, 8); messageContent +=8; memcpy(messageData->pv, messageContent, pvLength); messageContent +=pvLength; memcpy(messageData->MAC, messageContent, 8); /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; /* the parsed packet must be saved as it is used to generate the total_hash */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ } break; /* MSGTYPE_DHPART1 and MSGTYPE_DHPART2 */ case MSGTYPE_CONFIRM1: case MSGTYPE_CONFIRM2: { uint8_t *confirmMessageKey = NULL; uint8_t *confirmMessageMacKey = NULL; bzrtpConfirmMessage_t *messageData; uint16_t cipherTextLength; uint8_t computedHmac[8]; uint8_t *confirmPlainMessageBuffer; uint8_t *confirmPlainMessage; /* we shall first decrypt and validate the message, check we have the keys to do it */ if (zrtpChannelContext->role == RESPONDER) { /* responder uses initiator's keys to decrypt */ if ((zrtpChannelContext->zrtpkeyi == NULL) || (zrtpChannelContext->mackeyi == NULL)) { return BZRTP_PARSER_ERROR_INVALIDCONTEXT; } confirmMessageKey = zrtpChannelContext->zrtpkeyi; confirmMessageMacKey = zrtpChannelContext->mackeyi; } if (zrtpChannelContext->role == INITIATOR) { /* the iniator uses responder's keys to decrypt */ if ((zrtpChannelContext->zrtpkeyr == NULL) || (zrtpChannelContext->mackeyr == NULL)) { return BZRTP_PARSER_ERROR_INVALIDCONTEXT; } confirmMessageKey = zrtpChannelContext->zrtpkeyr; confirmMessageMacKey = zrtpChannelContext->mackeyr; } /* allocate a confirm message structure */ messageData = (bzrtpConfirmMessage_t *)malloc(sizeof(bzrtpConfirmMessage_t)); /* get the mac and the IV */ memcpy(messageData->confirm_mac, messageContent, 8); messageContent +=8; memcpy(messageData->CFBIV, messageContent, 16); messageContent +=16; /* get the cipher text length */ cipherTextLength = zrtpPacket->messageLength - ZRTP_MESSAGE_HEADER_LENGTH - 24; /* confirm message is header, confirm_mac(8 bytes), CFB IV(16 bytes), encrypted part */ /* validate the mac over the cipher text */ zrtpChannelContext->hmacFunction(confirmMessageMacKey, zrtpChannelContext->hashLength, messageContent, cipherTextLength, 8, computedHmac); if (memcmp(computedHmac, messageData->confirm_mac, 8) != 0) { /* confirm_mac doesn't match */ free(messageData); return BZRTP_PARSER_ERROR_UNMATCHINGCONFIRMMAC; } /* get plain message */ confirmPlainMessageBuffer = (uint8_t *)malloc(cipherTextLength*sizeof(uint8_t)); zrtpChannelContext->cipherDecryptionFunction(confirmMessageKey, messageData->CFBIV, messageContent, cipherTextLength, confirmPlainMessageBuffer); confirmPlainMessage = confirmPlainMessageBuffer; /* point into the allocated buffer */ /* parse it */ memcpy(messageData->H0, confirmPlainMessage, 32); confirmPlainMessage +=33; /* +33 because next 8 bits are unused */ /* Hash chain checking: if we are in multichannel or shared mode, we had not DHPart and then no H1 */ if (zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh || zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult) { /* compute the H1=SHA256(H0) we never received */ uint8_t checkH1[32]; bctoolbox_sha256(messageData->H0, 32, 32, checkH1); /* if we are responder, we received a commit packet with H2 then check that H2=SHA256(H1) and that the commit message MAC keyed with H1 match */ if ( zrtpChannelContext->role == RESPONDER) { uint8_t checkH2[32]; uint8_t checkMAC[32]; bzrtpCommitMessage_t *peerCommitMessageData; if (zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Commit message in this channel, this Confirm2 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageData; /* Check H2 = SHA256(H1) */ bctoolbox_sha256(checkH1, 32, 32, checkH2); if (memcmp(checkH2, peerCommitMessageData->H2, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the Commit MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(checkH1, 32, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerCommitMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } else { /* if we are initiator(we didn't received any commit message and then no H2), we must check that H3=SHA256(SHA256(H1)) and the Hello message MAC */ uint8_t checkH2[32]; uint8_t checkH3[32]; uint8_t checkMAC[32]; bzrtpHelloMessage_t *peerHelloMessageData; if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Hello message in this channel, this Confirm1 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData; /* Check H3 = SHA256(SHA256(H1)) */ bctoolbox_sha256(checkH1, 32, 32, checkH2); bctoolbox_sha256(checkH2, 32, 32, checkH3); if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the hello MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(checkH2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } } else { /* we are in DHM mode */ /* We have now H0, check it matches the H1 we had in the DHPart message H1=SHA256(H0) and that the DHPart message MAC is correct */ uint8_t checkH1[32]; uint8_t checkMAC[32]; bzrtpDHPartMessage_t *peerDHPartMessageData; if (zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no DHPART message in this channel, this confirm shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerDHPartMessageData = (bzrtpDHPartMessage_t *)zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageData; /* Check H1 = SHA256(H0) */ bctoolbox_sha256(messageData->H0, 32, 32, checkH1); if (memcmp(checkH1, peerDHPartMessageData->H1, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the DHPart message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(messageData->H0, 32, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerDHPartMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } messageData->sig_len = ((uint16_t)(confirmPlainMessage[0]&0x01))<<8 | (((uint16_t)confirmPlainMessage[1])&0x00FF); confirmPlainMessage += 2; messageData->E = ((*confirmPlainMessage)&0x08)>>3; messageData->V = ((*confirmPlainMessage)&0x04)>>2; messageData->A = ((*confirmPlainMessage)&0x02)>>1; messageData->D = (*confirmPlainMessage)&0x01; confirmPlainMessage += 1; messageData->cacheExpirationInterval = (((uint32_t)confirmPlainMessage[0])<<24) | (((uint32_t)confirmPlainMessage[1])<<16) | (((uint32_t)confirmPlainMessage[2])<<8) | ((uint32_t)confirmPlainMessage[3]); confirmPlainMessage += 4; /* if sig_len indicate a signature, parse it */ if (messageData->sig_len>0) { memcpy(messageData->signatureBlockType, confirmPlainMessage, 4); confirmPlainMessage += 4; /* allocate memory for the signature block, sig_len is in words(32 bits) and includes the signature block type word */ messageData->signatureBlock = (uint8_t *)malloc(4*(messageData->sig_len-1)*sizeof(uint8_t)); memcpy(messageData->signatureBlock, confirmPlainMessage, 4*(messageData->sig_len-1)); } else { messageData->signatureBlock = NULL; } /* free plain buffer */ free(confirmPlainMessageBuffer); /* the parsed commit packet must be saved as it is used to check correct packet repetition */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; } break; /* MSGTYPE_CONFIRM1 and MSGTYPE_CONFIRM2 */ case MSGTYPE_CONF2ACK: /* nothing to do for this one */ break; /* MSGTYPE_CONF2ACK */ case MSGTYPE_PING: { /* allocate a ping message structure */ bzrtpPingMessage_t *messageData; messageData = (bzrtpPingMessage_t *)malloc(sizeof(bzrtpPingMessage_t)); /* fill the structure */ memcpy(messageData->version, messageContent, 4); messageContent +=4; memcpy(messageData->endpointHash, messageContent, 8); /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; } break; /* MSGTYPE_PING */ } return 0; }
168,828
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void GetLoadTimes(const v8::FunctionCallbackInfo<v8::Value>& args) { WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); if (frame) { WebDataSource* data_source = frame->dataSource(); if (data_source) { DocumentState* document_state = DocumentState::FromDataSource(data_source); v8::Isolate* isolate = args.GetIsolate(); v8::Local<v8::Object> load_times = v8::Object::New(isolate); load_times->Set( v8::String::NewFromUtf8(isolate, "requestTime"), v8::Number::New(isolate, document_state->request_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "startLoadTime"), v8::Number::New(isolate, document_state->start_load_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "commitLoadTime"), v8::Number::New(isolate, document_state->commit_load_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "finishDocumentLoadTime"), v8::Number::New( isolate, document_state->finish_document_load_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "finishLoadTime"), v8::Number::New(isolate, document_state->finish_load_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "firstPaintTime"), v8::Number::New(isolate, document_state->first_paint_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "firstPaintAfterLoadTime"), v8::Number::New( isolate, document_state->first_paint_after_load_time().ToDoubleT())); load_times->Set( v8::String::NewFromUtf8(isolate, "navigationType"), v8::String::NewFromUtf8( isolate, GetNavigationType(data_source->navigationType()))); load_times->Set( v8::String::NewFromUtf8(isolate, "wasFetchedViaSpdy"), v8::Boolean::New(isolate, document_state->was_fetched_via_spdy())); load_times->Set( v8::String::NewFromUtf8(isolate, "wasNpnNegotiated"), v8::Boolean::New(isolate, document_state->was_npn_negotiated())); load_times->Set( v8::String::NewFromUtf8(isolate, "npnNegotiatedProtocol"), v8::String::NewFromUtf8( isolate, document_state->npn_negotiated_protocol().c_str())); load_times->Set( v8::String::NewFromUtf8(isolate, "wasAlternateProtocolAvailable"), v8::Boolean::New( isolate, document_state->was_alternate_protocol_available())); load_times->Set(v8::String::NewFromUtf8(isolate, "connectionInfo"), v8::String::NewFromUtf8( isolate, net::HttpResponseInfo::ConnectionInfoToString( document_state->connection_info()).c_str())); args.GetReturnValue().Set(load_times); return; } } args.GetReturnValue().SetNull(); } Commit Message: Cache all chrome.loadTimes info before passing them to setters. The setters can invalidate the pointers frame, data_source and document_state. BUG=549251 Review URL: https://codereview.chromium.org/1422753007 Cr-Commit-Position: refs/heads/master@{#357201} CWE ID:
static void GetLoadTimes(const v8::FunctionCallbackInfo<v8::Value>& args) { WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); if (!frame) { args.GetReturnValue().SetNull(); return; } WebDataSource* data_source = frame->dataSource(); if (!data_source) { args.GetReturnValue().SetNull(); return; } DocumentState* document_state = DocumentState::FromDataSource(data_source); if (!document_state) { args.GetReturnValue().SetNull(); return; } double request_time = document_state->request_time().ToDoubleT(); double start_load_time = document_state->start_load_time().ToDoubleT(); double commit_load_time = document_state->commit_load_time().ToDoubleT(); double finish_document_load_time = document_state->finish_document_load_time().ToDoubleT(); double finish_load_time = document_state->finish_load_time().ToDoubleT(); double first_paint_time = document_state->first_paint_time().ToDoubleT(); double first_paint_after_load_time = document_state->first_paint_after_load_time().ToDoubleT(); std::string navigation_type = GetNavigationType(data_source->navigationType()); bool was_fetched_via_spdy = document_state->was_fetched_via_spdy(); bool was_npn_negotiated = document_state->was_npn_negotiated(); std::string npn_negotiated_protocol = document_state->npn_negotiated_protocol(); bool was_alternate_protocol_available = document_state->was_alternate_protocol_available(); std::string connection_info = net::HttpResponseInfo::ConnectionInfoToString( document_state->connection_info()); // Important: |frame|, |data_source| and |document_state| should not be // referred to below this line, as JS setters below can invalidate these // pointers. v8::Isolate* isolate = args.GetIsolate(); v8::Local<v8::Object> load_times = v8::Object::New(isolate); load_times->Set(v8::String::NewFromUtf8(isolate, "requestTime"), v8::Number::New(isolate, request_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "startLoadTime"), v8::Number::New(isolate, start_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "commitLoadTime"), v8::Number::New(isolate, commit_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "finishDocumentLoadTime"), v8::Number::New(isolate, finish_document_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "finishLoadTime"), v8::Number::New(isolate, finish_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "firstPaintTime"), v8::Number::New(isolate, first_paint_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "firstPaintAfterLoadTime"), v8::Number::New(isolate, first_paint_after_load_time)); load_times->Set(v8::String::NewFromUtf8(isolate, "navigationType"), v8::String::NewFromUtf8(isolate, navigation_type.c_str())); load_times->Set(v8::String::NewFromUtf8(isolate, "wasFetchedViaSpdy"), v8::Boolean::New(isolate, was_fetched_via_spdy)); load_times->Set(v8::String::NewFromUtf8(isolate, "wasNpnNegotiated"), v8::Boolean::New(isolate, was_npn_negotiated)); load_times->Set( v8::String::NewFromUtf8(isolate, "npnNegotiatedProtocol"), v8::String::NewFromUtf8(isolate, npn_negotiated_protocol.c_str())); load_times->Set( v8::String::NewFromUtf8(isolate, "wasAlternateProtocolAvailable"), v8::Boolean::New(isolate, was_alternate_protocol_available)); load_times->Set(v8::String::NewFromUtf8(isolate, "connectionInfo"), v8::String::NewFromUtf8(isolate, connection_info.c_str())); args.GetReturnValue().Set(load_times); }
171,766
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void IBusBusGlobalEngineChangedCallback( IBusBus* bus, const gchar* engine_name, gpointer user_data) { DCHECK(engine_name); DLOG(INFO) << "Global engine is changed to " << engine_name; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->UpdateUI(engine_name); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static void IBusBusGlobalEngineChangedCallback( void IBusBusGlobalEngineChanged(IBusBus* bus, const gchar* engine_name) { DCHECK(engine_name); VLOG(1) << "Global engine is changed to " << engine_name; UpdateUI(engine_name); }
170,538
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GLboolean WebGLRenderingContextBase::isRenderbuffer( WebGLRenderbuffer* renderbuffer) { if (!renderbuffer || isContextLost()) return 0; if (!renderbuffer->HasEverBeenBound()) return 0; if (renderbuffer->IsDeleted()) return 0; return ContextGL()->IsRenderbuffer(renderbuffer->Object()); } Commit Message: Validate all incoming WebGLObjects. A few entry points were missing the correct validation. Tested with improved conformance tests in https://github.com/KhronosGroup/WebGL/pull/2654 . Bug: 848914 Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008 Reviewed-on: https://chromium-review.googlesource.com/1086718 Reviewed-by: Kai Ninomiya <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Commit-Queue: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#565016} CWE ID: CWE-119
GLboolean WebGLRenderingContextBase::isRenderbuffer( WebGLRenderbuffer* renderbuffer) { if (!renderbuffer || isContextLost() || !renderbuffer->Validate(ContextGroup(), this)) return 0; if (!renderbuffer->HasEverBeenBound()) return 0; if (renderbuffer->IsDeleted()) return 0; return ContextGL()->IsRenderbuffer(renderbuffer->Object()); }
173,131
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LayerWebKitThread::setNeedsCommit() { if (m_owner) m_owner->notifySyncRequired(); } Commit Message: [BlackBerry] GraphicsLayer: rename notifySyncRequired to notifyFlushRequired https://bugs.webkit.org/show_bug.cgi?id=111997 Patch by Alberto Garcia <[email protected]> on 2013-03-11 Reviewed by Rob Buis. This changed in r130439 but the old name was introduced again by mistake in r144465. * platform/graphics/blackberry/GraphicsLayerBlackBerry.h: (WebCore::GraphicsLayerBlackBerry::notifyFlushRequired): * platform/graphics/blackberry/LayerWebKitThread.cpp: (WebCore::LayerWebKitThread::setNeedsCommit): git-svn-id: svn://svn.chromium.org/blink/trunk@145363 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
void LayerWebKitThread::setNeedsCommit() { // Call notifyFlushRequired(), which in this implementation plumbs through to if (m_owner) m_owner->notifyFlushRequired(); }
171,591
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_netscreen_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf, char *line, int *err, gchar **err_info) { int sec; int dsec; char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH]; char direction[2]; guint pkt_len; char cap_src[13]; char cap_dst[13]; guint8 *pd; gchar *p; int n, i = 0; guint offset = 0; gchar dststr[13]; phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9u:%12s->%12s/", &sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: Can't parse packet-header"); return -1; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("netscreen: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } /* * If direction[0] is 'o', the direction is NETSCREEN_EGRESS, * otherwise it's NETSCREEN_INGRESS. */ phdr->ts.secs = sec; phdr->ts.nsecs = dsec * 100000000; phdr->len = pkt_len; /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); while(1) { /* The last packet is not delimited by an empty line, but by EOF * So accept EOF as a valid delimiter too */ if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) { break; } /* * Skip blanks. * The number of blanks is not fixed - for wireless * interfaces, there may be 14 extra spaces before * the hex data. */ for (p = &line[0]; g_ascii_isspace(*p); p++) ; /* packets are delimited with empty lines */ if (*p == '\0') { break; } n = parse_single_hex_dump_line(p, pd, offset); /* the smallest packet has a length of 6 bytes, if * the first hex-data is less then check whether * it is a info-line and act accordingly */ if (offset == 0 && n < 6) { if (info_line(line)) { if (++i <= NETSCREEN_MAX_INFOLINES) { continue; } } else { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: cannot parse hex-data"); return FALSE; } } /* If there is no more data and the line was not empty, * then there must be an error in the file */ if (n == -1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: cannot parse hex-data"); return FALSE; } /* Adjust the offset to the data that was just added to the buffer */ offset += n; /* If there was more hex-data than was announced in the len=x * header, then then there must be an error in the file */ if (offset > pkt_len) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: too much hex-data"); return FALSE; } } /* * Determine the encapsulation type, based on the * first 4 characters of the interface name * * XXX convert this to a 'case' structure when adding more * (non-ethernet) interfacetypes */ if (strncmp(cap_int, "adsl", 4) == 0) { /* The ADSL interface can be bridged with or without * PPP encapsulation. Check whether the first six bytes * of the hex data are the same as the destination mac * address in the header. If they are, assume ethernet * LinkLayer or else PPP */ g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x", pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]); if (strncmp(dststr, cap_dst, 12) == 0) phdr->pkt_encap = WTAP_ENCAP_ETHERNET; else phdr->pkt_encap = WTAP_ENCAP_PPP; } else if (strncmp(cap_int, "seri", 4) == 0) phdr->pkt_encap = WTAP_ENCAP_PPP; else phdr->pkt_encap = WTAP_ENCAP_ETHERNET; phdr->caplen = offset; return TRUE; } Commit Message: Don't treat the packet length as unsigned. The scanf family of functions are as annoyingly bad at handling unsigned numbers as strtoul() is - both of them are perfectly willing to accept a value beginning with a negative sign as an unsigned value. When using strtoul(), you can compensate for this by explicitly checking for a '-' as the first character of the string, but you can't do that with sscanf(). So revert to having pkt_len be signed, and scanning it with %d, but check for a negative value and fail if we see a negative value. Bug: 12396 Change-Id: I54fe8f61f42c32b5ef33da633ece51bbcda8c95f Reviewed-on: https://code.wireshark.org/review/15220 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-20
parse_netscreen_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf, char *line, int *err, gchar **err_info) { int pkt_len; int sec; int dsec; char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH]; char direction[2]; char cap_src[13]; char cap_dst[13]; guint8 *pd; gchar *p; int n, i = 0; int offset = 0; gchar dststr[13]; phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9d:%12s->%12s/", &sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: Can't parse packet-header"); return -1; } if (pkt_len < 0) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: packet header has a negative packet length"); return FALSE; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("netscreen: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } /* * If direction[0] is 'o', the direction is NETSCREEN_EGRESS, * otherwise it's NETSCREEN_INGRESS. */ phdr->ts.secs = sec; phdr->ts.nsecs = dsec * 100000000; phdr->len = pkt_len; /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); while(1) { /* The last packet is not delimited by an empty line, but by EOF * So accept EOF as a valid delimiter too */ if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) { break; } /* * Skip blanks. * The number of blanks is not fixed - for wireless * interfaces, there may be 14 extra spaces before * the hex data. */ for (p = &line[0]; g_ascii_isspace(*p); p++) ; /* packets are delimited with empty lines */ if (*p == '\0') { break; } n = parse_single_hex_dump_line(p, pd, offset); /* the smallest packet has a length of 6 bytes, if * the first hex-data is less then check whether * it is a info-line and act accordingly */ if (offset == 0 && n < 6) { if (info_line(line)) { if (++i <= NETSCREEN_MAX_INFOLINES) { continue; } } else { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: cannot parse hex-data"); return FALSE; } } /* If there is no more data and the line was not empty, * then there must be an error in the file */ if (n == -1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: cannot parse hex-data"); return FALSE; } /* Adjust the offset to the data that was just added to the buffer */ offset += n; /* If there was more hex-data than was announced in the len=x * header, then then there must be an error in the file */ if (offset > pkt_len) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: too much hex-data"); return FALSE; } } /* * Determine the encapsulation type, based on the * first 4 characters of the interface name * * XXX convert this to a 'case' structure when adding more * (non-ethernet) interfacetypes */ if (strncmp(cap_int, "adsl", 4) == 0) { /* The ADSL interface can be bridged with or without * PPP encapsulation. Check whether the first six bytes * of the hex data are the same as the destination mac * address in the header. If they are, assume ethernet * LinkLayer or else PPP */ g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x", pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]); if (strncmp(dststr, cap_dst, 12) == 0) phdr->pkt_encap = WTAP_ENCAP_ETHERNET; else phdr->pkt_encap = WTAP_ENCAP_PPP; } else if (strncmp(cap_int, "seri", 4) == 0) phdr->pkt_encap = WTAP_ENCAP_PPP; else phdr->pkt_encap = WTAP_ENCAP_ETHERNET; phdr->caplen = offset; return TRUE; }
169,962
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) { List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } if (inHeader->nOffset == 0) { mAnchorTimeUs = inHeader->nTimeStamp; mNumSamplesOutput = 0; } const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset; int32_t numBytesRead; if (mMode == MODE_NARROW) { if (outHeader->nAllocLen < kNumSamplesPerFrameNB * sizeof(int16_t)) { ALOGE("b/27662364: NB expected output buffer %zu bytes vs %u", kNumSamplesPerFrameNB * sizeof(int16_t), outHeader->nAllocLen); android_errorWriteLog(0x534e4554, "27662364"); notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); mSignalledError = true; return; } numBytesRead = AMRDecode(mState, (Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f), (UWord8 *)&inputPtr[1], reinterpret_cast<int16_t *>(outHeader->pBuffer), MIME_IETF); if (numBytesRead == -1) { ALOGE("PV AMR decoder AMRDecode() call failed"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } ++numBytesRead; // Include the frame type header byte. if (static_cast<size_t>(numBytesRead) > inHeader->nFilledLen) { notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } } else { if (outHeader->nAllocLen < kNumSamplesPerFrameWB * sizeof(int16_t)) { ALOGE("b/27662364: WB expected output buffer %zu bytes vs %u", kNumSamplesPerFrameWB * sizeof(int16_t), outHeader->nAllocLen); android_errorWriteLog(0x534e4554, "27662364"); notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); mSignalledError = true; return; } int16 mode = ((inputPtr[0] >> 3) & 0x0f); if (mode >= 10 && mode <= 13) { ALOGE("encountered illegal frame type %d in AMR WB content.", mode); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } size_t frameSize = getFrameSize(mode); CHECK_GE(inHeader->nFilledLen, frameSize); int16_t *outPtr = (int16_t *)outHeader->pBuffer; if (mode >= 9) { memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t)); } else if (mode < 9) { int16 frameType; RX_State_wb rx_state; mime_unsorting( const_cast<uint8_t *>(&inputPtr[1]), mInputSampleBuffer, &frameType, &mode, 1, &rx_state); int16_t numSamplesOutput; pvDecoder_AmrWb( mode, mInputSampleBuffer, outPtr, &numSamplesOutput, mDecoderBuf, frameType, mDecoderCookie); CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB); for (int i = 0; i < kNumSamplesPerFrameWB; ++i) { /* Delete the 2 LSBs (14-bit output) */ outPtr[i] &= 0xfffC; } } numBytesRead = frameSize; } inHeader->nOffset += numBytesRead; inHeader->nFilledLen -= numBytesRead; outHeader->nFlags = 0; outHeader->nOffset = 0; if (mMode == MODE_NARROW) { outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateNB; mNumSamplesOutput += kNumSamplesPerFrameNB; } else { outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateWB; mNumSamplesOutput += kNumSamplesPerFrameWB; } if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; ++mInputBufferCount; } } Commit Message: SoftAMR: check input buffer size to avoid overflow. Bug: 27662364 Change-Id: I47380545ea7d85845e141e722b0d84f498d27145 CWE ID: CWE-264
void SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) { List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); notifyEmptyBufferDone(inHeader); continue; } BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } if (inHeader->nOffset == 0) { mAnchorTimeUs = inHeader->nTimeStamp; mNumSamplesOutput = 0; } const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset; int32_t numBytesRead; if (mMode == MODE_NARROW) { if (outHeader->nAllocLen < kNumSamplesPerFrameNB * sizeof(int16_t)) { ALOGE("b/27662364: NB expected output buffer %zu bytes vs %u", kNumSamplesPerFrameNB * sizeof(int16_t), outHeader->nAllocLen); android_errorWriteLog(0x534e4554, "27662364"); notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); mSignalledError = true; return; } int16 mode = ((inputPtr[0] >> 3) & 0x0f); // for WMF since MIME_IETF is used when calling AMRDecode. size_t frameSize = WmfDecBytesPerFrame[mode] + 1; if (inHeader->nFilledLen < frameSize) { ALOGE("b/27662364: expected %zu bytes vs %u", frameSize, inHeader->nFilledLen); notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL); mSignalledError = true; return; } numBytesRead = AMRDecode(mState, (Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f), (UWord8 *)&inputPtr[1], reinterpret_cast<int16_t *>(outHeader->pBuffer), MIME_IETF); if (numBytesRead == -1) { ALOGE("PV AMR decoder AMRDecode() call failed"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } ++numBytesRead; // Include the frame type header byte. if (static_cast<size_t>(numBytesRead) > inHeader->nFilledLen) { notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } } else { if (outHeader->nAllocLen < kNumSamplesPerFrameWB * sizeof(int16_t)) { ALOGE("b/27662364: WB expected output buffer %zu bytes vs %u", kNumSamplesPerFrameWB * sizeof(int16_t), outHeader->nAllocLen); android_errorWriteLog(0x534e4554, "27662364"); notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); mSignalledError = true; return; } int16 mode = ((inputPtr[0] >> 3) & 0x0f); if (mode >= 10 && mode <= 13) { ALOGE("encountered illegal frame type %d in AMR WB content.", mode); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } size_t frameSize = getFrameSize(mode); if (inHeader->nFilledLen < frameSize) { ALOGE("b/27662364: expected %zu bytes vs %u", frameSize, inHeader->nFilledLen); notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL); mSignalledError = true; return; } int16_t *outPtr = (int16_t *)outHeader->pBuffer; if (mode >= 9) { memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t)); } else if (mode < 9) { int16 frameType; RX_State_wb rx_state; mime_unsorting( const_cast<uint8_t *>(&inputPtr[1]), mInputSampleBuffer, &frameType, &mode, 1, &rx_state); int16_t numSamplesOutput; pvDecoder_AmrWb( mode, mInputSampleBuffer, outPtr, &numSamplesOutput, mDecoderBuf, frameType, mDecoderCookie); CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB); for (int i = 0; i < kNumSamplesPerFrameWB; ++i) { /* Delete the 2 LSBs (14-bit output) */ outPtr[i] &= 0xfffC; } } numBytesRead = frameSize; } inHeader->nOffset += numBytesRead; inHeader->nFilledLen -= numBytesRead; outHeader->nFlags = 0; outHeader->nOffset = 0; if (mMode == MODE_NARROW) { outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateNB; mNumSamplesOutput += kNumSamplesPerFrameNB; } else { outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateWB; mNumSamplesOutput += kNumSamplesPerFrameWB; } if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; ++mInputBufferCount; } }
174,231
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DownloadController::OnDownloadStarted( DownloadItem* download_item) { DCHECK_CURRENTLY_ON(BrowserThread::UI); WebContents* web_contents = download_item->GetWebContents(); if (!web_contents) return; download_item->AddObserver(this); ChromeDownloadDelegate::FromWebContents(web_contents)->OnDownloadStarted( download_item->GetTargetFilePath().BaseName().value(), download_item->GetMimeType()); } Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack The only exception is OMA DRM download. And it only applies to context menu download interception. Clean up the remaining unused code now. BUG=647755 Review-Url: https://codereview.chromium.org/2371773003 Cr-Commit-Position: refs/heads/master@{#421332} CWE ID: CWE-254
void DownloadController::OnDownloadStarted( DownloadItem* download_item) { DCHECK_CURRENTLY_ON(BrowserThread::UI); WebContents* web_contents = download_item->GetWebContents(); if (!web_contents) return; download_item->AddObserver(this); ChromeDownloadDelegate::FromWebContents(web_contents)->OnDownloadStarted( download_item->GetTargetFilePath().BaseName().value()); }
171,882
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: jbig2_decode_mmr_init(Jbig2MmrCtx *mmr, int width, int height, const byte *data, size_t size) { int i; uint32_t word = 0; mmr->width = width; mmr->size = size; mmr->data_index = 0; mmr->bit_index = 0; for (i = 0; i < size && i < 4; i++) word |= (data[i] << ((3 - i) << 3)); mmr->word = word; } Commit Message: CWE ID: CWE-119
jbig2_decode_mmr_init(Jbig2MmrCtx *mmr, int width, int height, const byte *data, size_t size) { size_t i; uint32_t word = 0; mmr->width = width; mmr->size = size; mmr->data_index = 0; mmr->bit_index = 0; for (i = 0; i < size && i < 4; i++) word |= (data[i] << ((3 - i) << 3)); mmr->word = word; }
165,493