prompt
stringlengths 1.19k
236k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
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(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 != 24))
{
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/654
CWE ID: CWE-400
Target: 1
Example 2:
Code: static size_t mptsas_config_pack(uint8_t **data, const char *fmt, ...)
{
va_list ap;
size_t ret;
va_start(ap, fmt);
ret = vpack(data, fmt, ap);
va_end(ap);
if (data) {
assert(ret / 4 < 256 && (ret % 4) == 0);
stb_p(*data + 1, ret / 4);
}
return ret;
}
Commit Message:
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
Image *image)
{
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
currentOffset,
offset,
scene;
MagickSizeType
cc;
PixelPacket
transpix;
QuantizeInfo
*quantize_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*p;
ssize_t
y;
size_t
count,
bits_per_pixel,
bytes_per_row,
nextDepthOffset,
one;
unsigned char
bit,
byte,
color,
*lastrow,
*one_row,
*ptr,
version;
unsigned int
transparentIndex;
unsigned short
color16,
flags;
/*
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);
exception=AcquireExceptionInfo();
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
quantize_info=AcquireQuantizeInfo(image_info);
flags=0;
currentOffset=0;
transparentIndex=0;
transpix.red=0;
transpix.green=0;
transpix.blue=0;
transpix.opacity=0;
one=1;
version=0;
scene=0;
do
{
(void) TransformImageColorspace(image,sRGBColorspace);
count=GetNumberColors(image,NULL,exception);
for (bits_per_pixel=1; (one << bits_per_pixel) < count; bits_per_pixel*=2) ;
if (bits_per_pixel > 16)
bits_per_pixel=16;
else
if (bits_per_pixel < 16)
(void) TransformImageColorspace(image,image->colorspace);
if (bits_per_pixel < 8)
{
(void) TransformImageColorspace(image,GRAYColorspace);
(void) SetImageType(image,PaletteType);
(void) SortColormapByIntensity(image);
}
if ((image->storage_class == PseudoClass) && (image->colors > 256))
(void) SetImageStorageClass(image,DirectClass);
if (image->storage_class == PseudoClass)
flags|=PALM_HAS_COLORMAP_FLAG;
else
flags|=PALM_IS_DIRECT_COLOR;
(void) WriteBlobMSBShort(image,(unsigned short) image->columns); /* width */
(void) WriteBlobMSBShort(image,(unsigned short) image->rows); /* height */
bytes_per_row=((image->columns+(16/bits_per_pixel-1))/(16/
bits_per_pixel))*2;
(void) WriteBlobMSBShort(image,(unsigned short) bytes_per_row);
if ((image_info->compression == RLECompression) ||
(image_info->compression == FaxCompression))
flags|=PALM_IS_COMPRESSED_FLAG;
(void) WriteBlobMSBShort(image, flags);
(void) WriteBlobByte(image,(unsigned char) bits_per_pixel);
if (bits_per_pixel > 1)
version=1;
if ((image_info->compression == RLECompression) ||
(image_info->compression == FaxCompression))
version=2;
(void) WriteBlobByte(image,version);
(void) WriteBlobMSBShort(image,0); /* nextDepthOffset */
(void) WriteBlobByte(image,(unsigned char) transparentIndex);
if (image_info->compression == RLECompression)
(void) WriteBlobByte(image,PALM_COMPRESSION_RLE);
else
if (image_info->compression == FaxCompression)
(void) WriteBlobByte(image,PALM_COMPRESSION_SCANLINE);
else
(void) WriteBlobByte(image,PALM_COMPRESSION_NONE);
(void) WriteBlobMSBShort(image,0); /* reserved */
offset=16;
if (bits_per_pixel == 16)
{
(void) WriteBlobByte(image,5); /* # of bits of red */
(void) WriteBlobByte(image,6); /* # of bits of green */
(void) WriteBlobByte(image,5); /* # of bits of blue */
(void) WriteBlobByte(image,0); /* reserved by Palm */
(void) WriteBlobMSBLong(image,0); /* no transparent color, YET */
offset+=8;
}
if (bits_per_pixel == 8)
{
if (flags & PALM_HAS_COLORMAP_FLAG) /* Write out colormap */
{
quantize_info->dither=IsPaletteImage(image,&image->exception);
quantize_info->number_colors=image->colors;
(void) QuantizeImage(quantize_info,image);
(void) WriteBlobMSBShort(image,(unsigned short) image->colors);
for (count = 0; count < image->colors; count++)
{
(void) WriteBlobByte(image,(unsigned char) count);
(void) WriteBlobByte(image,ScaleQuantumToChar(
image->colormap[count].red));
(void) WriteBlobByte(image,
ScaleQuantumToChar(image->colormap[count].green));
(void) WriteBlobByte(image,
ScaleQuantumToChar(image->colormap[count].blue));
}
offset+=2+count*4;
}
else /* Map colors to Palm standard colormap */
{
Image
*affinity_image;
affinity_image=ConstituteImage(256,1,"RGB",CharPixel,&PalmPalette,
exception);
(void) TransformImageColorspace(affinity_image,
affinity_image->colorspace);
(void) RemapImage(quantize_info,image,affinity_image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetAuthenticPixels(image,0,y,image->columns,1,exception);
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,FindColor(&image->colormap[
(ssize_t) GetPixelIndex(indexes+x)]));
}
affinity_image=DestroyImage(affinity_image);
}
}
if (flags & PALM_IS_COMPRESSED_FLAG)
(void) WriteBlobMSBShort(image,0); /* fill in size later */
lastrow=(unsigned char *) NULL;
if (image_info->compression == FaxCompression)
lastrow=(unsigned char *) AcquireQuantumMemory(bytes_per_row,
sizeof(*lastrow));
/* TODO check whether memory really was acquired? */
one_row=(unsigned char *) AcquireQuantumMemory(bytes_per_row,
sizeof(*one_row));
if (one_row == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
ptr=one_row;
(void) ResetMagickMemory(ptr,0,bytes_per_row);
p=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (p == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if (bits_per_pixel == 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
color16=(unsigned short) ((((31*(size_t) GetPixelRed(p))/
(size_t) QuantumRange) << 11) |
(((63*(size_t) GetPixelGreen(p))/(size_t) QuantumRange) << 5) |
((31*(size_t) GetPixelBlue(p))/(size_t) QuantumRange));
if (GetPixelOpacity(p) == (Quantum) TransparentOpacity)
{
transpix.red=GetPixelRed(p);
transpix.green=GetPixelGreen(p);
transpix.blue=GetPixelBlue(p);
transpix.opacity=GetPixelOpacity(p);
flags|=PALM_HAS_TRANSPARENCY_FLAG;
}
*ptr++=(unsigned char) ((color16 >> 8) & 0xff);
*ptr++=(unsigned char) (color16 & 0xff);
p++;
}
}
else
{
byte=0x00;
bit=(unsigned char) (8-bits_per_pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bits_per_pixel >= 8)
color=(unsigned char) GetPixelIndex(indexes+x);
else
color=(unsigned char) (GetPixelIndex(indexes+x)*
((one << bits_per_pixel)-1)/MagickMax(1*image->colors-1,1));
byte|=color << bit;
if (bit != 0)
bit-=(unsigned char) bits_per_pixel;
else
{
*ptr++=byte;
byte=0x00;
bit=(unsigned char) (8-bits_per_pixel);
}
}
if ((image->columns % (8/bits_per_pixel)) != 0)
*ptr++=byte;
}
if (image_info->compression == RLECompression)
{
x=0;
while (x < (ssize_t) bytes_per_row)
{
byte=one_row[x];
count=1;
while ((one_row[++x] == byte) && (count < 255) &&
(x < (ssize_t) bytes_per_row))
count++;
(void) WriteBlobByte(image,(unsigned char) count);
(void) WriteBlobByte(image,(unsigned char) byte);
}
}
else
if (image_info->compression == FaxCompression)
{
char
tmpbuf[8],
*tptr;
for (x = 0; x < (ssize_t) bytes_per_row; x += 8)
{
tptr = tmpbuf;
for (bit=0, byte=0; bit < (unsigned char) MagickMin(8,(ssize_t) bytes_per_row-x); bit++)
{
if ((y == 0) || (lastrow[x + bit] != one_row[x + bit]))
{
byte |= (1 << (7 - bit));
*tptr++ = (char) one_row[x + bit];
}
}
(void) WriteBlobByte(image, byte);
(void) WriteBlob(image,tptr-tmpbuf,(unsigned char *) tmpbuf);
}
(void) CopyMagickMemory(lastrow,one_row,bytes_per_row);
}
else
(void) WriteBlob(image,bytes_per_row,one_row);
}
if (flags & PALM_HAS_TRANSPARENCY_FLAG)
{
offset=SeekBlob(image,currentOffset+6,SEEK_SET);
(void) WriteBlobMSBShort(image,flags);
offset=SeekBlob(image,currentOffset+12,SEEK_SET);
(void) WriteBlobByte(image,(unsigned char) transparentIndex); /* trans index */
}
if (bits_per_pixel == 16)
{
offset=SeekBlob(image,currentOffset+20,SEEK_SET);
(void) WriteBlobByte(image,0); /* reserved by Palm */
(void) WriteBlobByte(image,(unsigned char) ((31*transpix.red)/QuantumRange));
(void) WriteBlobByte(image,(unsigned char) ((63*transpix.green)/QuantumRange));
(void) WriteBlobByte(image,(unsigned char) ((31*transpix.blue)/QuantumRange));
}
if (flags & PALM_IS_COMPRESSED_FLAG) /* fill in size now */
{
offset=SeekBlob(image,currentOffset+offset,SEEK_SET);
(void) WriteBlobMSBShort(image,(unsigned short) (GetBlobSize(image)-
currentOffset-offset));
}
if (one_row != (unsigned char *) NULL)
one_row=(unsigned char *) RelinquishMagickMemory(one_row);
if (lastrow != (unsigned char *) NULL)
lastrow=(unsigned char *) RelinquishMagickMemory(lastrow);
if (GetNextImageInList(image) == (Image *) NULL)
break;
/* padding to 4 byte word */
for (cc=(GetBlobSize(image)) % 4; cc > 0; cc--)
(void) WriteBlobByte(image,0);
/* write nextDepthOffset and return to end of image */
(void) SeekBlob(image,currentOffset+10,SEEK_SET);
nextDepthOffset=(size_t) ((GetBlobSize(image)-currentOffset)/4);
(void) WriteBlobMSBShort(image,(unsigned short) nextDepthOffset);
currentOffset=(MagickOffsetType) GetBlobSize(image);
(void) SeekBlob(image,currentOffset,SEEK_SET);
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
quantize_info=DestroyQuantizeInfo(quantize_info);
(void) CloseBlob(image);
(void) DestroyExceptionInfo(exception);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/574
CWE ID: CWE-772
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int sco_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct sco_options opts;
struct sco_conninfo cinfo;
int len, err = 0;
BT_DBG("sk %p", sk);
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case SCO_OPTIONS:
if (sk->sk_state != BT_CONNECTED) {
err = -ENOTCONN;
break;
}
opts.mtu = sco_pi(sk)->conn->mtu;
BT_DBG("mtu %d", opts.mtu);
len = min_t(unsigned int, len, sizeof(opts));
if (copy_to_user(optval, (char *)&opts, len))
err = -EFAULT;
break;
case SCO_CONNINFO:
if (sk->sk_state != BT_CONNECTED) {
err = -ENOTCONN;
break;
}
cinfo.hci_handle = sco_pi(sk)->conn->hcon->handle;
memcpy(cinfo.dev_class, sco_pi(sk)->conn->hcon->dev_class, 3);
len = min_t(unsigned int, len, sizeof(cinfo));
if (copy_to_user(optval, (char *)&cinfo, len))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
Commit Message: Bluetooth: sco: fix information leak to userspace
struct sco_conninfo has one padding byte in the end. Local variable
cinfo of type sco_conninfo is copied to userspace with this uninizialized
one byte, leading to old stack contents leak.
Signed-off-by: Vasiliy Kulikov <[email protected]>
Signed-off-by: Gustavo F. Padovan <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: SYSCALL_DEFINE4(send, int, fd, void __user *, buff, size_t, len,
unsigned, flags)
{
return sys_sendto(fd, buff, len, flags, NULL, 0);
}
Commit Message: sendmmsg/sendmsg: fix unsafe user pointer access
Dereferencing a user pointer directly from kernel-space without going
through the copy_from_user family of functions is a bad idea. Two of
such usages can be found in the sendmsg code path called from sendmmsg,
added by
commit c71d8ebe7a4496fb7231151cb70a6baa0cb56f9a upstream.
commit 5b47b8038f183b44d2d8ff1c7d11a5c1be706b34 in the 3.0-stable tree.
Usages are performed through memcmp() and memcpy() directly. Fix those
by using the already copied msg_sys structure instead of the __user *msg
structure. Note that msg_sys can be set to NULL by verify_compat_iovec()
or verify_iovec(), which requires additional NULL pointer checks.
Signed-off-by: Mathieu Desnoyers <[email protected]>
Signed-off-by: David Goulet <[email protected]>
CC: Tetsuo Handa <[email protected]>
CC: Anton Blanchard <[email protected]>
CC: David S. Miller <[email protected]>
CC: stable <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void V8TestObject::VoidMethodArrayOfDoubleOrDOMStringArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_voidMethodArrayOfDoubleOrDOMStringArg");
test_object_v8_internal::VoidMethodArrayOfDoubleOrDOMStringArgMethod(info);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int main(int argc, char **argv) {
FILE *infile = NULL;
VpxVideoWriter *writer = NULL;
vpx_codec_ctx_t codec;
vpx_codec_enc_cfg_t cfg;
vpx_image_t raw;
vpx_codec_err_t res;
vpx_fixed_buf_t stats = {0};
VpxVideoInfo info = {0};
const VpxInterface *encoder = NULL;
int pass;
const int fps = 30; // TODO(dkovalev) add command line argument
const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument
const char *const codec_arg = argv[1];
const char *const width_arg = argv[2];
const char *const height_arg = argv[3];
const char *const infile_arg = argv[4];
const char *const outfile_arg = argv[5];
exec_name = argv[0];
if (argc != 6)
die("Invalid number of arguments.");
encoder = get_vpx_encoder_by_name(codec_arg);
if (!encoder)
die("Unsupported codec.");
info.codec_fourcc = encoder->fourcc;
info.time_base.numerator = 1;
info.time_base.denominator = fps;
info.frame_width = strtol(width_arg, NULL, 0);
info.frame_height = strtol(height_arg, NULL, 0);
if (info.frame_width <= 0 ||
info.frame_height <= 0 ||
(info.frame_width % 2) != 0 ||
(info.frame_height % 2) != 0) {
die("Invalid frame size: %dx%d", info.frame_width, info.frame_height);
}
if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width,
info.frame_height, 1)) {
die("Failed to allocate image", info.frame_width, info.frame_height);
}
writer = vpx_video_writer_open(outfile_arg, kContainerIVF, &info);
if (!writer)
die("Failed to open %s for writing", outfile_arg);
printf("Using %s\n", vpx_codec_iface_name(encoder->interface()));
res = vpx_codec_enc_config_default(encoder->interface(), &cfg, 0);
if (res)
die_codec(&codec, "Failed to get default codec config.");
cfg.g_w = info.frame_width;
cfg.g_h = info.frame_height;
cfg.g_timebase.num = info.time_base.numerator;
cfg.g_timebase.den = info.time_base.denominator;
cfg.rc_target_bitrate = bitrate;
for (pass = 0; pass < 2; ++pass) {
int frame_count = 0;
if (pass == 0) {
cfg.g_pass = VPX_RC_FIRST_PASS;
} else {
cfg.g_pass = VPX_RC_LAST_PASS;
cfg.rc_twopass_stats_in = stats;
}
if (!(infile = fopen(infile_arg, "rb")))
die("Failed to open %s for reading", infile_arg);
if (vpx_codec_enc_init(&codec, encoder->interface(), &cfg, 0))
die_codec(&codec, "Failed to initialize encoder");
while (vpx_img_read(&raw, infile)) {
++frame_count;
if (pass == 0) {
get_frame_stats(&codec, &raw, frame_count, 1, 0, VPX_DL_BEST_QUALITY,
&stats);
} else {
encode_frame(&codec, &raw, frame_count, 1, 0, VPX_DL_BEST_QUALITY,
writer);
}
}
if (pass == 0) {
get_frame_stats(&codec, NULL, frame_count, 1, 0, VPX_DL_BEST_QUALITY,
&stats);
} else {
printf("\n");
}
fclose(infile);
printf("Pass %d complete. Processed %d frames.\n", pass + 1, frame_count);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec.");
}
vpx_img_free(&raw);
free(stats.buf);
vpx_video_writer_close(writer);
return EXIT_SUCCESS;
}
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
Target: 1
Example 2:
Code: static int au1200fb_drv_remove(struct platform_device *dev)
{
struct au1200fb_platdata *pd = platform_get_drvdata(dev);
struct au1200fb_device *fbdev;
struct fb_info *fbi;
int plane;
/* Turn off the panel */
au1200_setpanel(NULL, pd);
for (plane = 0; plane < device_count; ++plane) {
fbi = _au1200fb_infos[plane];
fbdev = fbi->par;
/* Clean up all probe data */
unregister_framebuffer(fbi);
if (fbi->cmap.len != 0)
fb_dealloc_cmap(&fbi->cmap);
kfree(fbi->pseudo_palette);
framebuffer_release(fbi);
_au1200fb_infos[plane] = NULL;
}
free_irq(platform_get_irq(dev, 0), (void *)dev);
return 0;
}
Commit Message: Fix a few incorrectly checked [io_]remap_pfn_range() calls
Nico Golde reports a few straggling uses of [io_]remap_pfn_range() that
really should use the vm_iomap_memory() helper. This trivially converts
two of them to the helper, and comments about why the third one really
needs to continue to use remap_pfn_range(), and adds the missing size
check.
Reported-by: Nico Golde <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected].
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool PermissionsData::ShouldSkipPermissionWarnings(
const std::string& extension_id) {
return extension_id == extension_misc::kProdHangoutsExtensionId;
}
Commit Message: [Extensions] Restrict tabs.captureVisibleTab()
Modify the permissions for tabs.captureVisibleTab(). Instead of just
checking for <all_urls> and assuming its safe, do the following:
- If the page is a "normal" web page (e.g., http/https), allow the
capture if the extension has activeTab granted or <all_urls>.
- If the page is a file page (file:///), allow the capture if the
extension has file access *and* either of the <all_urls> or
activeTab permissions.
- If the page is a chrome:// page, allow the capture only if the
extension has activeTab granted.
Bug: 810220
Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304
Reviewed-on: https://chromium-review.googlesource.com/981195
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548891}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int do_hidp_sock_ioctl(struct socket *sock, unsigned int cmd, void __user *argp)
{
struct hidp_connadd_req ca;
struct hidp_conndel_req cd;
struct hidp_connlist_req cl;
struct hidp_conninfo ci;
struct socket *csock;
struct socket *isock;
int err;
BT_DBG("cmd %x arg %p", cmd, argp);
switch (cmd) {
case HIDPCONNADD:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&ca, argp, sizeof(ca)))
return -EFAULT;
csock = sockfd_lookup(ca.ctrl_sock, &err);
if (!csock)
return err;
isock = sockfd_lookup(ca.intr_sock, &err);
if (!isock) {
sockfd_put(csock);
return err;
}
err = hidp_connection_add(&ca, csock, isock);
if (!err && copy_to_user(argp, &ca, sizeof(ca)))
err = -EFAULT;
sockfd_put(csock);
sockfd_put(isock);
return err;
case HIDPCONNDEL:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&cd, argp, sizeof(cd)))
return -EFAULT;
return hidp_connection_del(&cd);
case HIDPGETCONNLIST:
if (copy_from_user(&cl, argp, sizeof(cl)))
return -EFAULT;
if (cl.cnum <= 0)
return -EINVAL;
err = hidp_get_connlist(&cl);
if (!err && copy_to_user(argp, &cl, sizeof(cl)))
return -EFAULT;
return err;
case HIDPGETCONNINFO:
if (copy_from_user(&ci, argp, sizeof(ci)))
return -EFAULT;
err = hidp_get_conninfo(&ci);
if (!err && copy_to_user(argp, &ci, sizeof(ci)))
return -EFAULT;
return err;
}
return -EINVAL;
}
Commit Message: Bluetooth: hidp: fix buffer overflow
Struct ca is copied from userspace. It is not checked whether the "name"
field is NULL terminated, which allows local users to obtain potentially
sensitive information from kernel stack memory, via a HIDPCONNADD command.
This vulnerability is similar to CVE-2011-1079.
Signed-off-by: Young Xiao <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
Cc: [email protected]
CWE ID: CWE-77
Target: 1
Example 2:
Code: static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
alpha;
size_t
a0,
a1,
bits,
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = ReadBlobLSBLong(image);
a1 = ReadBlobLSBLong(image);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/*
Extract alpha value: multiply 0..15 by 17 to get range 0..255
*/
if (j < 2)
alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf);
else
alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 16);
return MagickTrue;
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: struct sctp_chunk *sctp_assoc_lookup_asconf_ack(
const struct sctp_association *asoc,
__be32 serial)
{
struct sctp_chunk *ack;
/* Walk through the list of cached ASCONF-ACKs and find the
* ack chunk whose serial number matches that of the request.
*/
list_for_each_entry(ack, &asoc->asconf_ack_list, transmitted_list) {
if (ack->subh.addip_hdr->serial == serial) {
sctp_chunk_hold(ack);
return ack;
}
}
return NULL;
}
Commit Message: net: sctp: fix panic on duplicate ASCONF chunks
When receiving a e.g. semi-good formed connection scan in the
form of ...
-------------- INIT[ASCONF; ASCONF_ACK] ------------->
<----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------
-------------------- COOKIE-ECHO -------------------->
<-------------------- COOKIE-ACK ---------------------
---------------- ASCONF_a; ASCONF_b ----------------->
... where ASCONF_a equals ASCONF_b chunk (at least both serials
need to be equal), we panic an SCTP server!
The problem is that good-formed ASCONF chunks that we reply with
ASCONF_ACK chunks are cached per serial. Thus, when we receive a
same ASCONF chunk twice (e.g. through a lost ASCONF_ACK), we do
not need to process them again on the server side (that was the
idea, also proposed in the RFC). Instead, we know it was cached
and we just resend the cached chunk instead. So far, so good.
Where things get nasty is in SCTP's side effect interpreter, that
is, sctp_cmd_interpreter():
While incoming ASCONF_a (chunk = event_arg) is being marked
!end_of_packet and !singleton, and we have an association context,
we do not flush the outqueue the first time after processing the
ASCONF_ACK singleton chunk via SCTP_CMD_REPLY. Instead, we keep it
queued up, although we set local_cork to 1. Commit 2e3216cd54b1
changed the precedence, so that as long as we get bundled, incoming
chunks we try possible bundling on outgoing queue as well. Before
this commit, we would just flush the output queue.
Now, while ASCONF_a's ASCONF_ACK sits in the corked outq, we
continue to process the same ASCONF_b chunk from the packet. As
we have cached the previous ASCONF_ACK, we find it, grab it and
do another SCTP_CMD_REPLY command on it. So, effectively, we rip
the chunk->list pointers and requeue the same ASCONF_ACK chunk
another time. Since we process ASCONF_b, it's correctly marked
with end_of_packet and we enforce an uncork, and thus flush, thus
crashing the kernel.
Fix it by testing if the ASCONF_ACK is currently pending and if
that is the case, do not requeue it. When flushing the output
queue we may relink the chunk for preparing an outgoing packet,
but eventually unlink it when it's copied into the skb right
before transmission.
Joint work with Vlad Yasevich.
Fixes: 2e3216cd54b1 ("sctp: Follow security requirement of responding with 1 packet")
Signed-off-by: Daniel Borkmann <[email protected]>
Signed-off-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CoordinatorImpl::RequestGlobalMemoryDumpForPid(
base::ProcessId pid,
const RequestGlobalMemoryDumpForPidCallback& callback) {
if (pid == base::kNullProcessId) {
callback.Run(false, nullptr);
return;
}
auto adapter = [](const RequestGlobalMemoryDumpForPidCallback& callback,
bool success, uint64_t,
mojom::GlobalMemoryDumpPtr global_memory_dump) {
callback.Run(success, std::move(global_memory_dump));
};
QueuedRequest::Args args(
base::trace_event::MemoryDumpType::SUMMARY_ONLY,
base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND, {},
false /* addToTrace */, pid);
RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback));
}
Commit Message: memory-infra: split up memory-infra coordinator service into two
This allows for heap profiler to use its own service with correct
capabilities and all other instances to use the existing coordinator
service.
Bug: 792028
Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd
Reviewed-on: https://chromium-review.googlesource.com/836896
Commit-Queue: Lalit Maganti <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: oysteine <[email protected]>
Reviewed-by: Albert J. Wong <[email protected]>
Reviewed-by: Hector Dearman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529059}
CWE ID: CWE-269
Target: 1
Example 2:
Code: check_authkey_line(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
char *cp, const char *loc, struct sshauthopt **authoptsp)
{
int want_keytype = sshkey_is_cert(key) ? KEY_UNSPEC : key->type;
struct sshkey *found = NULL;
struct sshauthopt *keyopts = NULL, *certopts = NULL, *finalopts = NULL;
char *key_options = NULL, *fp = NULL;
const char *reason = NULL;
int ret = -1;
if (authoptsp != NULL)
*authoptsp = NULL;
if ((found = sshkey_new(want_keytype)) == NULL) {
debug3("%s: keytype %d failed", __func__, want_keytype);
goto out;
}
/* XXX djm: peek at key type in line and skip if unwanted */
if (sshkey_read(found, &cp) != 0) {
/* no key? check for options */
debug2("%s: check options: '%s'", loc, cp);
key_options = cp;
if (advance_past_options(&cp) != 0) {
reason = "invalid key option string";
goto fail_reason;
}
skip_space(&cp);
if (sshkey_read(found, &cp) != 0) {
/* still no key? advance to next line*/
debug2("%s: advance: '%s'", loc, cp);
goto out;
}
}
/* Parse key options now; we need to know if this is a CA key */
if ((keyopts = sshauthopt_parse(key_options, &reason)) == NULL) {
debug("%s: bad key options: %s", loc, reason);
auth_debug_add("%s: bad key options: %s", loc, reason);
goto out;
}
/* Ignore keys that don't match or incorrectly marked as CAs */
if (sshkey_is_cert(key)) {
/* Certificate; check signature key against CA */
if (!sshkey_equal(found, key->cert->signature_key) ||
!keyopts->cert_authority)
goto out;
} else {
/* Plain key: check it against key found in file */
if (!sshkey_equal(found, key) || keyopts->cert_authority)
goto out;
}
/* We have a candidate key, perform authorisation checks */
if ((fp = sshkey_fingerprint(found,
options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
fatal("%s: fingerprint failed", __func__);
debug("%s: matching %s found: %s %s", loc,
sshkey_is_cert(key) ? "CA" : "key", sshkey_type(found), fp);
if (auth_authorise_keyopts(ssh, pw, keyopts,
sshkey_is_cert(key), loc) != 0) {
reason = "Refused by key options";
goto fail_reason;
}
/* That's all we need for plain keys. */
if (!sshkey_is_cert(key)) {
verbose("Accepted key %s %s found at %s",
sshkey_type(found), fp, loc);
finalopts = keyopts;
keyopts = NULL;
goto success;
}
/*
* Additional authorisation for certificates.
*/
/* Parse and check options present in certificate */
if ((certopts = sshauthopt_from_cert(key)) == NULL) {
reason = "Invalid certificate options";
goto fail_reason;
}
if (auth_authorise_keyopts(ssh, pw, certopts, 0, loc) != 0) {
reason = "Refused by certificate options";
goto fail_reason;
}
if ((finalopts = sshauthopt_merge(keyopts, certopts, &reason)) == NULL)
goto fail_reason;
/*
* If the user has specified a list of principals as
* a key option, then prefer that list to matching
* their username in the certificate principals list.
*/
if (keyopts->cert_principals != NULL &&
!match_principals_option(keyopts->cert_principals, key->cert)) {
reason = "Certificate does not contain an authorized principal";
goto fail_reason;
}
if (sshkey_cert_check_authority(key, 0, 0,
keyopts->cert_principals == NULL ? pw->pw_name : NULL, &reason) != 0)
goto fail_reason;
verbose("Accepted certificate ID \"%s\" (serial %llu) "
"signed by CA %s %s found at %s",
key->cert->key_id,
(unsigned long long)key->cert->serial,
sshkey_type(found), fp, loc);
success:
if (finalopts == NULL)
fatal("%s: internal error: missing options", __func__);
if (authoptsp != NULL) {
*authoptsp = finalopts;
finalopts = NULL;
}
/* success */
ret = 0;
goto out;
fail_reason:
error("%s", reason);
auth_debug_add("%s", reason);
out:
free(fp);
sshauthopt_free(keyopts);
sshauthopt_free(certopts);
sshauthopt_free(finalopts);
sshkey_free(found);
return ret;
}
Commit Message: delay bailout for invalid authenticating user until after the packet
containing the request has been fully parsed. Reported by Dariusz Tytko
and Michał Sajdak; ok deraadt
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void __udf_read_inode(struct inode *inode)
{
struct buffer_head *bh = NULL;
struct fileEntry *fe;
struct extendedFileEntry *efe;
uint16_t ident;
struct udf_inode_info *iinfo = UDF_I(inode);
struct udf_sb_info *sbi = UDF_SB(inode->i_sb);
unsigned int link_count;
/*
* Set defaults, but the inode is still incomplete!
* Note: get_new_inode() sets the following on a new inode:
* i_sb = sb
* i_no = ino
* i_flags = sb->s_flags
* i_state = 0
* clean_inode(): zero fills and sets
* i_count = 1
* i_nlink = 1
* i_op = NULL;
*/
bh = udf_read_ptagged(inode->i_sb, &iinfo->i_location, 0, &ident);
if (!bh) {
udf_err(inode->i_sb, "(ino %ld) failed !bh\n", inode->i_ino);
make_bad_inode(inode);
return;
}
if (ident != TAG_IDENT_FE && ident != TAG_IDENT_EFE &&
ident != TAG_IDENT_USE) {
udf_err(inode->i_sb, "(ino %ld) failed ident=%d\n",
inode->i_ino, ident);
brelse(bh);
make_bad_inode(inode);
return;
}
fe = (struct fileEntry *)bh->b_data;
efe = (struct extendedFileEntry *)bh->b_data;
if (fe->icbTag.strategyType == cpu_to_le16(4096)) {
struct buffer_head *ibh;
ibh = udf_read_ptagged(inode->i_sb, &iinfo->i_location, 1,
&ident);
if (ident == TAG_IDENT_IE && ibh) {
struct buffer_head *nbh = NULL;
struct kernel_lb_addr loc;
struct indirectEntry *ie;
ie = (struct indirectEntry *)ibh->b_data;
loc = lelb_to_cpu(ie->indirectICB.extLocation);
if (ie->indirectICB.extLength &&
(nbh = udf_read_ptagged(inode->i_sb, &loc, 0,
&ident))) {
if (ident == TAG_IDENT_FE ||
ident == TAG_IDENT_EFE) {
memcpy(&iinfo->i_location,
&loc,
sizeof(struct kernel_lb_addr));
brelse(bh);
brelse(ibh);
brelse(nbh);
__udf_read_inode(inode);
return;
}
brelse(nbh);
}
}
brelse(ibh);
} else if (fe->icbTag.strategyType != cpu_to_le16(4)) {
udf_err(inode->i_sb, "unsupported strategy type: %d\n",
le16_to_cpu(fe->icbTag.strategyType));
brelse(bh);
make_bad_inode(inode);
return;
}
if (fe->icbTag.strategyType == cpu_to_le16(4))
iinfo->i_strat4096 = 0;
else /* if (fe->icbTag.strategyType == cpu_to_le16(4096)) */
iinfo->i_strat4096 = 1;
iinfo->i_alloc_type = le16_to_cpu(fe->icbTag.flags) &
ICBTAG_FLAG_AD_MASK;
iinfo->i_unique = 0;
iinfo->i_lenEAttr = 0;
iinfo->i_lenExtents = 0;
iinfo->i_lenAlloc = 0;
iinfo->i_next_alloc_block = 0;
iinfo->i_next_alloc_goal = 0;
if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_EFE)) {
iinfo->i_efe = 1;
iinfo->i_use = 0;
if (udf_alloc_i_data(inode, inode->i_sb->s_blocksize -
sizeof(struct extendedFileEntry))) {
make_bad_inode(inode);
return;
}
memcpy(iinfo->i_ext.i_data,
bh->b_data + sizeof(struct extendedFileEntry),
inode->i_sb->s_blocksize -
sizeof(struct extendedFileEntry));
} else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_FE)) {
iinfo->i_efe = 0;
iinfo->i_use = 0;
if (udf_alloc_i_data(inode, inode->i_sb->s_blocksize -
sizeof(struct fileEntry))) {
make_bad_inode(inode);
return;
}
memcpy(iinfo->i_ext.i_data,
bh->b_data + sizeof(struct fileEntry),
inode->i_sb->s_blocksize - sizeof(struct fileEntry));
} else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_USE)) {
iinfo->i_efe = 0;
iinfo->i_use = 1;
iinfo->i_lenAlloc = le32_to_cpu(
((struct unallocSpaceEntry *)bh->b_data)->
lengthAllocDescs);
if (udf_alloc_i_data(inode, inode->i_sb->s_blocksize -
sizeof(struct unallocSpaceEntry))) {
make_bad_inode(inode);
return;
}
memcpy(iinfo->i_ext.i_data,
bh->b_data + sizeof(struct unallocSpaceEntry),
inode->i_sb->s_blocksize -
sizeof(struct unallocSpaceEntry));
return;
}
read_lock(&sbi->s_cred_lock);
i_uid_write(inode, le32_to_cpu(fe->uid));
if (!uid_valid(inode->i_uid) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_IGNORE) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_SET))
inode->i_uid = UDF_SB(inode->i_sb)->s_uid;
i_gid_write(inode, le32_to_cpu(fe->gid));
if (!gid_valid(inode->i_gid) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_IGNORE) ||
UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_SET))
inode->i_gid = UDF_SB(inode->i_sb)->s_gid;
if (fe->icbTag.fileType != ICBTAG_FILE_TYPE_DIRECTORY &&
sbi->s_fmode != UDF_INVALID_MODE)
inode->i_mode = sbi->s_fmode;
else if (fe->icbTag.fileType == ICBTAG_FILE_TYPE_DIRECTORY &&
sbi->s_dmode != UDF_INVALID_MODE)
inode->i_mode = sbi->s_dmode;
else
inode->i_mode = udf_convert_permissions(fe);
inode->i_mode &= ~sbi->s_umask;
read_unlock(&sbi->s_cred_lock);
link_count = le16_to_cpu(fe->fileLinkCount);
if (!link_count)
link_count = 1;
set_nlink(inode, link_count);
inode->i_size = le64_to_cpu(fe->informationLength);
iinfo->i_lenExtents = inode->i_size;
if (iinfo->i_efe == 0) {
inode->i_blocks = le64_to_cpu(fe->logicalBlocksRecorded) <<
(inode->i_sb->s_blocksize_bits - 9);
if (!udf_disk_stamp_to_time(&inode->i_atime, fe->accessTime))
inode->i_atime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_mtime,
fe->modificationTime))
inode->i_mtime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_ctime, fe->attrTime))
inode->i_ctime = sbi->s_record_time;
iinfo->i_unique = le64_to_cpu(fe->uniqueID);
iinfo->i_lenEAttr = le32_to_cpu(fe->lengthExtendedAttr);
iinfo->i_lenAlloc = le32_to_cpu(fe->lengthAllocDescs);
iinfo->i_checkpoint = le32_to_cpu(fe->checkpoint);
} else {
inode->i_blocks = le64_to_cpu(efe->logicalBlocksRecorded) <<
(inode->i_sb->s_blocksize_bits - 9);
if (!udf_disk_stamp_to_time(&inode->i_atime, efe->accessTime))
inode->i_atime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_mtime,
efe->modificationTime))
inode->i_mtime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&iinfo->i_crtime, efe->createTime))
iinfo->i_crtime = sbi->s_record_time;
if (!udf_disk_stamp_to_time(&inode->i_ctime, efe->attrTime))
inode->i_ctime = sbi->s_record_time;
iinfo->i_unique = le64_to_cpu(efe->uniqueID);
iinfo->i_lenEAttr = le32_to_cpu(efe->lengthExtendedAttr);
iinfo->i_lenAlloc = le32_to_cpu(efe->lengthAllocDescs);
iinfo->i_checkpoint = le32_to_cpu(efe->checkpoint);
}
switch (fe->icbTag.fileType) {
case ICBTAG_FILE_TYPE_DIRECTORY:
inode->i_op = &udf_dir_inode_operations;
inode->i_fop = &udf_dir_operations;
inode->i_mode |= S_IFDIR;
inc_nlink(inode);
break;
case ICBTAG_FILE_TYPE_REALTIME:
case ICBTAG_FILE_TYPE_REGULAR:
case ICBTAG_FILE_TYPE_UNDEF:
case ICBTAG_FILE_TYPE_VAT20:
if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB)
inode->i_data.a_ops = &udf_adinicb_aops;
else
inode->i_data.a_ops = &udf_aops;
inode->i_op = &udf_file_inode_operations;
inode->i_fop = &udf_file_operations;
inode->i_mode |= S_IFREG;
break;
case ICBTAG_FILE_TYPE_BLOCK:
inode->i_mode |= S_IFBLK;
break;
case ICBTAG_FILE_TYPE_CHAR:
inode->i_mode |= S_IFCHR;
break;
case ICBTAG_FILE_TYPE_FIFO:
init_special_inode(inode, inode->i_mode | S_IFIFO, 0);
break;
case ICBTAG_FILE_TYPE_SOCKET:
init_special_inode(inode, inode->i_mode | S_IFSOCK, 0);
break;
case ICBTAG_FILE_TYPE_SYMLINK:
inode->i_data.a_ops = &udf_symlink_aops;
inode->i_op = &udf_symlink_inode_operations;
inode->i_mode = S_IFLNK | S_IRWXUGO;
break;
case ICBTAG_FILE_TYPE_MAIN:
udf_debug("METADATA FILE-----\n");
break;
case ICBTAG_FILE_TYPE_MIRROR:
udf_debug("METADATA MIRROR FILE-----\n");
break;
case ICBTAG_FILE_TYPE_BITMAP:
udf_debug("METADATA BITMAP FILE-----\n");
break;
default:
udf_err(inode->i_sb, "(ino %ld) failed unknown file type=%d\n",
inode->i_ino, fe->icbTag.fileType);
make_bad_inode(inode);
return;
}
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
struct deviceSpec *dsea =
(struct deviceSpec *)udf_get_extendedattr(inode, 12, 1);
if (dsea) {
init_special_inode(inode, inode->i_mode,
MKDEV(le32_to_cpu(dsea->majorDeviceIdent),
le32_to_cpu(dsea->minorDeviceIdent)));
/* Developer ID ??? */
} else
make_bad_inode(inode);
}
brelse(bh);
}
Commit Message: udf: Avoid infinite loop when processing indirect ICBs
We did not implement any bound on number of indirect ICBs we follow when
loading inode. Thus corrupted medium could cause kernel to go into an
infinite loop, possibly causing a stack overflow.
Fix the possible stack overflow by removing recursion from
__udf_read_inode() and limit number of indirect ICBs we follow to avoid
infinite loops.
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int toggle_utf8(const char *name, int fd, bool utf8) {
int r;
struct termios tc = {};
assert(name);
r = ioctl(fd, KDSKBMODE, utf8 ? K_UNICODE : K_XLATE);
if (r < 0)
return log_warning_errno(errno, "Failed to %s UTF-8 kbdmode on %s: %m", enable_disable(utf8), name);
r = loop_write(fd, utf8 ? "\033%G" : "\033%@", 3, false);
if (r < 0)
return log_warning_errno(r, "Failed to %s UTF-8 term processing on %s: %m", enable_disable(utf8), name);
r = tcgetattr(fd, &tc);
if (r >= 0) {
SET_FLAG(tc.c_iflag, IUTF8, utf8);
r = tcsetattr(fd, TCSANOW, &tc);
}
if (r < 0)
return log_warning_errno(errno, "Failed to %s iutf8 flag on %s: %m", enable_disable(utf8), name);
log_debug("UTF-8 kbdmode %sd on %s", enable_disable(utf8), name);
return 0;
}
Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check
VT kbd reset check
CWE ID: CWE-255
Target: 1
Example 2:
Code: bool NavigationControllerImpl::CanGoToOffset(int offset) const {
int index = GetIndexForOffset(offset);
return index >= 0 && index < GetEntryCount();
}
Commit Message: Delete unneeded pending entries in DidFailProvisionalLoad to prevent a spoof.
BUG=280512
BUG=278899
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/23978003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@222146 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: HostCache::Entry::~Entry() {}
Commit Message: Add PersistenceDelegate to HostCache
PersistenceDelegate is a new interface for persisting the contents of
the HostCache. This commit includes the interface itself, the logic in
HostCache for interacting with it, and a mock implementation of the
interface for testing. It does not include support for immediate data
removal since that won't be needed for the currently planned use case.
BUG=605149
Review-Url: https://codereview.chromium.org/2943143002
Cr-Commit-Position: refs/heads/master@{#481015}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
guint pkt_len;
int pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9u", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
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("toshiba: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
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: 12394
Change-Id: I4b19b95f2e1ffc96dac5c91bff6698c246f52007
Reviewed-on: https://code.wireshark.org/review/15230
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static bool cmd_r2cmd(RCore *core, const char *_input) {
char *input = r_str_newf ("r%s", _input);
int rc = 0;
if (r_str_startswith (input, "rax2")) {
rc = __runMain (core->r_main_rax2, input);
} else if (r_str_startswith (input, "radare2")) {
r_sys_cmdf ("%s", input);
} else if (r_str_startswith (input, "rasm2")) {
r_sys_cmdf ("%s", input);
} else if (r_str_startswith (input, "rabin2")) {
r_sys_cmdf ("%s", input);
} else if (r_str_startswith (input, "ragg2")) {
r_sys_cmdf ("%s", input);
} else if (r_str_startswith (input, "r2pm")) {
r_sys_cmdf ("%s", input);
} else if (r_str_startswith (input, "radiff2")) {
rc = __runMain (core->r_main_radiff2, input);
} else {
const char *r2cmds[] = {
"rax2", "r2pm", "rasm2", "rabin2", "rahash2", "rafind2", "rarun2", "ragg2", "radare2", "r2", NULL
};
int i;
for (i = 0; r2cmds[i]; i++) {
if (r_str_startswith (input, r2cmds[i])) {
free (input);
return true;
}
}
return false;
}
free (input);
core->num->value = rc;
return true;
}
Commit Message: Fix #14990 - multiple quoted command parsing issue ##core
> "?e hello""?e world"
hello
world"
> "?e hello";"?e world"
hello
world
CWE ID: CWE-78
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void VRDisplay::OnFocus() {
display_blurred_ = false;
ConnectVSyncProvider();
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
EventTypeNames::vrdisplayfocus, true, false, this, ""));
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst)
{
void (*cb) (const SSL *ssl, int type, int val) = NULL;
#ifndef OPENSSL_NO_SCTP
if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) {
WORK_STATE ret;
ret = dtls_wait_for_dry(s);
if (ret != WORK_FINISHED_CONTINUE)
return ret;
}
#endif
/* clean a few things up */
ssl3_cleanup_key_block(s);
if (!SSL_IS_DTLS(s)) {
/*
* We don't do this in DTLS because we may still need the init_buf
* in case there are any unexpected retransmits
*/
BUF_MEM_free(s->init_buf);
s->init_buf = NULL;
}
ssl_free_wbio_buffer(s);
s->init_num = 0;
if (!s->server || s->renegotiate == 2) {
/* skipped if we just sent a HelloRequest */
s->renegotiate = 0;
s->new_session = 0;
if (s->server) {
ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
s->ctx->stats.sess_accept_good++;
s->handshake_func = ossl_statem_accept;
} else {
ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
if (s->hit)
s->ctx->stats.sess_hit++;
s->handshake_func = ossl_statem_connect;
s->ctx->stats.sess_connect_good++;
}
if (s->info_callback != NULL)
cb = s->info_callback;
else if (s->ctx->info_callback != NULL)
cb = s->ctx->info_callback;
if (cb != NULL)
cb(s, SSL_CB_HANDSHAKE_DONE, 1);
if (SSL_IS_DTLS(s)) {
/* done with handshaking */
s->d1->handshake_read_seq = 0;
s->d1->handshake_write_seq = 0;
s->d1->next_handshake_write_seq = 0;
}
}
}
Commit Message:
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void hiddev_send_event(struct hid_device *hid,
struct hiddev_usage_ref *uref)
{
struct hiddev *hiddev = hid->hiddev;
struct hiddev_list *list;
unsigned long flags;
spin_lock_irqsave(&hiddev->list_lock, flags);
list_for_each_entry(list, &hiddev->list, node) {
if (uref->field_index != HID_FIELD_INDEX_NONE ||
(list->flags & HIDDEV_FLAG_REPORT) != 0) {
list->buffer[list->head] = *uref;
list->head = (list->head + 1) &
(HIDDEV_BUFFER_SIZE - 1);
kill_fasync(&list->fasync, SIGIO, POLL_IN);
}
}
spin_unlock_irqrestore(&hiddev->list_lock, flags);
wake_up_interruptible(&hiddev->wait);
}
Commit Message: HID: hiddev: validate num_values for HIDIOCGUSAGES, HIDIOCSUSAGES commands
This patch validates the num_values parameter from userland during the
HIDIOCGUSAGES and HIDIOCSUSAGES commands. Previously, if the report id was set
to HID_REPORT_ID_UNKNOWN, we would fail to validate the num_values parameter
leading to a heap overflow.
Cc: [email protected]
Signed-off-by: Scott Bauer <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int nfs4_do_close(struct path *path, struct nfs4_state *state, int wait)
{
struct nfs_server *server = NFS_SERVER(state->inode);
struct nfs4_closedata *calldata;
struct nfs4_state_owner *sp = state->owner;
struct rpc_task *task;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CLOSE],
.rpc_cred = state->owner->so_cred,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = server->client,
.rpc_message = &msg,
.callback_ops = &nfs4_close_ops,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC,
};
int status = -ENOMEM;
calldata = kmalloc(sizeof(*calldata), GFP_KERNEL);
if (calldata == NULL)
goto out;
calldata->inode = state->inode;
calldata->state = state;
calldata->arg.fh = NFS_FH(state->inode);
calldata->arg.stateid = &state->open_stateid;
/* Serialization for the sequence id */
calldata->arg.seqid = nfs_alloc_seqid(&state->owner->so_seqid);
if (calldata->arg.seqid == NULL)
goto out_free_calldata;
calldata->arg.open_flags = 0;
calldata->arg.bitmask = server->attr_bitmask;
calldata->res.fattr = &calldata->fattr;
calldata->res.seqid = calldata->arg.seqid;
calldata->res.server = server;
calldata->path.mnt = mntget(path->mnt);
calldata->path.dentry = dget(path->dentry);
msg.rpc_argp = &calldata->arg,
msg.rpc_resp = &calldata->res,
task_setup_data.callback_data = calldata;
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
status = 0;
if (wait)
status = rpc_wait_for_completion_task(task);
rpc_put_task(task);
return status;
out_free_calldata:
kfree(calldata);
out:
nfs4_put_open_state(state);
nfs4_put_state_owner(sp);
return status;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: handle_mlppp(netdissect_options *ndo,
const u_char *p, int length)
{
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "MLPPP, "));
ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length));
}
Commit Message: CVE-2017-13038/PPP: Do bounds checking.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add a test using the capture file supplied by Katie Holly.
CWE ID: CWE-125
Target: 1
Example 2:
Code: status_t OMXCodec::setupErrorCorrectionParameters() {
OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE errorCorrectionType;
InitOMXParams(&errorCorrectionType);
errorCorrectionType.nPortIndex = kPortIndexOutput;
status_t err = mOMX->getParameter(
mNode, OMX_IndexParamVideoErrorCorrection,
&errorCorrectionType, sizeof(errorCorrectionType));
if (err != OK) {
ALOGW("Error correction param query is not supported");
return OK; // Optional feature. Ignore this failure
}
errorCorrectionType.bEnableHEC = OMX_FALSE;
errorCorrectionType.bEnableResync = OMX_TRUE;
errorCorrectionType.nResynchMarkerSpacing = 256;
errorCorrectionType.bEnableDataPartitioning = OMX_FALSE;
errorCorrectionType.bEnableRVLC = OMX_FALSE;
err = mOMX->setParameter(
mNode, OMX_IndexParamVideoErrorCorrection,
&errorCorrectionType, sizeof(errorCorrectionType));
if (err != OK) {
ALOGW("Error correction param configuration is not supported");
}
return OK;
}
Commit Message: OMXCodec: check IMemory::pointer() before using allocation
Bug: 29421811
Change-Id: I0a73ba12bae4122f1d89fc92e5ea4f6a96cd1ed1
CWE ID: CWE-284
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void set_navigation()
{
GF_Err e;
char nav;
u32 type = gf_term_get_option(term, GF_OPT_NAVIGATION_TYPE);
e = GF_OK;
fflush(stdin);
if (!type) {
fprintf(stderr, "Content/compositor doesn't allow user-selectable navigation\n");
} else if (type==1) {
fprintf(stderr, "Select Navigation (\'N\'one, \'E\'xamine, \'S\'lide): ");
nav = getch();
if (nav=='N') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_NONE);
else if (nav=='E') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_EXAMINE);
else if (nav=='S') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_SLIDE);
else fprintf(stderr, "Unknown selector \'%c\' - only \'N\',\'E\',\'S\' allowed\n", nav);
} else if (type==2) {
fprintf(stderr, "Select Navigation (\'N\'one, \'W\'alk, \'F\'ly, \'E\'xamine, \'P\'an, \'S\'lide, \'G\'ame, \'V\'R, \'O\'rbit): ");
nav = getch();
if (nav=='N') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_NONE);
else if (nav=='W') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_WALK);
else if (nav=='F') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_FLY);
else if (nav=='E') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_EXAMINE);
else if (nav=='P') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_PAN);
else if (nav=='S') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_SLIDE);
else if (nav=='G') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_GAME);
else if (nav=='O') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_ORBIT);
else if (nav=='V') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_VR);
else fprintf(stderr, "Unknown selector %c - only \'N\',\'W\',\'F\',\'E\',\'P\',\'S\',\'G\', \'V\', \'O\' allowed\n", nav);
}
if (e) fprintf(stderr, "Error setting mode: %s\n", gf_error_to_string(e));
}
Commit Message: add some boundary checks on gf_text_get_utf8_line (#1188)
CWE ID: CWE-787
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct vmw_private *dev_priv = vmw_priv(dev);
struct vmw_user_surface *user_srf;
struct vmw_surface *srf;
struct vmw_resource *res;
struct vmw_resource *tmp;
union drm_vmw_gb_surface_create_arg *arg =
(union drm_vmw_gb_surface_create_arg *)data;
struct drm_vmw_gb_surface_create_req *req = &arg->req;
struct drm_vmw_gb_surface_create_rep *rep = &arg->rep;
struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
int ret;
uint32_t size;
uint32_t backup_handle;
if (req->multisample_count != 0)
return -EINVAL;
if (req->mip_levels > DRM_VMW_MAX_MIP_LEVELS)
return -EINVAL;
if (unlikely(vmw_user_surface_size == 0))
vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) +
128;
size = vmw_user_surface_size + 128;
/* Define a surface based on the parameters. */
ret = vmw_surface_gb_priv_define(dev,
size,
req->svga3d_flags,
req->format,
req->drm_surface_flags & drm_vmw_surface_flag_scanout,
req->mip_levels,
req->multisample_count,
req->array_size,
req->base_size,
&srf);
if (unlikely(ret != 0))
return ret;
user_srf = container_of(srf, struct vmw_user_surface, srf);
if (drm_is_primary_client(file_priv))
user_srf->master = drm_master_get(file_priv->master);
ret = ttm_read_lock(&dev_priv->reservation_sem, true);
if (unlikely(ret != 0))
return ret;
res = &user_srf->srf.res;
if (req->buffer_handle != SVGA3D_INVALID_ID) {
ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle,
&res->backup,
&user_srf->backup_base);
if (ret == 0 && res->backup->base.num_pages * PAGE_SIZE <
res->backup_size) {
DRM_ERROR("Surface backup buffer is too small.\n");
vmw_dmabuf_unreference(&res->backup);
ret = -EINVAL;
goto out_unlock;
}
} else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer)
ret = vmw_user_dmabuf_alloc(dev_priv, tfile,
res->backup_size,
req->drm_surface_flags &
drm_vmw_surface_flag_shareable,
&backup_handle,
&res->backup,
&user_srf->backup_base);
if (unlikely(ret != 0)) {
vmw_resource_unreference(&res);
goto out_unlock;
}
tmp = vmw_resource_reference(res);
ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime,
req->drm_surface_flags &
drm_vmw_surface_flag_shareable,
VMW_RES_SURFACE,
&vmw_user_surface_base_release, NULL);
if (unlikely(ret != 0)) {
vmw_resource_unreference(&tmp);
vmw_resource_unreference(&res);
goto out_unlock;
}
rep->handle = user_srf->prime.base.hash.key;
rep->backup_size = res->backup_size;
if (res->backup) {
rep->buffer_map_handle =
drm_vma_node_offset_addr(&res->backup->base.vma_node);
rep->buffer_size = res->backup->base.num_pages * PAGE_SIZE;
rep->buffer_handle = backup_handle;
} else {
rep->buffer_map_handle = 0;
rep->buffer_size = 0;
rep->buffer_handle = SVGA3D_INVALID_ID;
}
vmw_resource_unreference(&res);
out_unlock:
ttm_read_unlock(&dev_priv->reservation_sem);
return ret;
}
Commit Message: drm/vmwgfx: Make sure backup_handle is always valid
When vmw_gb_surface_define_ioctl() is called with an existing buffer,
we end up returning an uninitialized variable in the backup_handle.
The fix is to first initialize backup_handle to 0 just to be sure, and
second, when a user-provided buffer is found, we will use the
req->buffer_handle as the backup_handle.
Cc: <[email protected]>
Reported-by: Murray McAllister <[email protected]>
Signed-off-by: Sinclair Yeh <[email protected]>
Reviewed-by: Deepak Rawat <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void addrconf_addr_gen(struct inet6_dev *idev, bool prefix_route)
{
if (idev->addr_gen_mode == IN6_ADDR_GEN_MODE_EUI64) {
struct in6_addr addr;
ipv6_addr_set(&addr, htonl(0xFE800000), 0, 0, 0);
/* addrconf_add_linklocal also adds a prefix_route and we
* only need to care about prefix routes if ipv6_generate_eui64
* couldn't generate one.
*/
if (ipv6_generate_eui64(addr.s6_addr + 8, idev->dev) == 0)
addrconf_add_linklocal(idev, &addr);
else if (prefix_route)
addrconf_prefix_route(&addr, 64, idev->dev, 0, 0);
}
}
Commit Message: ipv6: addrconf: validate new MTU before applying it
Currently we don't check if the new MTU is valid or not and this allows
one to configure a smaller than minimum allowed by RFCs or even bigger
than interface own MTU, which is a problem as it may lead to packet
drops.
If you have a daemon like NetworkManager running, this may be exploited
by remote attackers by forging RA packets with an invalid MTU, possibly
leading to a DoS. (NetworkManager currently only validates for values
too small, but not for too big ones.)
The fix is just to make sure the new value is valid. That is, between
IPV6_MIN_MTU and interface's MTU.
Note that similar check is already performed at
ndisc_router_discovery(), for when kernel itself parses the RA.
Signed-off-by: Marcelo Ricardo Leitner <[email protected]>
Signed-off-by: Sabrina Dubroca <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool AXNodeObject::canHaveChildren() const {
if (!getNode() && !isAXLayoutObject())
return false;
if (getNode() && isHTMLMapElement(getNode()))
return false;
AccessibilityRole role = roleValue();
if (isPresentational())
role = nativeAccessibilityRoleIgnoringAria();
switch (role) {
case ImageRole:
case ButtonRole:
case PopUpButtonRole:
case CheckBoxRole:
case RadioButtonRole:
case SwitchRole:
case TabRole:
case ToggleButtonRole:
case ListBoxOptionRole:
case ScrollBarRole:
return false;
case StaticTextRole:
if (!axObjectCache().inlineTextBoxAccessibilityEnabled())
return false;
default:
return true;
}
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: image_transform_png_set_strip_16_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
if (that->bit_depth == 16)
{
that->sample_depth = that->bit_depth = 8;
if (that->red_sBIT > 8) that->red_sBIT = 8;
if (that->green_sBIT > 8) that->green_sBIT = 8;
if (that->blue_sBIT > 8) that->blue_sBIT = 8;
if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
/* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
* configuration option is set. From 1.5.4 the flag is never set and the
* 'scale' API (above) must be used.
*/
# ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
# if PNG_LIBPNG_VER >= 10504
# error PNG_READ_ACCURATE_SCALE should not be set
# endif
/* The strip 16 algorithm drops the low 8 bits rather than calculating
* 1/257, so we need to adjust the permitted errors appropriately:
* Notice that this is only relevant prior to the addition of the
* png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
*/
{
PNG_CONST double d = (255-128.5)/65535;
that->rede += d;
that->greene += d;
that->bluee += d;
that->alphae += d;
}
# endif
}
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: static bool ipv4_datagram_support_cmsg(const struct sock *sk,
struct sk_buff *skb,
int ee_origin)
{
struct in_pktinfo *info;
if (ee_origin == SO_EE_ORIGIN_ICMP)
return true;
if (ee_origin == SO_EE_ORIGIN_LOCAL)
return false;
/* Support IP_PKTINFO on tstamp packets if requested, to correlate
* timestamp with egress dev. Not possible for packets without dev
* or without payload (SOF_TIMESTAMPING_OPT_TSONLY).
*/
if ((!(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_CMSG)) ||
(!skb->dev))
return false;
info = PKTINFO_SKB_CB(skb);
info->ipi_spec_dst.s_addr = ip_hdr(skb)->saddr;
info->ipi_ifindex = skb->dev->ifindex;
return true;
}
Commit Message: ip: fix IP_CHECKSUM handling
The skbs processed by ip_cmsg_recv() are not guaranteed to
be linear e.g. when sending UDP packets over loopback with
MSGMORE.
Using csum_partial() on [potentially] the whole skb len
is dangerous; instead be on the safe side and use skb_checksum().
Thanks to syzkaller team to detect the issue and provide the
reproducer.
v1 -> v2:
- move the variable declaration in a tighter scope
Fixes: ad6f939ab193 ("ip: Add offset parameter to ip_cmsg_recv")
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: Paolo Abeni <[email protected]>
Acked-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RunTestsInFile(std::string filename, std::string pdf_filename) {
extensions::ResultCatcher catcher;
GURL url(embedded_test_server()->GetURL("/pdf/" + pdf_filename));
ASSERT_TRUE(LoadPdf(url));
content::WebContents* contents =
browser()->tab_strip_model()->GetActiveWebContents();
content::BrowserPluginGuestManager* guest_manager =
contents->GetBrowserContext()->GetGuestManager();
content::WebContents* guest_contents =
guest_manager->GetFullPageGuest(contents);
ASSERT_TRUE(guest_contents);
base::FilePath test_data_dir;
PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir);
test_data_dir = test_data_dir.Append(FILE_PATH_LITERAL("pdf"));
base::FilePath test_util_path = test_data_dir.AppendASCII("test_util.js");
std::string test_util_js;
ASSERT_TRUE(base::ReadFileToString(test_util_path, &test_util_js));
base::FilePath test_file_path = test_data_dir.AppendASCII(filename);
std::string test_js;
ASSERT_TRUE(base::ReadFileToString(test_file_path, &test_js));
test_util_js.append(test_js);
ASSERT_TRUE(content::ExecuteScript(guest_contents, test_util_js));
if (!catcher.GetNextResult())
FAIL() << catcher.message();
}
Commit Message: Prevent leaking PDF data cross-origin
BUG=520422
Review URL: https://codereview.chromium.org/1311973002
Cr-Commit-Position: refs/heads/master@{#345267}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: RenderFrameHostManager::GetSiteInstanceForNavigationRequest(
const NavigationRequest& request) {
SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance();
bool no_renderer_swap_allowed = false;
bool was_server_redirect = request.navigation_handle() &&
request.navigation_handle()->WasServerRedirect();
if (frame_tree_node_->IsMainFrame()) {
bool can_renderer_initiate_transfer =
(request.state() == NavigationRequest::FAILED &&
SiteIsolationPolicy::IsErrorPageIsolationEnabled(
true /* in_main_frame */)) ||
(render_frame_host_->IsRenderFrameLive() &&
IsURLHandledByNetworkStack(request.common_params().url) &&
IsRendererTransferNeededForNavigation(render_frame_host_.get(),
request.common_params().url));
no_renderer_swap_allowed |=
request.from_begin_navigation() && !can_renderer_initiate_transfer;
} else {
no_renderer_swap_allowed |= !CanSubframeSwapProcess(
request.common_params().url, request.source_site_instance(),
request.dest_site_instance(), was_server_redirect);
}
if (no_renderer_swap_allowed)
return scoped_refptr<SiteInstance>(current_site_instance);
SiteInstance* candidate_site_instance =
speculative_render_frame_host_
? speculative_render_frame_host_->GetSiteInstance()
: nullptr;
scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation(
request.common_params().url, request.source_site_instance(),
request.dest_site_instance(), candidate_site_instance,
request.common_params().transition,
request.state() == NavigationRequest::FAILED,
request.restore_type() != RestoreType::NONE, request.is_view_source(),
was_server_redirect);
return dest_site_instance;
}
Commit Message: Use unique processes for data URLs on restore.
Data URLs are usually put into the process that created them, but this
info is not tracked after a tab restore. Ensure that they do not end up
in the parent frame's process (or each other's process), in case they
are malicious.
BUG=863069
Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b
Reviewed-on: https://chromium-review.googlesource.com/1150767
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Commit-Queue: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#581023}
CWE ID: CWE-285
Target: 1
Example 2:
Code: snmp_socket_handler(vector_t *strvec)
{
if (vector_size(strvec) > 2) {
report_config_error(CONFIG_GENERAL_ERROR, "Too many parameters specified for snmp_socket - ignoring");
return;
}
if (vector_size(strvec) < 2) {
report_config_error(CONFIG_GENERAL_ERROR, "SNMP error : snmp socket name missing");
return;
}
if (strlen(strvec_slot(strvec,1)) > PATH_MAX - 1) {
report_config_error(CONFIG_GENERAL_ERROR, "SNMP error : snmp socket name too long - ignored");
return;
}
if (global_data->snmp_socket) {
report_config_error(CONFIG_GENERAL_ERROR, "SNMP socket already set to %s - ignoring", global_data->snmp_socket);
return;
}
global_data->snmp_socket = MALLOC(strlen(strvec_slot(strvec, 1) + 1));
strcpy(global_data->snmp_socket, strvec_slot(strvec,1));
}
Commit Message: Add command line and configuration option to set umask
Issue #1048 identified that files created by keepalived are created
with mode 0666. This commit changes the default to 0644, and also
allows the umask to be specified in the configuration or as a command
line option.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void PermissionsBubbleDialogDelegateView::OnWidgetDestroying(
views::Widget* widget) {
views::BubbleDialogDelegateView::OnWidgetDestroying(widget);
if (owner_) {
owner_->Closing();
owner_ = nullptr;
}
}
Commit Message: Elide the permission bubble title from the head of the string.
Long URLs can be used to spoof other origins in the permission bubble
title. This CL customises the title to be elided from the head, which
ensures that the maximal amount of the URL host is displayed in the case
where the URL is too long and causes the string to overflow.
Implementing the ellision means that the title cannot be multiline
(where elision is not well supported). Note that in English, the
window title is a string "$ORIGIN wants to", so the non-origin
component will not be elided. In other languages, the non-origin
component may appear fully or partly before the origin (e.g. in
Filipino, "Gusto ng $ORIGIN na"), so it may be elided there if the
URL is sufficiently long. This is not optimal, but the URLs that are
sufficiently long to trigger the elision are probably malicious, and
displaying the most relevant component of the URL is most important
for security purposes.
BUG=774438
Change-Id: I75c2364b10bf69bf337c7f4970481bf1809f6aae
Reviewed-on: https://chromium-review.googlesource.com/768312
Reviewed-by: Ben Wells <[email protected]>
Reviewed-by: Lucas Garron <[email protected]>
Reviewed-by: Matt Giuca <[email protected]>
Commit-Queue: Dominick Ng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#516921}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: gfx::Size ShellWindowFrameView::GetMinimumSize() {
gfx::Size min_size = frame_->client_view()->GetMinimumSize();
gfx::Rect client_bounds = GetBoundsForClientView();
min_size.Enlarge(0, client_bounds.y());
int closeButtonOffsetX =
(kCaptionHeight - close_button_->height()) / 2;
int header_width = close_button_->width() + closeButtonOffsetX * 2;
if (header_width > min_size.width())
min_size.set_width(header_width);
return min_size;
}
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79
Target: 1
Example 2:
Code: GDataDirectory* GDataWapiFeedProcessor::FindDirectoryForNewEntry(
GDataEntry* new_entry,
const FileResourceIdMap& file_map,
GDataDirectoryService* orphaned_dir_service) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
GDataDirectory* dir = NULL;
const std::string& parent_id = new_entry->parent_resource_id();
if (parent_id.empty()) {
dir = directory_service_->root();
DVLOG(1) << "Root parent for " << new_entry->base_name();
} else {
GDataEntry* entry = directory_service_->GetEntryByResourceId(parent_id);
dir = entry ? entry->AsGDataDirectory() : NULL;
if (!dir) {
FileResourceIdMap::const_iterator find_iter =
file_map.find(parent_id);
dir = (find_iter != file_map.end() &&
find_iter->second) ?
find_iter->second->AsGDataDirectory() : NULL;
if (dir) {
DVLOG(1) << "Found parent for " << new_entry->base_name()
<< " in file_map " << parent_id;
} else {
DVLOG(1) << "Adding orphan " << new_entry->GetFilePath().value();
dir = orphaned_dir_service->root();
}
}
}
return dir;
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: scoped_refptr<PermissionSet> UnpackPermissionSet(
const Permissions& permissions, std::string* error) {
APIPermissionSet apis;
std::vector<std::string>* permissions_list = permissions.permissions.get();
if (permissions_list) {
PermissionsInfo* info = PermissionsInfo::GetInstance();
for (std::vector<std::string>::iterator it = permissions_list->begin();
it != permissions_list->end(); ++it) {
if (it->find(kDelimiter) != std::string::npos) {
size_t delimiter = it->find(kDelimiter);
std::string permission_name = it->substr(0, delimiter);
std::string permission_arg = it->substr(delimiter + 1);
scoped_ptr<base::Value> permission_json(
base::JSONReader::Read(permission_arg));
if (!permission_json.get()) {
*error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it);
return NULL;
}
APIPermission* permission = NULL;
const APIPermissionInfo* bluetooth_device_permission_info =
info->GetByID(APIPermission::kBluetoothDevice);
const APIPermissionInfo* usb_device_permission_info =
info->GetByID(APIPermission::kUsbDevice);
if (permission_name == bluetooth_device_permission_info->name()) {
permission = new BluetoothDevicePermission(
bluetooth_device_permission_info);
} else if (permission_name == usb_device_permission_info->name()) {
permission = new UsbDevicePermission(usb_device_permission_info);
} else {
*error = kUnsupportedPermissionId;
return NULL;
}
CHECK(permission);
if (!permission->FromValue(permission_json.get())) {
*error = ErrorUtils::FormatErrorMessage(kInvalidParameter, *it);
return NULL;
}
apis.insert(permission);
} else {
const APIPermissionInfo* permission_info = info->GetByName(*it);
if (!permission_info) {
*error = ErrorUtils::FormatErrorMessage(
kUnknownPermissionError, *it);
return NULL;
}
apis.insert(permission_info->id());
}
}
}
URLPatternSet origins;
if (permissions.origins.get()) {
for (std::vector<std::string>::iterator it = permissions.origins->begin();
it != permissions.origins->end(); ++it) {
URLPattern origin(Extension::kValidHostPermissionSchemes);
URLPattern::ParseResult parse_result = origin.Parse(*it);
if (URLPattern::PARSE_SUCCESS != parse_result) {
*error = ErrorUtils::FormatErrorMessage(
kInvalidOrigin,
*it,
URLPattern::GetParseResultString(parse_result));
return NULL;
}
origins.AddPattern(origin);
}
}
return scoped_refptr<PermissionSet>(
new PermissionSet(apis, origins, URLPatternSet()));
}
Commit Message: Check prefs before allowing extension file access in the permissions API.
[email protected]
BUG=169632
Review URL: https://chromiumcodereview.appspot.com/11884008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int SeekHead::GetVoidElementCount() const
{
return m_void_element_count;
}
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
Target: 1
Example 2:
Code: void sched_exec(void)
{
struct task_struct *p = current;
unsigned long flags;
struct rq *rq;
int dest_cpu;
rq = task_rq_lock(p, &flags);
dest_cpu = p->sched_class->select_task_rq(rq, p, SD_BALANCE_EXEC, 0);
if (dest_cpu == smp_processor_id())
goto unlock;
/*
* select_task_rq() can race against ->cpus_allowed
*/
if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed) &&
likely(cpu_active(dest_cpu)) && migrate_task(p, dest_cpu)) {
struct migration_arg arg = { p, dest_cpu };
task_rq_unlock(rq, &flags);
stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
return;
}
unlock:
task_rq_unlock(rq, &flags);
}
Commit Message: Sched: fix skip_clock_update optimization
idle_balance() drops/retakes rq->lock, leaving the previous task
vulnerable to set_tsk_need_resched(). Clear it after we return
from balancing instead, and in setup_thread_stack() as well, so
no successfully descheduled or never scheduled task has it set.
Need resched confused the skip_clock_update logic, which assumes
that the next call to update_rq_clock() will come nearly immediately
after being set. Make the optimization robust against the waking
a sleeper before it sucessfully deschedules case by checking that
the current task has not been dequeued before setting the flag,
since it is that useless clock update we're trying to save, and
clear unconditionally in schedule() proper instead of conditionally
in put_prev_task().
Signed-off-by: Mike Galbraith <[email protected]>
Reported-by: Bjoern B. Brandenburg <[email protected]>
Tested-by: Yong Zhang <[email protected]>
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: [email protected]
LKML-Reference: <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int sctp_setsockopt_events(struct sock *sk, char __user *optval,
int optlen)
{
if (optlen != sizeof(struct sctp_event_subscribe))
return -EINVAL;
if (copy_from_user(&sctp_sk(sk)->subscribe, optval, optlen))
return -EFAULT;
return 0;
}
Commit Message: [SCTP]: Fix assertion (!atomic_read(&sk->sk_rmem_alloc)) failed message
In current implementation, LKSCTP does receive buffer accounting for
data in sctp_receive_queue and pd_lobby. However, LKSCTP don't do
accounting for data in frag_list when data is fragmented. In addition,
LKSCTP doesn't do accounting for data in reasm and lobby queue in
structure sctp_ulpq.
When there are date in these queue, assertion failed message is printed
in inet_sock_destruct because sk_rmem_alloc of oldsk does not become 0
when socket is destroyed.
Signed-off-by: Tsutomu Fujii <[email protected]>
Signed-off-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int csum_len_for_type(int cst)
{
switch (cst) {
case CSUM_NONE:
return 1;
case CSUM_ARCHAIC:
return 2;
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
return MD4_DIGEST_LEN;
case CSUM_MD5:
return MD5_DIGEST_LEN;
}
return 0;
}
Commit Message:
CWE ID: CWE-354
Target: 1
Example 2:
Code: void TabSpecificContentSettings::ClearGeolocationContentSettings() {
geolocation_settings_state_.ClearStateMap();
}
Commit Message: Check the content setting type is valid.
BUG=169770
Review URL: https://codereview.chromium.org/11875013
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176687 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int StreamTcpTest06 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
TcpSession ssn;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&ssn, 0, sizeof (TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_flags = TH_FIN;
p->tcph = &tcph;
/* StreamTcpPacket returns -1 on unsolicited FIN */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed: ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't: ");
goto end;
}
p->tcph->th_flags = TH_RST;
/* StreamTcpPacket returns -1 on unsolicited RST */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed (2): ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't (2): ");
goto end;
}
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
Commit Message: stream: support RST getting lost/ignored
In case of a valid RST on a SYN, the state is switched to 'TCP_CLOSED'.
However, the target of the RST may not have received it, or may not
have accepted it. Also, the RST may have been injected, so the supposed
sender may not actually be aware of the RST that was sent in it's name.
In this case the previous behavior was to switch the state to CLOSED and
accept no further TCP updates or stream reassembly.
This patch changes this. It still switches the state to CLOSED, as this
is by far the most likely to be correct. However, it will reconsider
the state if the receiver continues to talk.
To do this on each state change the previous state will be recorded in
TcpSession::pstate. If a non-RST packet is received after a RST, this
TcpSession::pstate is used to try to continue the conversation.
If the (supposed) sender of the RST is also continueing the conversation
as normal, it's highly likely it didn't send the RST. In this case
a stream event is generated.
Ticket: #2501
Reported-By: Kirill Shipulin
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t OMXNodeInstance::freeBuffer(
OMX_U32 portIndex, OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
CLOG_BUFFER(freeBuffer, "%s:%u %#x", portString(portIndex), portIndex, buffer);
removeActiveBuffer(portIndex, buffer);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer);
BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate);
OMX_ERRORTYPE err = OMX_FreeBuffer(mHandle, portIndex, header);
CLOG_IF_ERROR(freeBuffer, err, "%s:%u %#x", portString(portIndex), portIndex, buffer);
delete buffer_meta;
buffer_meta = NULL;
invalidateBufferID(buffer);
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE omx: check buffer port before using
Bug: 28816827
Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
CWE ID: CWE-119
Target: 1
Example 2:
Code: png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
png_uint_32 transformations /* Because these may affect the byte layout */)
{
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Offset to next interlace block */
static PNG_CONST unsigned int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
png_debug(1, "in png_do_read_interlace");
if (row != NULL && row_info != NULL)
{
png_uint_32 final_width;
final_width = row_info->width * png_pass_inc[pass];
switch (row_info->pixel_depth)
{
case 1:
{
png_bytep sp = row + (size_t)((row_info->width - 1) >> 3);
png_bytep dp = row + (size_t)((final_width - 1) >> 3);
unsigned int sshift, dshift;
unsigned int s_start, s_end;
int s_inc;
int jstop = (int)png_pass_inc[pass];
png_byte v;
png_uint_32 i;
int j;
#ifdef PNG_READ_PACKSWAP_SUPPORTED
if ((transformations & PNG_PACKSWAP) != 0)
{
sshift = ((row_info->width + 7) & 0x07);
dshift = ((final_width + 7) & 0x07);
s_start = 7;
s_end = 0;
s_inc = -1;
}
else
#endif
{
sshift = 7 - ((row_info->width + 7) & 0x07);
dshift = 7 - ((final_width + 7) & 0x07);
s_start = 0;
s_end = 7;
s_inc = 1;
}
for (i = 0; i < row_info->width; i++)
{
v = (png_byte)((*sp >> sshift) & 0x01);
for (j = 0; j < jstop; j++)
{
unsigned int tmp = *dp & (0x7f7f >> (7 - dshift));
tmp |= (unsigned int)(v << dshift);
*dp = (png_byte)(tmp & 0xff);
if (dshift == s_end)
{
dshift = s_start;
dp--;
}
else
dshift = (unsigned int)((int)dshift + s_inc);
}
if (sshift == s_end)
{
sshift = s_start;
sp--;
}
else
sshift = (unsigned int)((int)sshift + s_inc);
}
break;
}
case 2:
{
png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
unsigned int sshift, dshift;
unsigned int s_start, s_end;
int s_inc;
int jstop = (int)png_pass_inc[pass];
png_uint_32 i;
#ifdef PNG_READ_PACKSWAP_SUPPORTED
if ((transformations & PNG_PACKSWAP) != 0)
{
sshift = (((row_info->width + 3) & 0x03) << 1);
dshift = (((final_width + 3) & 0x03) << 1);
s_start = 6;
s_end = 0;
s_inc = -2;
}
else
#endif
{
sshift = ((3 - ((row_info->width + 3) & 0x03)) << 1);
dshift = ((3 - ((final_width + 3) & 0x03)) << 1);
s_start = 0;
s_end = 6;
s_inc = 2;
}
for (i = 0; i < row_info->width; i++)
{
png_byte v;
int j;
v = (png_byte)((*sp >> sshift) & 0x03);
for (j = 0; j < jstop; j++)
{
unsigned int tmp = *dp & (0x3f3f >> (6 - dshift));
tmp |= (unsigned int)(v << dshift);
*dp = (png_byte)(tmp & 0xff);
if (dshift == s_end)
{
dshift = s_start;
dp--;
}
else
dshift = (unsigned int)((int)dshift + s_inc);
}
if (sshift == s_end)
{
sshift = s_start;
sp--;
}
else
sshift = (unsigned int)((int)sshift + s_inc);
}
break;
}
case 4:
{
png_bytep sp = row + (size_t)((row_info->width - 1) >> 1);
png_bytep dp = row + (size_t)((final_width - 1) >> 1);
unsigned int sshift, dshift;
unsigned int s_start, s_end;
int s_inc;
png_uint_32 i;
int jstop = (int)png_pass_inc[pass];
#ifdef PNG_READ_PACKSWAP_SUPPORTED
if ((transformations & PNG_PACKSWAP) != 0)
{
sshift = (((row_info->width + 1) & 0x01) << 2);
dshift = (((final_width + 1) & 0x01) << 2);
s_start = 4;
s_end = 0;
s_inc = -4;
}
else
#endif
{
sshift = ((1 - ((row_info->width + 1) & 0x01)) << 2);
dshift = ((1 - ((final_width + 1) & 0x01)) << 2);
s_start = 0;
s_end = 4;
s_inc = 4;
}
for (i = 0; i < row_info->width; i++)
{
png_byte v = (png_byte)((*sp >> sshift) & 0x0f);
int j;
for (j = 0; j < jstop; j++)
{
unsigned int tmp = *dp & (0xf0f >> (4 - dshift));
tmp |= (unsigned int)(v << dshift);
*dp = (png_byte)(tmp & 0xff);
if (dshift == s_end)
{
dshift = s_start;
dp--;
}
else
dshift = (unsigned int)((int)dshift + s_inc);
}
if (sshift == s_end)
{
sshift = s_start;
sp--;
}
else
sshift = (unsigned int)((int)sshift + s_inc);
}
break;
}
default:
{
size_t pixel_bytes = (row_info->pixel_depth >> 3);
png_bytep sp = row + (size_t)(row_info->width - 1)
* pixel_bytes;
png_bytep dp = row + (size_t)(final_width - 1) * pixel_bytes;
int jstop = (int)png_pass_inc[pass];
png_uint_32 i;
for (i = 0; i < row_info->width; i++)
{
png_byte v[8]; /* SAFE; pixel_depth does not exceed 64 */
int j;
memcpy(v, sp, pixel_bytes);
for (j = 0; j < jstop; j++)
{
memcpy(dp, v, pixel_bytes);
dp -= pixel_bytes;
}
sp -= pixel_bytes;
}
break;
}
}
row_info->width = final_width;
row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width);
}
#ifndef PNG_READ_PACKSWAP_SUPPORTED
PNG_UNUSED(transformations) /* Silence compiler warning */
#endif
}
Commit Message: [libpng16] Fix the calculation of row_factor in png_check_chunk_length
(Bug report by Thuan Pham, SourceForge issue #278)
CWE ID: CWE-190
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void rds_tcp_kill_sock(struct net *net)
{
struct rds_tcp_connection *tc, *_tc;
LIST_HEAD(tmp_list);
struct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid);
struct socket *lsock = rtn->rds_tcp_listen_sock;
rtn->rds_tcp_listen_sock = NULL;
rds_tcp_listen_stop(lsock, &rtn->rds_tcp_accept_w);
spin_lock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) {
struct net *c_net = read_pnet(&tc->t_cpath->cp_conn->c_net);
if (net != c_net || !tc->t_sock)
continue;
if (!list_has_conn(&tmp_list, tc->t_cpath->cp_conn)) {
list_move_tail(&tc->t_tcp_node, &tmp_list);
} else {
list_del(&tc->t_tcp_node);
tc->t_tcp_node_detached = true;
}
}
spin_unlock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node)
rds_conn_destroy(tc->t_cpath->cp_conn);
}
Commit Message: net: rds: force to destroy connection if t_sock is NULL in rds_tcp_kill_sock().
When it is to cleanup net namespace, rds_tcp_exit_net() will call
rds_tcp_kill_sock(), if t_sock is NULL, it will not call
rds_conn_destroy(), rds_conn_path_destroy() and rds_tcp_conn_free() to free
connection, and the worker cp_conn_w is not stopped, afterwards the net is freed in
net_drop_ns(); While cp_conn_w rds_connect_worker() will call rds_tcp_conn_path_connect()
and reference 'net' which has already been freed.
In rds_tcp_conn_path_connect(), rds_tcp_set_callbacks() will set t_sock = sock before
sock->ops->connect, but if connect() is failed, it will call
rds_tcp_restore_callbacks() and set t_sock = NULL, if connect is always
failed, rds_connect_worker() will try to reconnect all the time, so
rds_tcp_kill_sock() will never to cancel worker cp_conn_w and free the
connections.
Therefore, the condition !tc->t_sock is not needed if it is going to do
cleanup_net->rds_tcp_exit_net->rds_tcp_kill_sock, because tc->t_sock is always
NULL, and there is on other path to cancel cp_conn_w and free
connection. So this patch is to fix this.
rds_tcp_kill_sock():
...
if (net != c_net || !tc->t_sock)
...
Acked-by: Santosh Shilimkar <[email protected]>
==================================================================
BUG: KASAN: use-after-free in inet_create+0xbcc/0xd28
net/ipv4/af_inet.c:340
Read of size 4 at addr ffff8003496a4684 by task kworker/u8:4/3721
CPU: 3 PID: 3721 Comm: kworker/u8:4 Not tainted 5.1.0 #11
Hardware name: linux,dummy-virt (DT)
Workqueue: krdsd rds_connect_worker
Call trace:
dump_backtrace+0x0/0x3c0 arch/arm64/kernel/time.c:53
show_stack+0x28/0x38 arch/arm64/kernel/traps.c:152
__dump_stack lib/dump_stack.c:77 [inline]
dump_stack+0x120/0x188 lib/dump_stack.c:113
print_address_description+0x68/0x278 mm/kasan/report.c:253
kasan_report_error mm/kasan/report.c:351 [inline]
kasan_report+0x21c/0x348 mm/kasan/report.c:409
__asan_report_load4_noabort+0x30/0x40 mm/kasan/report.c:429
inet_create+0xbcc/0xd28 net/ipv4/af_inet.c:340
__sock_create+0x4f8/0x770 net/socket.c:1276
sock_create_kern+0x50/0x68 net/socket.c:1322
rds_tcp_conn_path_connect+0x2b4/0x690 net/rds/tcp_connect.c:114
rds_connect_worker+0x108/0x1d0 net/rds/threads.c:175
process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153
worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296
kthread+0x2f0/0x378 kernel/kthread.c:255
ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117
Allocated by task 687:
save_stack mm/kasan/kasan.c:448 [inline]
set_track mm/kasan/kasan.c:460 [inline]
kasan_kmalloc+0xd4/0x180 mm/kasan/kasan.c:553
kasan_slab_alloc+0x14/0x20 mm/kasan/kasan.c:490
slab_post_alloc_hook mm/slab.h:444 [inline]
slab_alloc_node mm/slub.c:2705 [inline]
slab_alloc mm/slub.c:2713 [inline]
kmem_cache_alloc+0x14c/0x388 mm/slub.c:2718
kmem_cache_zalloc include/linux/slab.h:697 [inline]
net_alloc net/core/net_namespace.c:384 [inline]
copy_net_ns+0xc4/0x2d0 net/core/net_namespace.c:424
create_new_namespaces+0x300/0x658 kernel/nsproxy.c:107
unshare_nsproxy_namespaces+0xa0/0x198 kernel/nsproxy.c:206
ksys_unshare+0x340/0x628 kernel/fork.c:2577
__do_sys_unshare kernel/fork.c:2645 [inline]
__se_sys_unshare kernel/fork.c:2643 [inline]
__arm64_sys_unshare+0x38/0x58 kernel/fork.c:2643
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall arch/arm64/kernel/syscall.c:47 [inline]
el0_svc_common+0x168/0x390 arch/arm64/kernel/syscall.c:83
el0_svc_handler+0x60/0xd0 arch/arm64/kernel/syscall.c:129
el0_svc+0x8/0xc arch/arm64/kernel/entry.S:960
Freed by task 264:
save_stack mm/kasan/kasan.c:448 [inline]
set_track mm/kasan/kasan.c:460 [inline]
__kasan_slab_free+0x114/0x220 mm/kasan/kasan.c:521
kasan_slab_free+0x10/0x18 mm/kasan/kasan.c:528
slab_free_hook mm/slub.c:1370 [inline]
slab_free_freelist_hook mm/slub.c:1397 [inline]
slab_free mm/slub.c:2952 [inline]
kmem_cache_free+0xb8/0x3a8 mm/slub.c:2968
net_free net/core/net_namespace.c:400 [inline]
net_drop_ns.part.6+0x78/0x90 net/core/net_namespace.c:407
net_drop_ns net/core/net_namespace.c:406 [inline]
cleanup_net+0x53c/0x6d8 net/core/net_namespace.c:569
process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153
worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296
kthread+0x2f0/0x378 kernel/kthread.c:255
ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117
The buggy address belongs to the object at ffff8003496a3f80
which belongs to the cache net_namespace of size 7872
The buggy address is located 1796 bytes inside of
7872-byte region [ffff8003496a3f80, ffff8003496a5e40)
The buggy address belongs to the page:
page:ffff7e000d25a800 count:1 mapcount:0 mapping:ffff80036ce4b000
index:0x0 compound_mapcount: 0
flags: 0xffffe0000008100(slab|head)
raw: 0ffffe0000008100 dead000000000100 dead000000000200 ffff80036ce4b000
raw: 0000000000000000 0000000080040004 00000001ffffffff 0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff8003496a4580: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff8003496a4600: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
>ffff8003496a4680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff8003496a4700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff8003496a4780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
Fixes: 467fa15356ac("RDS-TCP: Support multiple RDS-TCP listen endpoints, one per netns.")
Reported-by: Hulk Robot <[email protected]>
Signed-off-by: Mao Wenan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int fpga_reset(void)
{
if (!check_boco2()) {
/* we do not have BOCO2, this is not really used */
return 0;
}
printf("PCIe reset through GPIO7: ");
/* apply PCIe reset via GPIO */
kw_gpio_set_valid(KM_PEX_RST_GPIO_PIN, 1);
kw_gpio_direction_output(KM_PEX_RST_GPIO_PIN, 1);
kw_gpio_set_value(KM_PEX_RST_GPIO_PIN, 0);
udelay(1000*10);
kw_gpio_set_value(KM_PEX_RST_GPIO_PIN, 1);
printf(" done\n");
return 0;
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787
Target: 1
Example 2:
Code: bool ndp_msgra_flag_other(struct ndp_msgra *msgra)
{
return msgra->ra->nd_ra_flags_reserved & ND_RA_FLAG_OTHER;
}
Commit Message: libndp: validate the IPv6 hop limit
None of the NDP messages should ever come from a non-local network; as
stated in RFC4861's 6.1.1 (RS), 6.1.2 (RA), 7.1.1 (NS), 7.1.2 (NA),
and 8.1. (redirect):
- The IP Hop Limit field has a value of 255, i.e., the packet
could not possibly have been forwarded by a router.
This fixes CVE-2016-3698.
Reported by: Julien BERNARD <[email protected]>
Signed-off-by: Lubomir Rintel <[email protected]>
Signed-off-by: Jiri Pirko <[email protected]>
CWE ID: CWE-284
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int b_unpack (lua_State *L) {
Header h;
const char *fmt = luaL_checkstring(L, 1);
size_t ld;
const char *data = luaL_checklstring(L, 2, &ld);
size_t pos = luaL_optinteger(L, 3, 1) - 1;
int n = 0; /* number of results */
defaultoptions(&h);
while (*fmt) {
int opt = *fmt++;
size_t size = optsize(L, opt, &fmt);
pos += gettoalign(pos, &h, opt, size);
luaL_argcheck(L, pos+size <= ld, 2, "data string too short");
/* stack space for item + next position */
luaL_checkstack(L, 2, "too many results");
switch (opt) {
case 'b': case 'B': case 'h': case 'H':
case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */
int issigned = islower(opt);
lua_Number res = getinteger(data+pos, h.endian, issigned, size);
lua_pushnumber(L, res); n++;
break;
}
case 'x': {
break;
}
case 'f': {
float f;
memcpy(&f, data+pos, size);
correctbytes((char *)&f, sizeof(f), h.endian);
lua_pushnumber(L, f); n++;
break;
}
case 'd': {
double d;
memcpy(&d, data+pos, size);
correctbytes((char *)&d, sizeof(d), h.endian);
lua_pushnumber(L, d); n++;
break;
}
case 'c': {
if (size == 0) {
if (n == 0 || !lua_isnumber(L, -1))
luaL_error(L, "format 'c0' needs a previous size");
size = lua_tonumber(L, -1);
lua_pop(L, 1); n--;
luaL_argcheck(L, size <= ld && pos <= ld - size,
2, "data string too short");
}
lua_pushlstring(L, data+pos, size); n++;
break;
}
case 's': {
const char *e = (const char *)memchr(data+pos, '\0', ld - pos);
if (e == NULL)
luaL_error(L, "unfinished string in data");
size = (e - (data+pos)) + 1;
lua_pushlstring(L, data+pos, size - 1); n++;
break;
}
default: controloptions(L, opt, &fmt, &h);
}
pos += size;
}
lua_pushinteger(L, pos + 1); /* next position */
return n + 1;
}
Commit Message: Security: fix Lua struct package offset handling.
After the first fix to the struct package I found another similar
problem, which is fixed by this patch. It could be reproduced easily by
running the following script:
return struct.unpack('f', "xxxxxxxxxxxxx",-3)
The above will access bytes before the 'data' pointer.
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->SetRenderer(frame_host_ ? frame_host_->GetProcess()->GetID()
: ChildProcessHost::kInvalidUniqueID,
frame_host_);
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::DOMHandler()));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::MemoryHandler()));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
session->AddHandler(
base::WrapUnique(new protocol::TargetHandler(false /* browser_only */)));
session->AddHandler(base::WrapUnique(new protocol::TracingHandler(
protocol::TracingHandler::Renderer,
frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0,
GetIOContext())));
session->AddHandler(
base::WrapUnique(new protocol::PageHandler(emulation_handler)));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
if (EnsureAgent())
session->AttachToAgent(agent_ptr_);
if (sessions().size() == 1) {
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
}
Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages
If the page navigates to web ui, we force detach the debugger extension.
[email protected]
Bug: 798222
Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3
Reviewed-on: https://chromium-review.googlesource.com/935961
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540916}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static v8::Handle<v8::Value> unsignedIntSequenceAttrAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info)
{
INC_STATS("DOM.TestObj.unsignedIntSequenceAttr._get");
TestObj* imp = V8TestObj::toNative(info.Holder());
return v8Array(imp->unsignedIntSequenceAttr(), info.GetIsolate());
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int nbd_negotiate_write(QIOChannel *ioc, const void *buffer, size_t size)
{
ssize_t ret;
guint watch;
assert(qemu_in_coroutine());
/* Negotiation are always in main loop. */
watch = qio_channel_add_watch(ioc,
G_IO_OUT,
nbd_negotiate_continue,
qemu_coroutine_self(),
NULL);
ret = nbd_write(ioc, buffer, size, NULL);
g_source_remove(watch);
return ret;
}
Commit Message:
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool FileBrowserPrivateGetShareUrlFunction::RunAsync() {
using extensions::api::file_browser_private::GetShareUrl::Params;
const scoped_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
const base::FilePath path = file_manager::util::GetLocalPathFromURL(
render_view_host(), GetProfile(), GURL(params->url));
DCHECK(drive::util::IsUnderDriveMountPoint(path));
const base::FilePath drive_path = drive::util::ExtractDrivePath(path);
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(GetProfile());
if (!file_system) {
return false;
}
file_system->GetShareUrl(
drive_path,
file_manager::util::GetFileManagerBaseUrl(), // embed origin
base::Bind(&FileBrowserPrivateGetShareUrlFunction::OnGetShareUrl, this));
return true;
}
Commit Message: Reland r286968: The CL borrows ShareDialog from Files.app and add it to Gallery.
Previous Review URL: https://codereview.chromium.org/431293002
BUG=374667
TEST=manually
[email protected], [email protected]
Review URL: https://codereview.chromium.org/433733004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@286975 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: PHP_FUNCTION(pg_free_result)
{
zval *result;
pgsql_result_handle *pg_result;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &result) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
if (Z_RES_P(result) == NULL) {
RETURN_FALSE;
}
zend_list_close(Z_RES_P(result));
RETURN_TRUE;
}
Commit Message:
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
SplashCoord *mat, GBool glyphMode) {
SplashBitmap *scaledMask;
SplashClipResult clipRes, clipRes2;
SplashPipe pipe;
int scaledWidth, scaledHeight, t0, t1;
SplashCoord r00, r01, r10, r11, det, ir00, ir01, ir10, ir11;
SplashCoord vx[4], vy[4];
int xMin, yMin, xMax, yMax;
ImageSection section[3];
int nSections;
int y, xa, xb, x, i, xx, yy;
vx[0] = mat[4]; vy[0] = mat[5];
vx[1] = mat[2] + mat[4]; vy[1] = mat[3] + mat[5];
vx[2] = mat[0] + mat[2] + mat[4]; vy[2] = mat[1] + mat[3] + mat[5];
vx[3] = mat[0] + mat[4]; vy[3] = mat[1] + mat[5];
xMin = imgCoordMungeLowerC(vx[0], glyphMode);
xMax = imgCoordMungeUpperC(vx[0], glyphMode);
yMin = imgCoordMungeLowerC(vy[0], glyphMode);
yMax = imgCoordMungeUpperC(vy[0], glyphMode);
for (i = 1; i < 4; ++i) {
t0 = imgCoordMungeLowerC(vx[i], glyphMode);
if (t0 < xMin) {
xMin = t0;
}
t0 = imgCoordMungeUpperC(vx[i], glyphMode);
if (t0 > xMax) {
xMax = t0;
}
t1 = imgCoordMungeLowerC(vy[i], glyphMode);
if (t1 < yMin) {
yMin = t1;
}
t1 = imgCoordMungeUpperC(vy[i], glyphMode);
if (t1 > yMax) {
yMax = t1;
}
}
clipRes = state->clip->testRect(xMin, yMin, xMax - 1, yMax - 1);
opClipRes = clipRes;
if (clipRes == splashClipAllOutside) {
return;
}
if (mat[0] >= 0) {
t0 = imgCoordMungeUpperC(mat[0] + mat[4], glyphMode) -
imgCoordMungeLowerC(mat[4], glyphMode);
} else {
t0 = imgCoordMungeUpperC(mat[4], glyphMode) -
imgCoordMungeLowerC(mat[0] + mat[4], glyphMode);
}
if (mat[1] >= 0) {
t1 = imgCoordMungeUpperC(mat[1] + mat[5], glyphMode) -
imgCoordMungeLowerC(mat[5], glyphMode);
} else {
t1 = imgCoordMungeUpperC(mat[5], glyphMode) -
imgCoordMungeLowerC(mat[1] + mat[5], glyphMode);
}
scaledWidth = t0 > t1 ? t0 : t1;
if (mat[2] >= 0) {
t0 = imgCoordMungeUpperC(mat[2] + mat[4], glyphMode) -
imgCoordMungeLowerC(mat[4], glyphMode);
} else {
t0 = imgCoordMungeUpperC(mat[4], glyphMode) -
imgCoordMungeLowerC(mat[2] + mat[4], glyphMode);
}
if (mat[3] >= 0) {
t1 = imgCoordMungeUpperC(mat[3] + mat[5], glyphMode) -
imgCoordMungeLowerC(mat[5], glyphMode);
} else {
t1 = imgCoordMungeUpperC(mat[5], glyphMode) -
imgCoordMungeLowerC(mat[3] + mat[5], glyphMode);
}
scaledHeight = t0 > t1 ? t0 : t1;
if (scaledWidth == 0) {
scaledWidth = 1;
}
if (scaledHeight == 0) {
scaledHeight = 1;
}
r00 = mat[0] / scaledWidth;
r01 = mat[1] / scaledWidth;
r10 = mat[2] / scaledHeight;
r11 = mat[3] / scaledHeight;
det = r00 * r11 - r01 * r10;
if (splashAbs(det) < 1e-6) {
return;
}
ir00 = r11 / det;
ir01 = -r01 / det;
ir10 = -r10 / det;
ir11 = r00 / det;
scaledMask = scaleMask(src, srcData, srcWidth, srcHeight,
scaledWidth, scaledHeight);
i = (vy[2] <= vy[3]) ? 2 : 3;
}
Commit Message:
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: check_compat_entry_size_and_hooks(struct compat_arpt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_arpt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!arp_checkentry(&e->arp))
return -EINVAL;
ret = xt_compat_check_entry_offsets(e, e->target_offset,
e->next_offset);
if (ret)
return ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - (void *)base;
t = compat_arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto out;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
goto release_target;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
release_target:
module_put(t->u.kernel.target->me);
out:
return ret;
}
Commit Message: netfilter: x_tables: check for bogus target offset
We're currently asserting that targetoff + targetsize <= nextoff.
Extend it to also check that targetoff is >= sizeof(xt_entry).
Since this is generic code, add an argument pointing to the start of the
match/target, we can then derive the base structure size from the delta.
We also need the e->elems pointer in a followup change to validate matches.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: GC_INNER void * GC_generic_malloc_inner_ignore_off_page(size_t lb, int k)
{
word lb_adjusted;
void * op;
if (lb <= HBLKSIZE)
return(GC_generic_malloc_inner(lb, k));
lb_adjusted = ADD_SLOP(lb);
op = GC_alloc_large_and_clear(lb_adjusted, k, IGNORE_OFF_PAGE);
GC_bytes_allocd += lb_adjusted;
return op;
}
Commit Message: Fix calloc() overflow
* malloc.c (calloc): Check multiplication overflow in calloc(),
assuming REDIRECT_MALLOC.
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int cx24116_set_voltage(struct dvb_frontend *fe,
fe_sec_voltage_t voltage)
{
struct cx24116_cmd cmd;
int ret;
dprintk("%s: %s\n", __func__,
voltage == SEC_VOLTAGE_13 ? "SEC_VOLTAGE_13" :
voltage == SEC_VOLTAGE_18 ? "SEC_VOLTAGE_18" : "??");
/* Wait for LNB ready */
ret = cx24116_wait_for_lnb(fe);
if (ret != 0)
return ret;
/* Wait for voltage/min repeat delay */
msleep(100);
cmd.args[0x00] = CMD_LNBDCLEVEL;
cmd.args[0x01] = (voltage == SEC_VOLTAGE_18 ? 0x01 : 0x00);
cmd.len = 0x02;
/* Min delay time before DiSEqC send */
msleep(15);
return cx24116_cmd_execute(fe, &cmd);
}
Commit Message: [media] cx24116: fix a buffer overflow when checking userspace params
The maximum size for a DiSEqC command is 6, according to the
userspace API. However, the code allows to write up much more values:
drivers/media/dvb-frontends/cx24116.c:983 cx24116_send_diseqc_msg() error: buffer overflow 'd->msg' 6 <= 23
Cc: [email protected]
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ProfileChooserView::SignOutAllWebAccounts() {
Hide();
ProfileOAuth2TokenServiceFactory::GetForProfile(browser_->profile())
->RevokeAllCredentials();
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static irqreturn_t dwc3_interrupt(int irq, void *_evt)
{
struct dwc3_event_buffer *evt = _evt;
return dwc3_check_event_buf(evt);
}
Commit Message: usb: dwc3: gadget: never call ->complete() from ->ep_queue()
This is a requirement which has always existed but, somehow, wasn't
reflected in the documentation and problems weren't found until now
when Tuba Yavuz found a possible deadlock happening between dwc3 and
f_hid. She described the situation as follows:
spin_lock_irqsave(&hidg->write_spinlock, flags); // first acquire
/* we our function has been disabled by host */
if (!hidg->req) {
free_ep_req(hidg->in_ep, hidg->req);
goto try_again;
}
[...]
status = usb_ep_queue(hidg->in_ep, hidg->req, GFP_ATOMIC);
=>
[...]
=> usb_gadget_giveback_request
=>
f_hidg_req_complete
=>
spin_lock_irqsave(&hidg->write_spinlock, flags); // second acquire
Note that this happens because dwc3 would call ->complete() on a
failed usb_ep_queue() due to failed Start Transfer command. This is,
anyway, a theoretical situation because dwc3 currently uses "No
Response Update Transfer" command for Bulk and Interrupt endpoints.
It's still good to make this case impossible to happen even if the "No
Reponse Update Transfer" command is changed.
Reported-by: Tuba Yavuz <[email protected]>
Signed-off-by: Felipe Balbi <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ewk_frame_editor_client_contents_changed(Evas_Object* ewkFrame)
{
evas_object_smart_callback_call(ewkFrame, "editorclient,contents,changed", 0);
EWK_FRAME_SD_GET_OR_RETURN(ewkFrame, smartData);
ewk_view_editor_client_contents_changed(smartData->view);
}
Commit Message: [EFL] fast/frames/frame-crash-with-page-cache.html is crashing
https://bugs.webkit.org/show_bug.cgi?id=85879
Patch by Mikhail Pozdnyakov <[email protected]> on 2012-05-17
Reviewed by Noam Rosenthal.
Source/WebKit/efl:
_ewk_frame_smart_del() is considering now that the frame can be present in cache.
loader()->detachFromParent() is only applied for the main frame.
loader()->cancelAndClear() is not used anymore.
* ewk/ewk_frame.cpp:
(_ewk_frame_smart_del):
LayoutTests:
* platform/efl/test_expectations.txt: Removed fast/frames/frame-crash-with-page-cache.html.
git-svn-id: svn://svn.chromium.org/blink/trunk@117409 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool xmp_init()
{
RESET_ERROR;
try {
bool result = SXMPFiles::Initialize(kXMPFiles_IgnoreLocalText);
SXMPMeta::SetDefaultErrorCallback(&_xmp_error_callback, nullptr, 1);
return result;
SXMPMeta::SetDefaultErrorCallback(&_xmp_error_callback, nullptr, 1);
return result;
}
catch (const XMP_Error &e) {
set_error(e);
}
return false;
}
Commit Message:
CWE ID: CWE-416
Target: 1
Example 2:
Code: static void hmac_exit_tfm(struct crypto_tfm *tfm)
{
struct hmac_ctx *ctx = hmac_ctx(__crypto_shash_cast(tfm));
crypto_free_shash(ctx->hash);
}
Commit Message: crypto: include crypto- module prefix in template
This adds the module loading prefix "crypto-" to the template lookup
as well.
For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly
includes the "crypto-" prefix at every level, correctly rejecting "vfat":
net-pf-38
algif-hash
crypto-vfat(blowfish)
crypto-vfat(blowfish)-all
crypto-vfat
Reported-by: Mathias Krause <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Acked-by: Mathias Krause <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const BlockEntry* Cues::GetBlock(
const CuePoint* pCP,
const CuePoint::TrackPosition* pTP) const
{
if (pCP == NULL)
return NULL;
if (pTP == NULL)
return NULL;
return m_pSegment->GetBlock(*pCP, *pTP);
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int pop_sync_mailbox(struct Context *ctx, int *index_hint)
{
int i, j, ret = 0;
char buf[LONG_STRING];
struct PopData *pop_data = (struct PopData *) ctx->data;
struct Progress progress;
#ifdef USE_HCACHE
header_cache_t *hc = NULL;
#endif
pop_data->check_time = 0;
while (true)
{
if (pop_reconnect(ctx) < 0)
return -1;
mutt_progress_init(&progress, _("Marking messages deleted..."),
MUTT_PROGRESS_MSG, WriteInc, ctx->deleted);
#ifdef USE_HCACHE
hc = pop_hcache_open(pop_data, ctx->path);
#endif
for (i = 0, j = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++)
{
if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->refno != -1)
{
j++;
if (!ctx->quiet)
mutt_progress_update(&progress, j, -1);
snprintf(buf, sizeof(buf), "DELE %d\r\n", ctx->hdrs[i]->refno);
ret = pop_query(pop_data, buf, sizeof(buf));
if (ret == 0)
{
mutt_bcache_del(pop_data->bcache, ctx->hdrs[i]->data);
#ifdef USE_HCACHE
mutt_hcache_delete(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data));
#endif
}
}
#ifdef USE_HCACHE
if (ctx->hdrs[i]->changed)
{
mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data),
ctx->hdrs[i], 0);
}
#endif
}
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (ret == 0)
{
mutt_str_strfcpy(buf, "QUIT\r\n", sizeof(buf));
ret = pop_query(pop_data, buf, sizeof(buf));
}
if (ret == 0)
{
pop_data->clear_cache = true;
pop_clear_cache(pop_data);
pop_data->status = POP_DISCONNECTED;
return 0;
}
if (ret == -2)
{
mutt_error("%s", pop_data->err_msg);
return -1;
}
}
}
Commit Message: sanitise cache paths
Co-authored-by: JerikoOne <[email protected]>
CWE ID: CWE-22
Target: 1
Example 2:
Code: nlmsvc_owner_key(struct file_lock *fl)
{
return (unsigned long)fl->fl_owner ^ (unsigned long)fl->fl_pid;
}
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GDataDirectory::RemoveChildFiles() {
for (GDataFileCollection::const_iterator iter = child_files_.begin();
iter != child_files_.end(); ++iter) {
if (directory_service_)
directory_service_->RemoveEntryFromResourceMap(iter->second);
}
STLDeleteValues(&child_files_);
child_files_.clear();
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: nsPluginInstance::setupCookies(const std::string& pageurl)
{
std::string::size_type pos;
pos = pageurl.find("/", pageurl.find("//", 0) + 2) + 1;
std::string url = pageurl.substr(0, pos);
std::string ncookie;
char *cookie = 0;
uint32_t length = 0;
NPError rv = NPERR_GENERIC_ERROR;
#if NPAPI_VERSION != 190
if (NPNFuncs.getvalueforurl) {
rv = NPN_GetValueForURL(_instance, NPNURLVCookie, url.c_str(),
&cookie, &length);
} else {
LOG_ONCE( gnash::log_debug("Browser doesn't support getvalueforurl") );
}
#endif
if (rv == NPERR_GENERIC_ERROR) {
log_debug("Trying window.document.cookie for cookies");
ncookie = getDocumentProp("cookie");
}
if (cookie) {
ncookie.assign(cookie, length);
NPN_MemFree(cookie);
}
if (ncookie.empty()) {
gnash::log_debug("No stored Cookie for %s", url);
return;
}
gnash::log_debug("The Cookie for %s is %s", url, ncookie);
std::ofstream cookiefile;
std::stringstream ss;
ss << "/tmp/gnash-cookies." << getpid();
cookiefile.open(ss.str().c_str(), std::ios::out | std::ios::trunc);
typedef boost::char_separator<char> char_sep;
typedef boost::tokenizer<char_sep> tokenizer;
tokenizer tok(ncookie, char_sep(";"));
for (tokenizer::iterator it=tok.begin(); it != tok.end(); ++it) {
cookiefile << "Set-Cookie: " << *it << std::endl;
}
cookiefile.close();
if (setenv("GNASH_COOKIES_IN", ss.str().c_str(), 1) < 0) {
gnash::log_error(
"Couldn't set environment variable GNASH_COOKIES_IN to %s",
ncookie);
}
}
Commit Message:
CWE ID: CWE-264
Target: 1
Example 2:
Code: int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval,
unsigned int optlen)
{
struct inet_connection_sock *icsk = inet_csk(sk);
if (level != SOL_TCP)
return icsk->icsk_af_ops->setsockopt(sk, level, optname,
optval, optlen);
return do_tcp_setsockopt(sk, level, optname, optval, optlen);
}
Commit Message: net: Fix oops from tcp_collapse() when using splice()
tcp_read_sock() can have a eat skbs without immediately advancing copied_seq.
This can cause a panic in tcp_collapse() if it is called as a result
of the recv_actor dropping the socket lock.
A userspace program that splices data from a socket to either another
socket or to a file can trigger this bug.
Signed-off-by: Steven J. Magnani <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: IndexedDBDispatcher* IndexedDBDispatcher::ThreadSpecificInstance() {
if (g_idb_dispatcher_tls.Pointer()->Get())
return g_idb_dispatcher_tls.Pointer()->Get();
IndexedDBDispatcher* dispatcher = new IndexedDBDispatcher;
if (WorkerTaskRunner::Instance()->CurrentWorkerId())
webkit_glue::WorkerTaskRunner::Instance()->AddStopObserver(dispatcher);
return dispatcher;
}
Commit Message: Add DCHECK to ensure IndexedDBDispatcher doesn't get re-created.
This could happen if there are IDB objects that survive the call to
didStopWorkerRunLoop.
BUG=121734
TEST=
Review URL: http://codereview.chromium.org/9999035
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131679 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int __init ipip_init(void)
{
int err;
printk(banner);
if (xfrm4_tunnel_register(&ipip_handler, AF_INET)) {
printk(KERN_INFO "ipip init: can't register tunnel\n");
return -EAGAIN;
}
err = register_pernet_device(&ipip_net_ops);
if (err)
xfrm4_tunnel_deregister(&ipip_handler, AF_INET);
return err;
}
Commit Message: tunnels: fix netns vs proto registration ordering
Same stuff as in ip_gre patch: receive hook can be called before netns
setup is done, oopsing in net_generic().
Signed-off-by: Alexey Dobriyan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: void RenderWidgetHostViewAndroid::UpdateCursor(const WebCursor& cursor) {
}
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:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void __unregister_pernet_operations(struct pernet_operations *ops)
{
struct net *net;
LIST_HEAD(net_exit_list);
list_del(&ops->list);
for_each_net(net)
list_add_tail(&net->exit_list, &net_exit_list);
ops_exit_list(ops, &net_exit_list);
ops_free_list(ops, &net_exit_list);
}
Commit Message: net: Fix double free and memory corruption in get_net_ns_by_id()
(I can trivially verify that that idr_remove in cleanup_net happens
after the network namespace count has dropped to zero --EWB)
Function get_net_ns_by_id() does not check for net::count
after it has found a peer in netns_ids idr.
It may dereference a peer, after its count has already been
finaly decremented. This leads to double free and memory
corruption:
put_net(peer) rtnl_lock()
atomic_dec_and_test(&peer->count) [count=0] ...
__put_net(peer) get_net_ns_by_id(net, id)
spin_lock(&cleanup_list_lock)
list_add(&net->cleanup_list, &cleanup_list)
spin_unlock(&cleanup_list_lock)
queue_work() peer = idr_find(&net->netns_ids, id)
| get_net(peer) [count=1]
| ...
| (use after final put)
v ...
cleanup_net() ...
spin_lock(&cleanup_list_lock) ...
list_replace_init(&cleanup_list, ..) ...
spin_unlock(&cleanup_list_lock) ...
... ...
... put_net(peer)
... atomic_dec_and_test(&peer->count) [count=0]
... spin_lock(&cleanup_list_lock)
... list_add(&net->cleanup_list, &cleanup_list)
... spin_unlock(&cleanup_list_lock)
... queue_work()
... rtnl_unlock()
rtnl_lock() ...
for_each_net(tmp) { ...
id = __peernet2id(tmp, peer) ...
spin_lock_irq(&tmp->nsid_lock) ...
idr_remove(&tmp->netns_ids, id) ...
... ...
net_drop_ns() ...
net_free(peer) ...
} ...
|
v
cleanup_net()
...
(Second free of peer)
Also, put_net() on the right cpu may reorder with left's cpu
list_replace_init(&cleanup_list, ..), and then cleanup_list
will be corrupted.
Since cleanup_net() is executed in worker thread, while
put_net(peer) can happen everywhere, there should be
enough time for concurrent get_net_ns_by_id() to pick
the peer up, and the race does not seem to be unlikely.
The patch fixes the problem in standard way.
(Also, there is possible problem in peernet2id_alloc(), which requires
check for net::count under nsid_lock and maybe_get_net(peer), but
in current stable kernel it's used under rtnl_lock() and it has to be
safe. Openswitch begun to use peernet2id_alloc(), and possibly it should
be fixed too. While this is not in stable kernel yet, so I'll send
a separate message to netdev@ later).
Cc: Nicolas Dichtel <[email protected]>
Signed-off-by: Kirill Tkhai <[email protected]>
Fixes: 0c7aecd4bde4 "netns: add rtnl cmd to add and get peer netns ids"
Reviewed-by: Andrey Ryabinin <[email protected]>
Reviewed-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: Eric W. Biederman <[email protected]>
Reviewed-by: Eric Dumazet <[email protected]>
Acked-by: Nicolas Dichtel <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SendRequest() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!service_)
return;
bool is_extended_reporting = false;
if (item_->GetBrowserContext()) {
Profile* profile =
Profile::FromBrowserContext(item_->GetBrowserContext());
is_extended_reporting = profile &&
profile->GetPrefs()->GetBoolean(
prefs::kSafeBrowsingExtendedReportingEnabled);
}
ClientDownloadRequest request;
if (is_extended_reporting) {
request.mutable_population()->set_user_population(
ChromeUserPopulation::EXTENDED_REPORTING);
} else {
request.mutable_population()->set_user_population(
ChromeUserPopulation::SAFE_BROWSING);
}
request.set_url(SanitizeUrl(item_->GetUrlChain().back()));
request.mutable_digests()->set_sha256(item_->GetHash());
request.set_length(item_->GetReceivedBytes());
for (size_t i = 0; i < item_->GetUrlChain().size(); ++i) {
ClientDownloadRequest::Resource* resource = request.add_resources();
resource->set_url(SanitizeUrl(item_->GetUrlChain()[i]));
if (i == item_->GetUrlChain().size() - 1) {
resource->set_type(ClientDownloadRequest::DOWNLOAD_URL);
resource->set_referrer(SanitizeUrl(item_->GetReferrerUrl()));
DVLOG(2) << "dl url " << resource->url();
if (!item_->GetRemoteAddress().empty()) {
resource->set_remote_ip(item_->GetRemoteAddress());
DVLOG(2) << " dl url remote addr: " << resource->remote_ip();
}
DVLOG(2) << "dl referrer " << resource->referrer();
} else {
DVLOG(2) << "dl redirect " << i << " " << resource->url();
resource->set_type(ClientDownloadRequest::DOWNLOAD_REDIRECT);
}
}
for (size_t i = 0; i < tab_redirects_.size(); ++i) {
ClientDownloadRequest::Resource* resource = request.add_resources();
DVLOG(2) << "tab redirect " << i << " " << tab_redirects_[i].spec();
resource->set_url(SanitizeUrl(tab_redirects_[i]));
resource->set_type(ClientDownloadRequest::TAB_REDIRECT);
}
if (tab_url_.is_valid()) {
ClientDownloadRequest::Resource* resource = request.add_resources();
resource->set_url(SanitizeUrl(tab_url_));
DVLOG(2) << "tab url " << resource->url();
resource->set_type(ClientDownloadRequest::TAB_URL);
if (tab_referrer_url_.is_valid()) {
resource->set_referrer(SanitizeUrl(tab_referrer_url_));
DVLOG(2) << "tab referrer " << resource->referrer();
}
}
request.set_user_initiated(item_->HasUserGesture());
request.set_file_basename(
item_->GetTargetFilePath().BaseName().AsUTF8Unsafe());
request.set_download_type(type_);
request.mutable_signature()->CopyFrom(signature_info_);
if (image_headers_)
request.set_allocated_image_headers(image_headers_.release());
if (zipped_executable_)
request.mutable_archived_binary()->Swap(&archived_binary_);
if (!request.SerializeToString(&client_download_request_data_)) {
FinishRequest(UNKNOWN, REASON_INVALID_REQUEST_PROTO);
return;
}
service_->client_download_request_callbacks_.Notify(item_, &request);
DVLOG(2) << "Sending a request for URL: "
<< item_->GetUrlChain().back();
fetcher_ = net::URLFetcher::Create(0 /* ID used for testing */,
GetDownloadRequestUrl(),
net::URLFetcher::POST, this);
fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
fetcher_->SetAutomaticallyRetryOn5xx(false); // Don't retry on error.
fetcher_->SetRequestContext(service_->request_context_getter_.get());
fetcher_->SetUploadData("application/octet-stream",
client_download_request_data_);
request_start_time_ = base::TimeTicks::Now();
UMA_HISTOGRAM_COUNTS("SBClientDownload.DownloadRequestPayloadSize",
client_download_request_data_.size());
fetcher_->Start();
}
Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService.
BUG=496898,464083
[email protected], [email protected], [email protected], [email protected]
Review URL: https://codereview.chromium.org/1299223006 .
Cr-Commit-Position: refs/heads/master@{#344876}
CWE ID:
Target: 1
Example 2:
Code: static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen)
{
sc_context_t *ctx;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
tcos_data *data;
int tcos3, r;
assert(card != NULL && crgram != NULL && out != NULL);
ctx = card->ctx;
tcos3=(card->type==SC_CARD_TYPE_TCOS_V3);
data=(tcos_data *)card->drv_data;
SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_NORMAL);
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"TCOS3:%d PKCS1:%d\n",tcos3,
!!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1));
sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = crgram_len;
apdu.data = sbuf;
apdu.lc = apdu.datalen = crgram_len+1;
sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02);
memcpy(sbuf+1, crgram, crgram_len);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1==0x90 && apdu.sw2==0x00) {
size_t len= (apdu.resplen>outlen) ? outlen : apdu.resplen;
unsigned int offset=0;
if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2){
offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset;
offset=(offset<len-1) ? offset+1 : 0;
}
memcpy(out, apdu.resp+offset, len-offset);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Document::fullScreenElementRemoved()
{
m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
webkitCancelFullScreen();
}
Commit Message: Unreviewed, rolling out r147402.
http://trac.webkit.org/changeset/147402
https://bugs.webkit.org/show_bug.cgi?id=112903
Source/WebCore:
* dom/Document.cpp:
(WebCore::Document::processHttpEquiv):
* loader/DocumentLoader.cpp:
(WebCore::DocumentLoader::responseReceived):
LayoutTests:
* http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag.html:
* http/tests/security/XFrameOptions/x-frame-options-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny.html:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
git-svn-id: svn://svn.chromium.org/blink/trunk@147450 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static ssize_t aio_setup_single_vector(struct kiocb *kiocb)
{
kiocb->ki_iovec = &kiocb->ki_inline_vec;
kiocb->ki_iovec->iov_base = kiocb->ki_buf;
kiocb->ki_iovec->iov_len = kiocb->ki_left;
kiocb->ki_nr_segs = 1;
kiocb->ki_cur_seg = 0;
return 0;
}
Commit Message: vfs: make AIO use the proper rw_verify_area() area helpers
We had for some reason overlooked the AIO interface, and it didn't use
the proper rw_verify_area() helper function that checks (for example)
mandatory locking on the file, and that the size of the access doesn't
cause us to overflow the provided offset limits etc.
Instead, AIO did just the security_file_permission() thing (that
rw_verify_area() also does) directly.
This fixes it to do all the proper helper functions, which not only
means that now mandatory file locking works with AIO too, we can
actually remove lines of code.
Reported-by: Manish Honap <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: process_polygon2(STREAM s, POLYGON2_ORDER * os, uint32 present, RD_BOOL delta)
{
int index, data, next;
uint8 flags = 0;
RD_POINT *points;
BRUSH brush;
if (present & 0x0001)
rdp_in_coord(s, &os->x, delta);
if (present & 0x0002)
rdp_in_coord(s, &os->y, delta);
if (present & 0x0004)
in_uint8(s, os->opcode);
if (present & 0x0008)
in_uint8(s, os->fillmode);
if (present & 0x0010)
rdp_in_colour(s, &os->bgcolour);
if (present & 0x0020)
rdp_in_colour(s, &os->fgcolour);
rdp_parse_brush(s, &os->brush, present >> 6);
if (present & 0x0800)
in_uint8(s, os->npoints);
if (present & 0x1000)
{
in_uint8(s, os->datasize);
in_uint8a(s, os->data, os->datasize);
}
logger(Graphics, Debug,
"process_polygon2(), x=%d, y=%d, op=0x%x, fm=%d, bs=%d, bg=0x%x, fg=0x%x, n=%d, sz=%d)",
os->x, os->y, os->opcode, os->fillmode, os->brush.style, os->bgcolour, os->fgcolour,
os->npoints, os->datasize);
if (os->opcode < 0x01 || os->opcode > 0x10)
{
logger(Graphics, Error, "process_polygon2(), bad ROP2 0x%x", os->opcode);
return;
}
setup_brush(&brush, &os->brush);
points = (RD_POINT *) xmalloc((os->npoints + 1) * sizeof(RD_POINT));
memset(points, 0, (os->npoints + 1) * sizeof(RD_POINT));
points[0].x = os->x;
points[0].y = os->y;
index = 0;
data = ((os->npoints - 1) / 4) + 1;
for (next = 1; (next <= os->npoints) && (next < 256) && (data < os->datasize); next++)
{
if ((next - 1) % 4 == 0)
flags = os->data[index++];
if (~flags & 0x80)
points[next].x = parse_delta(os->data, &data);
if (~flags & 0x40)
points[next].y = parse_delta(os->data, &data);
flags <<= 2;
}
if (next - 1 == os->npoints)
ui_polygon(os->opcode - 1, os->fillmode, points, os->npoints + 1,
&brush, os->bgcolour, os->fgcolour);
else
logger(Graphics, Error, "process_polygon2(), polygon parse error");
xfree(points);
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int UDPSocketWin::InternalRecvFrom(IOBuffer* buf, int buf_len,
IPEndPoint* address) {
DCHECK(!core_->read_iobuffer_);
SockaddrStorage& storage = core_->recv_addr_storage_;
storage.addr_len = sizeof(storage.addr_storage);
WSABUF read_buffer;
read_buffer.buf = buf->data();
read_buffer.len = buf_len;
DWORD flags = 0;
DWORD num;
CHECK_NE(INVALID_SOCKET, socket_);
AssertEventNotSignaled(core_->read_overlapped_.hEvent);
int rv = WSARecvFrom(socket_, &read_buffer, 1, &num, &flags, storage.addr,
&storage.addr_len, &core_->read_overlapped_, NULL);
if (rv == 0) {
if (ResetEventIfSignaled(core_->read_overlapped_.hEvent)) {
int result = num;
if (address && result >= 0) {
if (!ReceiveAddressToIPEndpoint(address))
result = ERR_FAILED;
}
LogRead(result, buf->data());
return result;
}
} else {
int os_error = WSAGetLastError();
if (os_error != WSA_IO_PENDING) {
int result = MapSystemError(os_error);
LogRead(result, NULL);
return result;
}
}
core_->WatchForRead();
core_->read_iobuffer_ = buf;
return ERR_IO_PENDING;
}
Commit Message: Map posix error codes in bind better, and fix one windows mapping.
r=wtc
BUG=330233
Review URL: https://codereview.chromium.org/101193008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: png_write_finish_row(png_structp png_ptr)
{
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
/* Start of interlace block in the y direction */
int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
/* Offset to next interlace block in the y direction */
int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
#endif
int ret;
png_debug(1, "in png_write_finish_row");
/* Next row */
png_ptr->row_number++;
/* See if we are done */
if (png_ptr->row_number < png_ptr->num_rows)
return;
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* If interlaced, go to next pass */
if (png_ptr->interlaced)
{
png_ptr->row_number = 0;
if (png_ptr->transformations & PNG_INTERLACE)
{
png_ptr->pass++;
}
else
{
/* Loop until we find a non-zero width or height pass */
do
{
png_ptr->pass++;
if (png_ptr->pass >= 7)
break;
png_ptr->usr_width = (png_ptr->width +
png_pass_inc[png_ptr->pass] - 1 -
png_pass_start[png_ptr->pass]) /
png_pass_inc[png_ptr->pass];
png_ptr->num_rows = (png_ptr->height +
png_pass_yinc[png_ptr->pass] - 1 -
png_pass_ystart[png_ptr->pass]) /
png_pass_yinc[png_ptr->pass];
if (png_ptr->transformations & PNG_INTERLACE)
break;
} while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
}
/* Reset the row above the image for the next pass */
if (png_ptr->pass < 7)
{
if (png_ptr->prev_row != NULL)
png_memset(png_ptr->prev_row, 0,
(png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
png_ptr->usr_bit_depth, png_ptr->width)) + 1);
return;
}
}
#endif
/* If we get here, we've just written the last row, so we need
to flush the compressor */
do
{
/* Tell the compressor we are done */
ret = deflate(&png_ptr->zstream, Z_FINISH);
/* Check for an error */
if (ret == Z_OK)
{
/* Check to see if we need more room */
if (!(png_ptr->zstream.avail_out))
{
png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
}
}
else if (ret != Z_STREAM_END)
{
if (png_ptr->zstream.msg != NULL)
png_error(png_ptr, png_ptr->zstream.msg);
else
png_error(png_ptr, "zlib error");
}
} while (ret != Z_STREAM_END);
/* Write any extra space */
if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
{
png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
png_ptr->zstream.avail_out);
}
deflateReset(&png_ptr->zstream);
png_ptr->zstream.data_type = Z_BINARY;
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119
Target: 1
Example 2:
Code: ProfileSyncService::~ProfileSyncService() {
sync_prefs_.RemoveSyncPrefObserver(this);
Shutdown();
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void V8Proxy::registerExtension(v8::Extension* extension)
{
registerExtensionWithV8(extension);
staticExtensionsList().append(extension);
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void t1_check_unusual_charstring(void)
{
char *p = strstr(t1_line_array, charstringname) + strlen(charstringname);
int i;
/*tex If no number follows |/CharStrings|, let's read the next line. */
if (sscanf(p, "%i", &i) != 1) {
strcpy(t1_buf_array, t1_line_array);
t1_getline();
strcat(t1_buf_array, t1_line_array);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
}
}
Commit Message: writet1 protection against buffer overflow
git-svn-id: svn://tug.org/texlive/trunk/Build/source@48697 c570f23f-e606-0410-a88d-b1316a301751
CWE ID: CWE-119
Target: 1
Example 2:
Code: static __be64 frwr_mkey_mask(void)
{
u64 result;
result = MLX5_MKEY_MASK_LEN |
MLX5_MKEY_MASK_PAGE_SIZE |
MLX5_MKEY_MASK_START_ADDR |
MLX5_MKEY_MASK_EN_RINVAL |
MLX5_MKEY_MASK_KEY |
MLX5_MKEY_MASK_LR |
MLX5_MKEY_MASK_LW |
MLX5_MKEY_MASK_RR |
MLX5_MKEY_MASK_RW |
MLX5_MKEY_MASK_A |
MLX5_MKEY_MASK_SMALL_FENCE |
MLX5_MKEY_MASK_FREE;
return cpu_to_be64(result);
}
Commit Message: IB/mlx5: Fix leaking stack memory to userspace
mlx5_ib_create_qp_resp was never initialized and only the first 4 bytes
were written.
Fixes: 41d902cb7c32 ("RDMA/mlx5: Fix definition of mlx5_ib_create_qp_resp")
Cc: <[email protected]>
Acked-by: Leon Romanovsky <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: spnego_gss_wrap_size_limit(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
OM_uint32 req_output_size,
OM_uint32 *max_input_size)
{
OM_uint32 ret;
ret = gss_wrap_size_limit(minor_status,
context_handle,
conf_req_flag,
qop_req,
req_output_size,
max_input_size);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_METHOD(Phar, getSupportedCompression)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
phar_request_initialize(TSRMLS_C);
if (PHAR_G(has_zlib)) {
add_next_index_stringl(return_value, "GZ", 2, 1);
}
if (PHAR_G(has_bz2)) {
add_next_index_stringl(return_value, "BZIP2", 5, 1);
}
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: void WebRuntimeFeatures::EnableNewRemotePlaybackPipeline(bool enable) {
RuntimeEnabledFeatures::SetNewRemotePlaybackPipelineEnabled(enable);
}
Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag.
The feature has long since been stable (since M64) and doesn't seem
to be a need for this flag.
BUG=788936
Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0
Reviewed-on: https://chromium-review.googlesource.com/c/1324143
Reviewed-by: Mike West <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Dave Tapuska <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607329}
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: R_API RConfigNode* r_config_node_new(const char *name, const char *value) {
RConfigNode *node;
if (STRNULL (name)) {
return NULL;
}
node = R_NEW0 (RConfigNode);
if (!node) {
return NULL;
}
node->name = strdup (name);
node->value = strdup (value? value: "");
node->flags = CN_RW | CN_STR;
node->i_value = r_num_get (NULL, value);
node->options = r_list_new ();
return node;
}
Commit Message: Fix #7698 - UAF in r_config_set when loading a dex
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void* ipc_alloc(int size)
{
void* out;
if(size > PAGE_SIZE)
out = vmalloc(size);
else
out = kmalloc(size, GFP_KERNEL);
return out;
}
Commit Message: ipc,sem: fine grained locking for semtimedop
Introduce finer grained locking for semtimedop, to handle the common case
of a program wanting to manipulate one semaphore from an array with
multiple semaphores.
If the call is a semop manipulating just one semaphore in an array with
multiple semaphores, only take the lock for that semaphore itself.
If the call needs to manipulate multiple semaphores, or another caller is
in a transaction that manipulates multiple semaphores, the sem_array lock
is taken, as well as all the locks for the individual semaphores.
On a 24 CPU system, performance numbers with the semop-multi
test with N threads and N semaphores, look like this:
vanilla Davidlohr's Davidlohr's + Davidlohr's +
threads patches rwlock patches v3 patches
10 610652 726325 1783589 2142206
20 341570 365699 1520453 1977878
30 288102 307037 1498167 2037995
40 290714 305955 1612665 2256484
50 288620 312890 1733453 2650292
60 289987 306043 1649360 2388008
70 291298 306347 1723167 2717486
80 290948 305662 1729545 2763582
90 290996 306680 1736021 2757524
100 292243 306700 1773700 3059159
[[email protected]: do not call sem_lock when bogus sma]
[[email protected]: make refcounter atomic]
Signed-off-by: Rik van Riel <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Acked-by: Davidlohr Bueso <[email protected]>
Cc: Chegu Vinod <[email protected]>
Cc: Jason Low <[email protected]>
Reviewed-by: Michel Lespinasse <[email protected]>
Cc: Peter Hurley <[email protected]>
Cc: Stanislav Kinsbursky <[email protected]>
Tested-by: Emmanuel Benisty <[email protected]>
Tested-by: Sedat Dilek <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189
Target: 1
Example 2:
Code: static pfunc stream_token(struct jv_parser* p, char ch) {
jv_kind k;
jv last;
switch (ch) {
case '[':
if (jv_is_valid(p->next))
return "Expected a separator between values";
p->path = jv_array_append(p->path, jv_number(0)); // push
p->last_seen = JV_LAST_OPEN_ARRAY;
p->stacklen++;
break;
case '{':
if (p->last_seen == JV_LAST_VALUE)
return "Expected a separator between values";
p->path = jv_array_append(p->path, jv_null()); // push
p->last_seen = JV_LAST_OPEN_OBJECT;
p->stacklen++;
break;
case ':':
if (p->stacklen == 0 || jv_get_kind(jv_array_get(jv_copy(p->path), p->stacklen - 1)) == JV_KIND_NUMBER)
return "':' not as part of an object";
if (!jv_is_valid(p->next) || p->last_seen == JV_LAST_NONE)
return "Expected string key before ':'";
if (jv_get_kind(p->next) != JV_KIND_STRING)
return "Object keys must be strings";
if (p->last_seen != JV_LAST_VALUE)
return "':' should follow a key";
p->last_seen = JV_LAST_COLON;
p->path = jv_array_set(p->path, p->stacklen - 1, p->next);
p->next = jv_invalid();
break;
case ',':
if (p->last_seen != JV_LAST_VALUE)
return "Expected value before ','";
if (p->stacklen == 0)
return "',' not as part of an object or array";
last = jv_array_get(jv_copy(p->path), p->stacklen - 1);
k = jv_get_kind(last);
if (k == JV_KIND_NUMBER) {
int idx = jv_number_value(last);
if (jv_is_valid(p->next)) {
p->output = JV_ARRAY(jv_copy(p->path), p->next);
p->next = jv_invalid();
}
p->path = jv_array_set(p->path, p->stacklen - 1, jv_number(idx + 1));
p->last_seen = JV_LAST_COMMA;
} else if (k == JV_KIND_STRING) {
if (jv_is_valid(p->next)) {
p->output = JV_ARRAY(jv_copy(p->path), p->next);
p->next = jv_invalid();
}
p->path = jv_array_set(p->path, p->stacklen - 1, jv_true()); // ready for another name:value pair
p->last_seen = JV_LAST_COMMA;
} else {
assert(k == JV_KIND_NULL);
jv_free(last);
return "Objects must consist of key:value pairs";
}
jv_free(last);
break;
case ']':
if (p->stacklen == 0)
return "Unmatched ']' at the top-level";
if (p->last_seen == JV_LAST_COMMA)
return "Expected another array element";
if (p->last_seen == JV_LAST_OPEN_ARRAY)
assert(!jv_is_valid(p->next));
last = jv_array_get(jv_copy(p->path), p->stacklen - 1);
k = jv_get_kind(last);
jv_free(last);
if (k != JV_KIND_NUMBER)
return "Unmatched ']' in the middle of an object";
if (jv_is_valid(p->next)) {
p->output = JV_ARRAY(jv_copy(p->path), p->next, jv_true());
p->next = jv_invalid();
} else if (p->last_seen != JV_LAST_OPEN_ARRAY) {
p->output = JV_ARRAY(jv_copy(p->path));
}
p->path = jv_array_slice(p->path, 0, --(p->stacklen)); // pop
jv_free(p->next);
p->next = jv_invalid();
if (p->last_seen == JV_LAST_OPEN_ARRAY)
p->output = JV_ARRAY(jv_copy(p->path), jv_array()); // Empty arrays are leaves
if (p->stacklen == 0)
p->last_seen = JV_LAST_NONE;
else
p->last_seen = JV_LAST_VALUE;
break;
case '}':
if (p->stacklen == 0)
return "Unmatched '}' at the top-level";
if (p->last_seen == JV_LAST_COMMA)
return "Expected another key:value pair";
if (p->last_seen == JV_LAST_OPEN_OBJECT)
assert(!jv_is_valid(p->next));
last = jv_array_get(jv_copy(p->path), p->stacklen - 1);
k = jv_get_kind(last);
jv_free(last);
if (k == JV_KIND_NUMBER)
return "Unmatched '}' in the middle of an array";
Commit Message: Heap buffer overflow in tokenadd() (fix #105)
This was an off-by one: the NUL terminator byte was not allocated on
resize. This was triggered by JSON-encoded numbers longer than 256
bytes.
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: status_t OMXNodeInstance::setConfig(
OMX_INDEXTYPE index, const void *params, size_t size) {
Mutex::Autolock autoLock(mLock);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
CLOG_CONFIG(setConfig, "%s(%#x), %zu@%p)", asString(extIndex), index, size, params);
if (isProhibitedIndex_l(index)) {
android_errorWriteLog(0x534e4554, "29422020");
return BAD_INDEX;
}
OMX_ERRORTYPE err = OMX_SetConfig(
mHandle, index, const_cast<void *>(params));
CLOG_IF_ERROR(setConfig, err, "%s(%#x)", asString(extIndex), index);
return StatusFromOMXError(err);
}
Commit Message: IOMX: allow configuration after going to loaded state
This was disallowed recently but we still use it as MediaCodcec.stop
only goes to loaded state, and does not free component.
Bug: 31450460
Change-Id: I72e092e4e55c9f23b1baee3e950d76e84a5ef28d
(cherry picked from commit e03b22839d78c841ce0a1a0a1ee1960932188b0b)
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void readpng2_warning_handler(png_structp png_ptr, png_const_charp msg)
{
fprintf(stderr, "readpng2 libpng warning: %s\n", msg);
fflush(stderr);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: static int brcmf_cfg80211_sched_scan_stop(struct wiphy *wiphy,
struct net_device *ndev, u64 reqid)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(SCAN, "enter\n");
brcmf_pno_stop_sched_scan(ifp, reqid);
if (cfg->int_escan_map)
brcmf_notify_escan_complete(cfg, ifp, true, true);
return 0;
}
Commit Message: brcmfmac: fix possible buffer overflow in brcmf_cfg80211_mgmt_tx()
The lower level nl80211 code in cfg80211 ensures that "len" is between
25 and NL80211_ATTR_FRAME (2304). We subtract DOT11_MGMT_HDR_LEN (24) from
"len" so thats's max of 2280. However, the action_frame->data[] buffer is
only BRCMF_FIL_ACTION_FRAME_SIZE (1800) bytes long so this memcpy() can
overflow.
memcpy(action_frame->data, &buf[DOT11_MGMT_HDR_LEN],
le16_to_cpu(action_frame->len));
Cc: [email protected] # 3.9.x
Fixes: 18e2f61db3b70 ("brcmfmac: P2P action frame tx.")
Reported-by: "freenerguo(郭大兴)" <[email protected]>
Signed-off-by: Arend van Spriel <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
{
#ifdef PNG_USE_LOCAL_ARRAYS
PNG_sCAL;
#endif
char buf[64];
png_size_t total_len;
png_debug(1, "in png_write_sCAL");
buf[0] = (char)unit;
#ifdef _WIN32_WCE
/* sprintf() function is not supported on WindowsCE */
{
wchar_t wc_buf[32];
size_t wc_len;
swprintf(wc_buf, TEXT("%12.12e"), width);
wc_len = wcslen(wc_buf);
WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL,
NULL);
total_len = wc_len + 2;
swprintf(wc_buf, TEXT("%12.12e"), height);
wc_len = wcslen(wc_buf);
WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
NULL, NULL);
total_len += wc_len;
}
#else
png_snprintf(buf + 1, 63, "%12.12e", width);
total_len = 1 + png_strlen(buf + 1) + 1;
png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
total_len += png_strlen(buf + total_len);
#endif
png_debug1(3, "sCAL total length = %u", (unsigned int)total_len);
png_write_chunk(png_ptr, (png_bytep)png_sCAL, (png_bytep)buf, total_len);
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int dns_read_name(unsigned char *buffer, unsigned char *bufend,
unsigned char *name, char *destination, int dest_len,
int *offset)
{
int nb_bytes = 0, n = 0;
int label_len;
unsigned char *reader = name;
char *dest = destination;
while (1) {
/* Name compression is in use */
if ((*reader & 0xc0) == 0xc0) {
/* Must point BEFORE current position */
if ((buffer + reader[1]) > reader)
goto err;
n = dns_read_name(buffer, bufend, buffer + reader[1],
dest, dest_len - nb_bytes, offset);
if (n == 0)
goto err;
}
label_len = *reader;
if (label_len == 0)
goto out;
/* Check if:
* - we won't read outside the buffer
* - there is enough place in the destination
*/
if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
goto err;
/* +1 to take label len + label string */
label_len++;
memcpy(dest, reader, label_len);
dest += label_len;
nb_bytes += label_len;
reader += label_len;
}
out:
/* offset computation:
* parse from <name> until finding either NULL or a pointer "c0xx"
*/
reader = name;
*offset = 0;
while (reader < bufend) {
if ((reader[0] & 0xc0) == 0xc0) {
*offset += 2;
break;
}
else if (*reader == 0) {
*offset += 1;
break;
}
*offset += 1;
++reader;
}
return nb_bytes;
err:
return 0;
}
Commit Message:
CWE ID: CWE-835
Target: 1
Example 2:
Code: void OnWillCreateBrowserContextServices(content::BrowserContext* context) {
OneGoogleBarServiceFactory::GetInstance()->SetTestingFactory(
context, &LocalNTPOneGoogleBarSmokeTest::CreateOneGoogleBarService);
}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <[email protected]>
Reviewed-by: Marc Treib <[email protected]>
Commit-Queue: Chris Pickel <[email protected]>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: alloc_clnt_odstate(struct nfs4_client *clp)
{
struct nfs4_clnt_odstate *co;
co = kmem_cache_zalloc(odstate_slab, GFP_KERNEL);
if (co) {
co->co_client = clp;
atomic_set(&co->co_odcount, 1);
}
return co;
}
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
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GpuCommandBufferStub::OnRegisterTransferBuffer(
base::SharedMemoryHandle transfer_buffer,
size_t size,
int32 id_request,
IPC::Message* reply_message) {
TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnRegisterTransferBuffer");
base::SharedMemory shared_memory(transfer_buffer, false);
if (command_buffer_.get()) {
int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory,
size,
id_request);
GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message,
id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
Commit Message: Sizes going across an IPC should be uint32.
BUG=164946
Review URL: https://chromiumcodereview.appspot.com/11472038
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171944 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: void ewk_frame_core_gone(Evas_Object* ewkFrame)
{
DBG("ewkFrame=%p", ewkFrame);
EWK_FRAME_SD_GET_OR_RETURN(ewkFrame, smartData);
smartData->frame = 0;
}
Commit Message: [EFL] fast/frames/frame-crash-with-page-cache.html is crashing
https://bugs.webkit.org/show_bug.cgi?id=85879
Patch by Mikhail Pozdnyakov <[email protected]> on 2012-05-17
Reviewed by Noam Rosenthal.
Source/WebKit/efl:
_ewk_frame_smart_del() is considering now that the frame can be present in cache.
loader()->detachFromParent() is only applied for the main frame.
loader()->cancelAndClear() is not used anymore.
* ewk/ewk_frame.cpp:
(_ewk_frame_smart_del):
LayoutTests:
* platform/efl/test_expectations.txt: Removed fast/frames/frame-crash-with-page-cache.html.
git-svn-id: svn://svn.chromium.org/blink/trunk@117409 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int getnum (lua_State *L, const char **fmt, int df) {
if (!isdigit(**fmt)) /* no number? */
return df; /* return default value */
else {
int a = 0;
do {
if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0')))
luaL_error(L, "integral size overflow");
a = a*10 + *((*fmt)++) - '0';
} while (isdigit(**fmt));
return a;
}
}
Commit Message: Security: update Lua struct package for security.
During an auditing Apple found that the "struct" Lua package
we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains
a security problem. A bound-checking statement fails because of integer
overflow. The bug exists since we initially integrated this package with
Lua, when scripting was introduced, so every version of Redis with
EVAL/EVALSHA capabilities exposed is affected.
Instead of just fixing the bug, the library was updated to the latest
version shipped by the author.
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: GpuProcessHost::~GpuProcessHost() {
DCHECK(CalledOnValidThread());
SendOutstandingReplies();
if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) {
if (software_rendering_) {
if (++g_gpu_software_crash_count >= kGpuMaxCrashCount) {
gpu_enabled_ = false;
}
} else {
if (++g_gpu_crash_count >= kGpuMaxCrashCount) {
#if !defined(OS_CHROMEOS)
hardware_gpu_enabled_ = false;
GpuDataManagerImpl::GetInstance()->BlacklistCard();
#endif
}
}
}
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
DIED_FIRST_TIME + g_gpu_crash_count,
GPU_PROCESS_LIFETIME_EVENT_MAX);
int exit_code;
base::TerminationStatus status = process_->GetTerminationStatus(&exit_code);
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
status,
base::TERMINATION_STATUS_MAX_ENUM);
if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
exit_code,
content::RESULT_CODE_LAST_CODE);
}
#if defined(OS_WIN)
if (gpu_process_)
CloseHandle(gpu_process_);
#endif
while (!queued_messages_.empty()) {
delete queued_messages_.front();
queued_messages_.pop();
}
if (g_gpu_process_hosts[kind_] == this)
g_gpu_process_hosts[kind_] = NULL;
BrowserThread::PostTask(BrowserThread::UI,
FROM_HERE,
base::Bind(&GpuProcessHostUIShim::Destroy, host_id_));
}
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:
Target: 1
Example 2:
Code: GF_Err segr_Write(GF_Box *s, GF_BitStream *bs)
{
u32 i, k;
FDSessionGroupBox *ptr = (FDSessionGroupBox *) s;
if (!s) return GF_BAD_PARAM;
gf_bs_write_u16(bs, ptr->num_session_groups);
for (i=0; i<ptr->num_session_groups; i++) {
gf_bs_write_u8(bs, ptr->session_groups[i].nb_groups);
for (k=0; k<ptr->session_groups[i].nb_groups; k++) {
gf_bs_write_u32(bs, ptr->session_groups[i].group_ids[k]);
}
gf_bs_write_u16(bs, ptr->session_groups[i].nb_channels);
for (k=0; k<ptr->session_groups[i].nb_channels; k++) {
gf_bs_write_u32(bs, ptr->session_groups[i].channels[k]);
}
}
return GF_OK;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int xmkstemp(char **tmpname, char *dir)
{
char *localtmp;
char *tmpenv;
mode_t old_mode;
int fd, rc;
/* Some use cases must be capable of being moved atomically
* with rename(2), which is the reason why dir is here. */
if (dir != NULL)
tmpenv = dir;
else
tmpenv = getenv("TMPDIR");
if (tmpenv)
rc = asprintf(&localtmp, "%s/%s.XXXXXX", tmpenv,
program_invocation_short_name);
else
rc = asprintf(&localtmp, "%s/%s.XXXXXX", _PATH_TMP,
program_invocation_short_name);
if (rc < 0)
return -1;
old_mode = umask(077);
fd = mkostemp(localtmp, O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC);
umask(old_mode);
if (fd == -1) {
free(localtmp);
localtmp = NULL;
}
*tmpname = localtmp;
return fd;
}
Commit Message: chsh, chfn, vipw: fix filenames collision
The utils when compiled WITHOUT libuser then mkostemp()ing
"/etc/%s.XXXXXX" where the filename prefix is argv[0] basename.
An attacker could repeatedly execute the util with modified argv[0]
and after many many attempts mkostemp() may generate suffix which
makes sense. The result maybe temporary file with name like rc.status
ld.so.preload or krb5.keytab, etc.
Note that distros usually use libuser based ch{sh,fn} or stuff from
shadow-utils.
It's probably very minor security bug.
Addresses: CVE-2015-5224
Signed-off-by: Karel Zak <[email protected]>
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SPL_METHOD(SplFileInfo, getPathInfo)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_class_entry *ce = intern->info_class;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) {
int path_len;
char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC);
if (path) {
char *dpath = estrndup(path, path_len);
path_len = php_dirname(dpath, path_len);
spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC);
efree(dpath);
}
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
Target: 1
Example 2:
Code: AutocompleteResult::const_iterator AutocompleteResult::begin() const {
return matches_.begin();
}
Commit Message: Adds per-provider information to omnibox UMA logs.
Adds a fairly general structure to omnibox logs that can be used to pass information (that's not per-result information) from providers to the UMA logs. Right now it's only used to pass whether the asynchronous pass of a provider has finished, but it will probably be used for other things in the future.
BUG=
TEST=
Review URL: https://chromiumcodereview.appspot.com/10380007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137288 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: rdpsnd_queue_empty(void)
{
return (queue_lo == queue_hi);
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *a)
{
return (tsfb->numlvls > 0) ? jpc_tsfb_synthesize2(tsfb,
jas_seq2d_getref(a, jas_seq2d_xstart(a), jas_seq2d_ystart(a)),
jas_seq2d_xstart(a), jas_seq2d_ystart(a), jas_seq2d_width(a),
jas_seq2d_height(a), jas_seq2d_rowstep(a), tsfb->numlvls - 1) : 0;
}
Commit Message: Fixed an integral type promotion problem by adding a JAS_CAST.
Modified the jpc_tsfb_synthesize function so that it will be a noop for
an empty sequence (in order to avoid dereferencing a null pointer).
CWE ID: CWE-476
Target: 1
Example 2:
Code: void CL_Shutdown(char *finalmsg, qboolean disconnect, qboolean quit)
{
static qboolean recursive = qfalse;
if(!(com_cl_running && com_cl_running->integer))
return;
Com_Printf( "----- Client Shutdown (%s) -----\n", finalmsg );
if ( recursive ) {
Com_Printf( "WARNING: Recursive shutdown\n" );
return;
}
recursive = qtrue;
noGameRestart = quit;
if(disconnect)
CL_Disconnect(qtrue);
CL_ClearMemory(qtrue);
CL_Snd_Shutdown();
Cmd_RemoveCommand ("cmd");
Cmd_RemoveCommand ("configstrings");
Cmd_RemoveCommand ("clientinfo");
Cmd_RemoveCommand ("snd_restart");
Cmd_RemoveCommand ("vid_restart");
Cmd_RemoveCommand ("disconnect");
Cmd_RemoveCommand ("record");
Cmd_RemoveCommand ("demo");
Cmd_RemoveCommand ("cinematic");
Cmd_RemoveCommand ("stoprecord");
Cmd_RemoveCommand ("connect");
Cmd_RemoveCommand ("reconnect");
Cmd_RemoveCommand ("localservers");
Cmd_RemoveCommand ("globalservers");
Cmd_RemoveCommand ("rcon");
Cmd_RemoveCommand ("ping");
Cmd_RemoveCommand ("serverstatus");
Cmd_RemoveCommand ("showip");
Cmd_RemoveCommand ("fs_openedList");
Cmd_RemoveCommand ("fs_referencedList");
Cmd_RemoveCommand ("model");
Cmd_RemoveCommand ("video");
Cmd_RemoveCommand ("stopvideo");
CL_ShutdownInput();
Con_Shutdown();
Cvar_Set( "cl_running", "0" );
recursive = qfalse;
Com_Memset( &cls, 0, sizeof( cls ) );
Key_SetCatcher( 0 );
Com_Printf( "-----------------------\n" );
}
Commit Message: Don't load .pk3s as .dlls, and don't load user config files from .pk3s.
CWE ID: CWE-269
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int start_decoder(vorb *f)
{
uint8 header[6], x,y;
int len,i,j,k, max_submaps = 0;
int longest_floorlist=0;
if (!start_page(f)) return FALSE;
if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
if (f->segments[0] != 30) return error(f, VORBIS_invalid_first_page);
if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
get32(f); // bitrate_maximum
get32(f); // bitrate_nominal
get32(f); // bitrate_minimum
x = get8(f);
{
int log0,log1;
log0 = x & 15;
log1 = x >> 4;
f->blocksize_0 = 1 << log0;
f->blocksize_1 = 1 << log1;
if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
if (log0 > log1) return error(f, VORBIS_invalid_setup);
}
x = get8(f);
if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
if (!start_page(f)) return FALSE;
if (!start_packet(f)) return FALSE;
do {
len = next_segment(f);
skip(f, len);
f->bytes_in_seg = 0;
} while (len);
if (!start_packet(f)) return FALSE;
#ifndef STB_VORBIS_NO_PUSHDATA_API
if (IS_PUSH_MODE(f)) {
if (!is_whole_packet_present(f, TRUE)) {
if (f->error == VORBIS_invalid_stream)
f->error = VORBIS_invalid_setup;
return FALSE;
}
}
#endif
crc32_init(); // always init it, to avoid multithread race conditions
if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
for (i=0; i < 6; ++i) header[i] = get8_packet(f);
if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
f->codebook_count = get_bits(f,8) + 1;
f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
for (i=0; i < f->codebook_count; ++i) {
uint32 *values;
int ordered, sorted_count;
int total=0;
uint8 *lengths;
Codebook *c = f->codebooks+i;
CHECK(f);
x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
x = get_bits(f, 8);
c->dimensions = (get_bits(f, 8)<<8) + x;
x = get_bits(f, 8);
y = get_bits(f, 8);
c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
ordered = get_bits(f,1);
c->sparse = ordered ? 0 : get_bits(f,1);
if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup);
if (c->sparse)
lengths = (uint8 *) setup_temp_malloc(f, c->entries);
else
lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (!lengths) return error(f, VORBIS_outofmem);
if (ordered) {
int current_entry = 0;
int current_length = get_bits(f,5) + 1;
while (current_entry < c->entries) {
int limit = c->entries - current_entry;
int n = get_bits(f, ilog(limit));
if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
memset(lengths + current_entry, current_length, n);
current_entry += n;
++current_length;
}
} else {
for (j=0; j < c->entries; ++j) {
int present = c->sparse ? get_bits(f,1) : 1;
if (present) {
lengths[j] = get_bits(f, 5) + 1;
++total;
if (lengths[j] == 32)
return error(f, VORBIS_invalid_setup);
} else {
lengths[j] = NO_CODE;
}
}
}
if (c->sparse && total >= c->entries >> 2) {
if (c->entries > (int) f->setup_temp_memory_required)
f->setup_temp_memory_required = c->entries;
c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem);
memcpy(c->codeword_lengths, lengths, c->entries);
setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
lengths = c->codeword_lengths;
c->sparse = 0;
}
if (c->sparse) {
sorted_count = total;
} else {
sorted_count = 0;
#ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
for (j=0; j < c->entries; ++j)
if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
++sorted_count;
#endif
}
c->sorted_entries = sorted_count;
values = NULL;
CHECK(f);
if (!c->sparse) {
c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
} else {
unsigned int size;
if (c->sorted_entries) {
c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
if (!c->codewords) return error(f, VORBIS_outofmem);
values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
if (!values) return error(f, VORBIS_outofmem);
}
size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
if (size > f->setup_temp_memory_required)
f->setup_temp_memory_required = size;
}
if (!compute_codewords(c, lengths, c->entries, values)) {
if (c->sparse) setup_temp_free(f, values, 0);
return error(f, VORBIS_invalid_setup);
}
if (c->sorted_entries) {
c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem);
c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
if (c->sorted_values == NULL) return error(f, VORBIS_outofmem);
++c->sorted_values;
c->sorted_values[-1] = -1;
compute_sorted_huffman(c, lengths, values);
}
if (c->sparse) {
setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
setup_temp_free(f, lengths, c->entries);
c->codewords = NULL;
}
compute_accelerated_huffman(c);
CHECK(f);
c->lookup_type = get_bits(f, 4);
if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
if (c->lookup_type > 0) {
uint16 *mults;
c->minimum_value = float32_unpack(get_bits(f, 32));
c->delta_value = float32_unpack(get_bits(f, 32));
c->value_bits = get_bits(f, 4)+1;
c->sequence_p = get_bits(f,1);
if (c->lookup_type == 1) {
c->lookup_values = lookup1_values(c->entries, c->dimensions);
} else {
c->lookup_values = c->entries * c->dimensions;
}
if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup);
mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
if (mults == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < (int) c->lookup_values; ++j) {
int q = get_bits(f, c->value_bits);
if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
mults[j] = q;
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
if (c->lookup_type == 1) {
int len, sparse = c->sparse;
float last=0;
if (sparse) {
if (c->sorted_entries == 0) goto skip;
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
} else
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
len = sparse ? c->sorted_entries : c->entries;
for (j=0; j < len; ++j) {
unsigned int z = sparse ? c->sorted_values[j] : j;
unsigned int div=1;
for (k=0; k < c->dimensions; ++k) {
int off = (z / div) % c->lookup_values;
float val = mults[off];
val = mults[off]*c->delta_value + c->minimum_value + last;
c->multiplicands[j*c->dimensions + k] = val;
if (c->sequence_p)
last = val;
if (k+1 < c->dimensions) {
if (div > UINT_MAX / (unsigned int) c->lookup_values) {
setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
return error(f, VORBIS_invalid_setup);
}
div *= c->lookup_values;
}
}
}
c->lookup_type = 2;
}
else
#endif
{
float last=0;
CHECK(f);
c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
for (j=0; j < (int) c->lookup_values; ++j) {
float val = mults[j] * c->delta_value + c->minimum_value + last;
c->multiplicands[j] = val;
if (c->sequence_p)
last = val;
}
}
#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
skip:;
#endif
setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values);
CHECK(f);
}
CHECK(f);
}
x = get_bits(f, 6) + 1;
for (i=0; i < x; ++i) {
uint32 z = get_bits(f, 16);
if (z != 0) return error(f, VORBIS_invalid_setup);
}
f->floor_count = get_bits(f, 6)+1;
f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
if (f->floor_config == NULL) return error(f, VORBIS_outofmem);
for (i=0; i < f->floor_count; ++i) {
f->floor_types[i] = get_bits(f, 16);
if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
if (f->floor_types[i] == 0) {
Floor0 *g = &f->floor_config[i].floor0;
g->order = get_bits(f,8);
g->rate = get_bits(f,16);
g->bark_map_size = get_bits(f,16);
g->amplitude_bits = get_bits(f,6);
g->amplitude_offset = get_bits(f,8);
g->number_of_books = get_bits(f,4) + 1;
for (j=0; j < g->number_of_books; ++j)
g->book_list[j] = get_bits(f,8);
return error(f, VORBIS_feature_not_supported);
} else {
stbv__floor_ordering p[31*8+2];
Floor1 *g = &f->floor_config[i].floor1;
int max_class = -1;
g->partitions = get_bits(f, 5);
for (j=0; j < g->partitions; ++j) {
g->partition_class_list[j] = get_bits(f, 4);
if (g->partition_class_list[j] > max_class)
max_class = g->partition_class_list[j];
}
for (j=0; j <= max_class; ++j) {
g->class_dimensions[j] = get_bits(f, 3)+1;
g->class_subclasses[j] = get_bits(f, 2);
if (g->class_subclasses[j]) {
g->class_masterbooks[j] = get_bits(f, 8);
if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
g->subclass_books[j][k] = get_bits(f,8)-1;
if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
}
}
g->floor1_multiplier = get_bits(f,2)+1;
g->rangebits = get_bits(f,4);
g->Xlist[0] = 0;
g->Xlist[1] = 1 << g->rangebits;
g->values = 2;
for (j=0; j < g->partitions; ++j) {
int c = g->partition_class_list[j];
for (k=0; k < g->class_dimensions[c]; ++k) {
g->Xlist[g->values] = get_bits(f, g->rangebits);
++g->values;
}
}
for (j=0; j < g->values; ++j) {
p[j].x = g->Xlist[j];
p[j].id = j;
}
qsort(p, g->values, sizeof(p[0]), point_compare);
for (j=0; j < g->values; ++j)
g->sorted_order[j] = (uint8) p[j].id;
for (j=2; j < g->values; ++j) {
int low,hi;
neighbors(g->Xlist, j, &low,&hi);
g->neighbors[j][0] = low;
g->neighbors[j][1] = hi;
}
if (g->values > longest_floorlist)
longest_floorlist = g->values;
}
}
f->residue_count = get_bits(f, 6)+1;
f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0]));
if (f->residue_config == NULL) return error(f, VORBIS_outofmem);
memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));
for (i=0; i < f->residue_count; ++i) {
uint8 residue_cascade[64];
Residue *r = f->residue_config+i;
f->residue_types[i] = get_bits(f, 16);
if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
r->begin = get_bits(f, 24);
r->end = get_bits(f, 24);
if (r->end < r->begin) return error(f, VORBIS_invalid_setup);
r->part_size = get_bits(f,24)+1;
r->classifications = get_bits(f,6)+1;
r->classbook = get_bits(f,8);
if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup);
for (j=0; j < r->classifications; ++j) {
uint8 high_bits=0;
uint8 low_bits=get_bits(f,3);
if (get_bits(f,1))
high_bits = get_bits(f,5);
residue_cascade[j] = high_bits*8 + low_bits;
}
r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
if (r->residue_books == NULL) return error(f, VORBIS_outofmem);
for (j=0; j < r->classifications; ++j) {
for (k=0; k < 8; ++k) {
if (residue_cascade[j] & (1 << k)) {
r->residue_books[j][k] = get_bits(f, 8);
if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
} else {
r->residue_books[j][k] = -1;
}
}
}
r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
if (!r->classdata) return error(f, VORBIS_outofmem);
memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
int classwords = f->codebooks[r->classbook].dimensions;
int temp = j;
r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem);
for (k=classwords-1; k >= 0; --k) {
r->classdata[j][k] = temp % r->classifications;
temp /= r->classifications;
}
}
}
f->mapping_count = get_bits(f,6)+1;
f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
if (f->mapping == NULL) return error(f, VORBIS_outofmem);
memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));
for (i=0; i < f->mapping_count; ++i) {
Mapping *m = f->mapping + i;
int mapping_type = get_bits(f,16);
if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
if (m->chan == NULL) return error(f, VORBIS_outofmem);
if (get_bits(f,1))
m->submaps = get_bits(f,4)+1;
else
m->submaps = 1;
if (m->submaps > max_submaps)
max_submaps = m->submaps;
if (get_bits(f,1)) {
m->coupling_steps = get_bits(f,8)+1;
for (k=0; k < m->coupling_steps; ++k) {
m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));
m->chan[k].angle = get_bits(f, ilog(f->channels-1));
if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
}
} else
m->coupling_steps = 0;
if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
if (m->submaps > 1) {
for (j=0; j < f->channels; ++j) {
m->chan[j].mux = get_bits(f, 4);
if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
}
} else
for (j=0; j < f->channels; ++j)
m->chan[j].mux = 0;
for (j=0; j < m->submaps; ++j) {
get_bits(f,8); // discard
m->submap_floor[j] = get_bits(f,8);
m->submap_residue[j] = get_bits(f,8);
if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
}
}
f->mode_count = get_bits(f, 6)+1;
for (i=0; i < f->mode_count; ++i) {
Mode *m = f->mode_config+i;
m->blockflag = get_bits(f,1);
m->windowtype = get_bits(f,16);
m->transformtype = get_bits(f,16);
m->mapping = get_bits(f,8);
if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
}
flush_packet(f);
f->previous_length = 0;
for (i=0; i < f->channels; ++i) {
f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem);
#ifdef STB_VORBIS_NO_DEFER_FLOOR
f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem);
#endif
}
if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
f->blocksize[0] = f->blocksize_0;
f->blocksize[1] = f->blocksize_1;
#ifdef STB_VORBIS_DIVIDE_TABLE
if (integer_divide_table[1][1]==0)
for (i=0; i < DIVTAB_NUMER; ++i)
for (j=1; j < DIVTAB_DENOM; ++j)
integer_divide_table[i][j] = i / j;
#endif
{
uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
uint32 classify_mem;
int i,max_part_read=0;
for (i=0; i < f->residue_count; ++i) {
Residue *r = f->residue_config + i;
int n_read = r->end - r->begin;
int part_read = n_read / r->part_size;
if (part_read > max_part_read)
max_part_read = part_read;
}
#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
#else
classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
#endif
f->temp_memory_required = classify_mem;
if (imdct_mem > f->temp_memory_required)
f->temp_memory_required = imdct_mem;
}
f->first_decode = TRUE;
if (f->alloc.alloc_buffer) {
assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
return error(f, VORBIS_outofmem);
}
f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
return TRUE;
}
Commit Message: fix unchecked length in stb_vorbis that could crash on corrupt/invalid files
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ScriptPromise Bluetooth::requestDevice(ScriptState* script_state,
const RequestDeviceOptions* options,
ExceptionState& exception_state) {
ExecutionContext* context = ExecutionContext::From(script_state);
#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_MACOSX) && \
!defined(OS_WIN)
context->AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kInfo,
"Web Bluetooth is experimental on this platform. See "
"https://github.com/WebBluetoothCG/web-bluetooth/blob/gh-pages/"
"implementation-status.md"));
#endif
CHECK(context->IsSecureContext());
auto& doc = *To<Document>(context);
auto* frame = doc.GetFrame();
if (!frame) {
return ScriptPromise::Reject(
script_state, V8ThrowException::CreateTypeError(
script_state->GetIsolate(), "Document not active"));
}
if (!LocalFrame::HasTransientUserActivation(frame)) {
return ScriptPromise::RejectWithDOMException(
script_state,
MakeGarbageCollected<DOMException>(
DOMExceptionCode::kSecurityError,
"Must be handling a user gesture to show a permission request."));
}
if (!service_) {
frame->GetInterfaceProvider().GetInterface(mojo::MakeRequest(
&service_, context->GetTaskRunner(TaskType::kMiscPlatformAPI)));
}
auto device_options = mojom::blink::WebBluetoothRequestDeviceOptions::New();
ConvertRequestDeviceOptions(options, device_options, exception_state);
if (exception_state.HadException())
return ScriptPromise();
Platform::Current()->RecordRapporURL("Bluetooth.APIUsage.Origin", doc.Url());
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
service_->RequestDevice(
std::move(device_options),
WTF::Bind(&Bluetooth::RequestDeviceCallback, WrapPersistent(this),
WrapPersistent(resolver)));
return promise;
}
Commit Message: bluetooth: Implement getAvailability()
This change implements the getAvailability() method for
navigator.bluetooth as defined in the specification.
Bug: 707640
Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516
Reviewed-by: Chris Harrelson <[email protected]>
Reviewed-by: Giovanni Ortuño Urquidi <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]>
Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]>
Cr-Commit-Position: refs/heads/master@{#688987}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void Browser::UpdateTargetURL(TabContents* source, int32 page_id,
const GURL& url) {
Browser::UpdateTargetURLHelper(source, page_id, url);
if (!GetStatusBubble())
return;
if (source == GetSelectedTabContents()) {
PrefService* prefs = profile_->GetPrefs();
GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages));
}
}
Commit Message: Implement a bubble that appears at the top of the screen when a tab enters
fullscreen mode via webkitRequestFullScreen(), telling the user how to exit
fullscreen.
This is implemented as an NSView rather than an NSWindow because the floating
chrome that appears in presentation mode should overlap the bubble.
Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac:
the mode in which the UI is hidden, accessible by moving the cursor to the top
of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode.
On Lion, however, fullscreen mode does not imply presentation mode: in
non-presentation fullscreen mode, the chrome is permanently shown. It is
possible to switch between presentation mode and fullscreen mode using the
presentation mode UI control.
When a tab initiates fullscreen mode on Lion, we enter presentation mode if not
in presentation mode already. When the user exits fullscreen mode using Chrome
UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we
return the user to the mode they were in before the tab entered fullscreen.
BUG=14471
TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen.
Need to test the Lion logic somehow, with no Lion trybots.
BUG=96883
Original review http://codereview.chromium.org/7890056/
TBR=thakis
Review URL: http://codereview.chromium.org/7920024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int rdfa_parse_start(rdfacontext* context)
{
int rval = RDFA_PARSE_SUCCESS;
context->wb_allocated = sizeof(char) * READ_BUFFER_SIZE;
context->working_buffer = (char*)malloc(context->wb_allocated + 1);
*context->working_buffer = '\0';
#ifndef LIBRDFA_IN_RAPTOR
context->parser = XML_ParserCreate(NULL);
#endif
context->done = 0;
context->context_stack = rdfa_create_list(32);
rdfa_push_item(context->context_stack, context, RDFALIST_FLAG_CONTEXT);
#ifdef LIBRDFA_IN_RAPTOR
context->sax2 = raptor_new_sax2(context->world, context->locator,
context->context_stack);
#else
#endif
#ifdef LIBRDFA_IN_RAPTOR
raptor_sax2_set_start_element_handler(context->sax2,
raptor_rdfa_start_element);
raptor_sax2_set_end_element_handler(context->sax2,
raptor_rdfa_end_element);
raptor_sax2_set_characters_handler(context->sax2,
raptor_rdfa_character_data);
raptor_sax2_set_namespace_handler(context->sax2,
raptor_rdfa_namespace_handler);
#else
XML_SetUserData(context->parser, context->context_stack);
XML_SetElementHandler(context->parser, start_element, end_element);
XML_SetCharacterDataHandler(context->parser, character_data);
#endif
rdfa_init_context(context);
#ifdef LIBRDFA_IN_RAPTOR
if(1) {
raptor_parser* rdf_parser = (raptor_parser*)context->callback_data;
/* Optionally forbid internal network and file requests in the
* XML parser
*/
raptor_sax2_set_option(context->sax2,
RAPTOR_OPTION_NO_NET, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET));
raptor_sax2_set_option(context->sax2,
RAPTOR_OPTION_NO_FILE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE));
if(rdf_parser->uri_filter)
raptor_sax2_set_uri_filter(context->sax2, rdf_parser->uri_filter,
rdf_parser->uri_filter_user_data);
}
context->base_uri=raptor_new_uri(context->sax2->world, (const unsigned char*)context->base);
raptor_sax2_parse_start(context->sax2, context->base_uri);
#endif
return rval;
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int ccid3_hc_tx_getsockopt(struct sock *sk, const int optname, int len,
u32 __user *optval, int __user *optlen)
{
const struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
struct tfrc_tx_info tfrc;
const void *val;
switch (optname) {
case DCCP_SOCKOPT_CCID_TX_INFO:
if (len < sizeof(tfrc))
return -EINVAL;
tfrc.tfrctx_x = hc->tx_x;
tfrc.tfrctx_x_recv = hc->tx_x_recv;
tfrc.tfrctx_x_calc = hc->tx_x_calc;
tfrc.tfrctx_rtt = hc->tx_rtt;
tfrc.tfrctx_p = hc->tx_p;
tfrc.tfrctx_rto = hc->tx_t_rto;
tfrc.tfrctx_ipi = hc->tx_t_ipi;
len = sizeof(tfrc);
val = &tfrc;
break;
default:
return -ENOPROTOOPT;
}
if (put_user(len, optlen) || copy_to_user(optval, val, len))
return -EFAULT;
return 0;
}
Commit Message: dccp: fix info leak via getsockopt(DCCP_SOCKOPT_CCID_TX_INFO)
The CCID3 code fails to initialize the trailing padding bytes of struct
tfrc_tx_info added for alignment on 64 bit architectures. It that for
potentially leaks four bytes kernel stack via the getsockopt() syscall.
Add an explicit memset(0) before filling the structure to avoid the
info leak.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Gerrit Renker <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: Guchar *getDataPtr() { return data; }
Commit Message:
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool Browser::is_app() const {
return !app_name_.empty();
}
Commit Message: Implement a bubble that appears at the top of the screen when a tab enters
fullscreen mode via webkitRequestFullScreen(), telling the user how to exit
fullscreen.
This is implemented as an NSView rather than an NSWindow because the floating
chrome that appears in presentation mode should overlap the bubble.
Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac:
the mode in which the UI is hidden, accessible by moving the cursor to the top
of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode.
On Lion, however, fullscreen mode does not imply presentation mode: in
non-presentation fullscreen mode, the chrome is permanently shown. It is
possible to switch between presentation mode and fullscreen mode using the
presentation mode UI control.
When a tab initiates fullscreen mode on Lion, we enter presentation mode if not
in presentation mode already. When the user exits fullscreen mode using Chrome
UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we
return the user to the mode they were in before the tab entered fullscreen.
BUG=14471
TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen.
Need to test the Lion logic somehow, with no Lion trybots.
BUG=96883
Original review http://codereview.chromium.org/7890056/
TBR=thakis
Review URL: http://codereview.chromium.org/7920024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
Commit Message: Moved EOF check.
CWE ID: CWE-20
Target: 1
Example 2:
Code: void HTMLFormControlElement::setFormEnctype(const AtomicString& value) {
setAttribute(kFormenctypeAttr, value);
}
Commit Message: autofocus: Fix a crash with an autofocus element in a document without browsing context.
ShouldAutofocus() should check existence of the browsing context.
Otherwise, doc.TopFrameOrigin() returns null.
Before crrev.com/695830, ShouldAutofocus() was called only for
rendered elements. That is to say, the document always had
browsing context.
Bug: 1003228
Change-Id: I2a941c34e9707d44869a6d7585dc7fb9f06e3bf4
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1800902
Commit-Queue: Kent Tamura <[email protected]>
Reviewed-by: Keishi Hattori <[email protected]>
Cr-Commit-Position: refs/heads/master@{#696291}
CWE ID: CWE-704
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RunExternalProtocolDialogWithDelegate(
const GURL& url,
int render_process_host_id,
int routing_id,
ui::PageTransition page_transition,
bool has_user_gesture,
ExternalProtocolHandler::Delegate* delegate) {
if (delegate) {
delegate->RunExternalProtocolDialog(url, render_process_host_id, routing_id,
page_transition, has_user_gesture);
return;
}
ExternalProtocolHandler::RunExternalProtocolDialog(
url, render_process_host_id, routing_id, page_transition,
has_user_gesture);
}
Commit Message: Reland "Launching an external protocol handler now escapes the URL."
This is a reland of 2401e58572884b3561e4348d64f11ac74667ef02
Original change's description:
> Launching an external protocol handler now escapes the URL.
>
> Fixes bug introduced in r102449.
>
> Bug: 785809
> Change-Id: I9e6dd1031dd7e7b8d378b138ab151daefdc0c6dc
> Reviewed-on: https://chromium-review.googlesource.com/778747
> Commit-Queue: Matt Giuca <[email protected]>
> Reviewed-by: Eric Lawrence <[email protected]>
> Reviewed-by: Ben Wells <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#518848}
Bug: 785809
Change-Id: Ib8954584004ff5681654398db76d48cdf4437df7
Reviewed-on: https://chromium-review.googlesource.com/788551
Reviewed-by: Ben Wells <[email protected]>
Commit-Queue: Matt Giuca <[email protected]>
Cr-Commit-Position: refs/heads/master@{#519203}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: read_png(FILE *fp)
{
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,0,0,0);
png_infop info_ptr = NULL;
png_bytep row = NULL, display = NULL;
if (png_ptr == NULL)
return 0;
if (setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
if (row != NULL) free(row);
if (display != NULL) free(display);
return 0;
}
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");
png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, NULL, 0);
png_read_info(png_ptr, info_ptr);
{
png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr);
row = malloc(rowbytes);
display = malloc(rowbytes);
if (row == NULL || display == NULL)
png_error(png_ptr, "OOM allocating row buffers");
{
png_uint_32 height = png_get_image_height(png_ptr, info_ptr);
int passes = png_set_interlace_handling(png_ptr);
int pass;
png_start_read_image(png_ptr);
for (pass = 0; pass < passes; ++pass)
{
png_uint_32 y = height;
/* NOTE: this trashes the row each time; interlace handling won't
* work, but this avoids memory thrashing for speed testing.
*/
while (y-- > 0)
png_read_row(png_ptr, row, display);
}
}
}
/* Make sure to read to the end of the file: */
png_read_end(png_ptr, info_ptr);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
free(row);
free(display);
return 1;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: void WebGL2RenderingContextBase::copyBufferSubData(GLenum read_target,
GLenum write_target,
long long read_offset,
long long write_offset,
long long size) {
if (isContextLost())
return;
if (!ValidateValueFitNonNegInt32("copyBufferSubData", "readOffset",
read_offset) ||
!ValidateValueFitNonNegInt32("copyBufferSubData", "writeOffset",
write_offset) ||
!ValidateValueFitNonNegInt32("copyBufferSubData", "size", size)) {
return;
}
WebGLBuffer* read_buffer =
ValidateBufferDataTarget("copyBufferSubData", read_target);
if (!read_buffer)
return;
WebGLBuffer* write_buffer =
ValidateBufferDataTarget("copyBufferSubData", write_target);
if (!write_buffer)
return;
if (read_offset + size > read_buffer->GetSize() ||
write_offset + size > write_buffer->GetSize()) {
SynthesizeGLError(GL_INVALID_VALUE, "copyBufferSubData", "buffer overflow");
return;
}
if ((write_buffer->GetInitialTarget() == GL_ELEMENT_ARRAY_BUFFER &&
read_buffer->GetInitialTarget() != GL_ELEMENT_ARRAY_BUFFER) ||
(write_buffer->GetInitialTarget() != GL_ELEMENT_ARRAY_BUFFER &&
read_buffer->GetInitialTarget() == GL_ELEMENT_ARRAY_BUFFER)) {
SynthesizeGLError(GL_INVALID_OPERATION, "copyBufferSubData",
"Cannot copy into an element buffer destination from a "
"non-element buffer source");
return;
}
if (write_buffer->GetInitialTarget() == 0)
write_buffer->SetInitialTarget(read_buffer->GetInitialTarget());
ContextGL()->CopyBufferSubData(
read_target, write_target, static_cast<GLintptr>(read_offset),
static_cast<GLintptr>(write_offset), static_cast<GLsizeiptr>(size));
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GfxICCBasedCache::put(int numA, int genA,
GfxICCBasedColorSpace *cs)
{
int i;
if (cache[GFX_ICCBASED_CACHE_SIZE-1].num > 0) {
delete cache[GFX_ICCBASED_CACHE_SIZE-1].colorSpace;
}
for (i = GFX_ICCBASED_CACHE_SIZE-1; i > 0; i--) {
if (cache[i - 1].num > 0) cache[i] = cache[i - 1];
}
cache[0].num = numA;
cache[0].gen = genA;
cache[0].colorSpace = (GfxICCBasedColorSpace *)cs->copy();
}
Commit Message:
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool InputMethodController::FinishComposingText(
ConfirmCompositionBehavior confirm_behavior) {
if (!HasComposition())
return false;
const bool is_too_long = IsTextTooLongAt(composition_range_->StartPosition());
const String& composing = ComposingText();
if (confirm_behavior == kKeepSelection) {
const bool is_handle_visible = GetFrame().Selection().IsHandleVisible();
const PlainTextRange& old_offsets = GetSelectionOffsets();
Editor::RevealSelectionScope reveal_selection_scope(&GetEditor());
if (is_too_long) {
ReplaceComposition(ComposingText());
} else {
Clear();
DispatchCompositionEndEvent(GetFrame(), composing);
}
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets();
const EphemeralRange& old_selection_range =
EphemeralRangeForOffsets(old_offsets);
if (old_selection_range.IsNull())
return false;
const SelectionInDOMTree& selection =
SelectionInDOMTree::Builder()
.SetBaseAndExtent(old_selection_range)
.SetIsHandleVisible(is_handle_visible)
.Build();
GetFrame().Selection().SetSelection(
selection,
SetSelectionData::Builder().SetShouldCloseTyping(true).Build());
return true;
}
Element* root_editable_element =
GetFrame()
.Selection()
.ComputeVisibleSelectionInDOMTreeDeprecated()
.RootEditableElement();
if (!root_editable_element)
return false;
PlainTextRange composition_range =
PlainTextRange::Create(*root_editable_element, *composition_range_);
if (composition_range.IsNull())
return false;
if (is_too_long) {
ReplaceComposition(ComposingText());
} else {
Clear();
}
if (!MoveCaret(composition_range.End()))
return false;
DispatchCompositionEndEvent(GetFrame(), composing);
return true;
}
Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection
This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate|
since handle visibility is used only for setting |FrameSelection|, hence it is
a redundant member variable of |SelectionTemplate|.
Bug: 742093
Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e
Reviewed-on: https://chromium-review.googlesource.com/595389
Commit-Queue: Yoshifumi Inoue <[email protected]>
Reviewed-by: Xiaocheng Hu <[email protected]>
Reviewed-by: Kent Tamura <[email protected]>
Cr-Commit-Position: refs/heads/master@{#491660}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static vpx_codec_err_t update_error_state(vpx_codec_alg_priv_t *ctx,
const struct vpx_internal_error_info *error) {
if (error->error_code)
set_error_detail(ctx, error->has_detail ? error->detail : NULL);
return error->error_code;
}
Commit Message: DO NOT MERGE | libvpx: cherry-pick aa1c813 from upstream
Description from upstream:
vp9: Fix potential SEGV in decoder_peek_si_internal
decoder_peek_si_internal could potentially read more bytes than
what actually exists in the input buffer. We check for the buffer
size to be at least 8, but we try to read up to 10 bytes in the
worst case. A well crafted file could thus cause a segfault.
Likely change that introduced this bug was:
https://chromium-review.googlesource.com/#/c/70439 (git hash:
7c43fb6)
Bug: 30013856
Change-Id: If556414cb5b82472d5673e045bc185cc57bb9af3
(cherry picked from commit bd57d587c2eb743c61b049add18f9fd72bf78c33)
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: on_bus_acquired(GDBusConnection *connection,
const gchar *name,
__attribute__((unused)) gpointer user_data)
{
global_connection = connection;
gchar *path;
element e;
GError *local_error = NULL;
log_message(LOG_INFO, "Acquired DBus bus %s", name);
/* register VRRP object */
path = dbus_object_create_path_vrrp();
guint vrrp = g_dbus_connection_register_object(connection, path,
vrrp_introspection_data->interfaces[0],
&interface_vtable, NULL, NULL, &local_error);
g_hash_table_insert(objects, "__Vrrp__", GUINT_TO_POINTER(vrrp));
g_free(path);
if (local_error != NULL) {
log_message(LOG_INFO, "Registering VRRP object on %s failed: %s",
path, local_error->message);
g_clear_error(&local_error);
}
/* for each available VRRP instance, register an object */
if (LIST_ISEMPTY(vrrp_data->vrrp))
return;
for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) {
vrrp_t * vrrp = ELEMENT_DATA(e);
dbus_create_object(vrrp);
}
/* Send a signal to say we have started */
path = dbus_object_create_path_vrrp();
dbus_emit_signal(global_connection, path, DBUS_VRRP_INTERFACE, "VrrpStarted", NULL);
g_free(path);
/* Notify DBus of the state of our instances */
for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) {
vrrp_t * vrrp = ELEMENT_DATA(e);
dbus_send_state_signal(vrrp);
}
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int asn1_ber_decoder(const struct asn1_decoder *decoder,
void *context,
const unsigned char *data,
size_t datalen)
{
const unsigned char *machine = decoder->machine;
const asn1_action_t *actions = decoder->actions;
size_t machlen = decoder->machlen;
enum asn1_opcode op;
unsigned char tag = 0, csp = 0, jsp = 0, optag = 0, hdr = 0;
const char *errmsg;
size_t pc = 0, dp = 0, tdp = 0, len = 0;
int ret;
unsigned char flags = 0;
#define FLAG_INDEFINITE_LENGTH 0x01
#define FLAG_MATCHED 0x02
#define FLAG_LAST_MATCHED 0x04 /* Last tag matched */
#define FLAG_CONS 0x20 /* Corresponds to CONS bit in the opcode tag
* - ie. whether or not we are going to parse
* a compound type.
*/
#define NR_CONS_STACK 10
unsigned short cons_dp_stack[NR_CONS_STACK];
unsigned short cons_datalen_stack[NR_CONS_STACK];
unsigned char cons_hdrlen_stack[NR_CONS_STACK];
#define NR_JUMP_STACK 10
unsigned char jump_stack[NR_JUMP_STACK];
if (datalen > 65535)
return -EMSGSIZE;
next_op:
pr_debug("next_op: pc=\e[32m%zu\e[m/%zu dp=\e[33m%zu\e[m/%zu C=%d J=%d\n",
pc, machlen, dp, datalen, csp, jsp);
if (unlikely(pc >= machlen))
goto machine_overrun_error;
op = machine[pc];
if (unlikely(pc + asn1_op_lengths[op] > machlen))
goto machine_overrun_error;
/* If this command is meant to match a tag, then do that before
* evaluating the command.
*/
if (op <= ASN1_OP__MATCHES_TAG) {
unsigned char tmp;
/* Skip conditional matches if possible */
if ((op & ASN1_OP_MATCH__COND &&
flags & FLAG_MATCHED) ||
dp == datalen) {
flags &= ~FLAG_LAST_MATCHED;
pc += asn1_op_lengths[op];
goto next_op;
}
flags = 0;
hdr = 2;
/* Extract a tag from the data */
if (unlikely(dp >= datalen - 1))
goto data_overrun_error;
tag = data[dp++];
if (unlikely((tag & 0x1f) == ASN1_LONG_TAG))
goto long_tag_not_supported;
if (op & ASN1_OP_MATCH__ANY) {
pr_debug("- any %02x\n", tag);
} else {
/* Extract the tag from the machine
* - Either CONS or PRIM are permitted in the data if
* CONS is not set in the op stream, otherwise CONS
* is mandatory.
*/
optag = machine[pc + 1];
flags |= optag & FLAG_CONS;
/* Determine whether the tag matched */
tmp = optag ^ tag;
tmp &= ~(optag & ASN1_CONS_BIT);
pr_debug("- match? %02x %02x %02x\n", tag, optag, tmp);
if (tmp != 0) {
/* All odd-numbered tags are MATCH_OR_SKIP. */
if (op & ASN1_OP_MATCH__SKIP) {
pc += asn1_op_lengths[op];
dp--;
goto next_op;
}
goto tag_mismatch;
}
}
flags |= FLAG_MATCHED;
len = data[dp++];
if (len > 0x7f) {
if (unlikely(len == ASN1_INDEFINITE_LENGTH)) {
/* Indefinite length */
if (unlikely(!(tag & ASN1_CONS_BIT)))
goto indefinite_len_primitive;
flags |= FLAG_INDEFINITE_LENGTH;
if (unlikely(2 > datalen - dp))
goto data_overrun_error;
} else {
int n = len - 0x80;
if (unlikely(n > 2))
goto length_too_long;
if (unlikely(dp >= datalen - n))
goto data_overrun_error;
hdr += n;
for (len = 0; n > 0; n--) {
len <<= 8;
len |= data[dp++];
}
if (unlikely(len > datalen - dp))
goto data_overrun_error;
}
}
if (flags & FLAG_CONS) {
/* For expected compound forms, we stack the positions
* of the start and end of the data.
*/
if (unlikely(csp >= NR_CONS_STACK))
goto cons_stack_overflow;
cons_dp_stack[csp] = dp;
cons_hdrlen_stack[csp] = hdr;
if (!(flags & FLAG_INDEFINITE_LENGTH)) {
cons_datalen_stack[csp] = datalen;
datalen = dp + len;
} else {
cons_datalen_stack[csp] = 0;
}
csp++;
}
pr_debug("- TAG: %02x %zu%s\n",
tag, len, flags & FLAG_CONS ? " CONS" : "");
tdp = dp;
}
/* Decide how to handle the operation */
switch (op) {
case ASN1_OP_MATCH_ANY_ACT:
case ASN1_OP_COND_MATCH_ANY_ACT:
ret = actions[machine[pc + 1]](context, hdr, tag, data + dp, len);
if (ret < 0)
return ret;
goto skip_data;
case ASN1_OP_MATCH_ACT:
case ASN1_OP_MATCH_ACT_OR_SKIP:
case ASN1_OP_COND_MATCH_ACT_OR_SKIP:
ret = actions[machine[pc + 2]](context, hdr, tag, data + dp, len);
if (ret < 0)
return ret;
goto skip_data;
case ASN1_OP_MATCH:
case ASN1_OP_MATCH_OR_SKIP:
case ASN1_OP_MATCH_ANY:
case ASN1_OP_COND_MATCH_OR_SKIP:
case ASN1_OP_COND_MATCH_ANY:
skip_data:
if (!(flags & FLAG_CONS)) {
if (flags & FLAG_INDEFINITE_LENGTH) {
ret = asn1_find_indefinite_length(
data, datalen, &dp, &len, &errmsg);
if (ret < 0)
goto error;
} else {
dp += len;
}
pr_debug("- LEAF: %zu\n", len);
}
pc += asn1_op_lengths[op];
goto next_op;
case ASN1_OP_MATCH_JUMP:
case ASN1_OP_MATCH_JUMP_OR_SKIP:
case ASN1_OP_COND_MATCH_JUMP_OR_SKIP:
pr_debug("- MATCH_JUMP\n");
if (unlikely(jsp == NR_JUMP_STACK))
goto jump_stack_overflow;
jump_stack[jsp++] = pc + asn1_op_lengths[op];
pc = machine[pc + 2];
goto next_op;
case ASN1_OP_COND_FAIL:
if (unlikely(!(flags & FLAG_MATCHED)))
goto tag_mismatch;
pc += asn1_op_lengths[op];
goto next_op;
case ASN1_OP_COMPLETE:
if (unlikely(jsp != 0 || csp != 0)) {
pr_err("ASN.1 decoder error: Stacks not empty at completion (%u, %u)\n",
jsp, csp);
return -EBADMSG;
}
return 0;
case ASN1_OP_END_SET:
case ASN1_OP_END_SET_ACT:
if (unlikely(!(flags & FLAG_MATCHED)))
goto tag_mismatch;
case ASN1_OP_END_SEQ:
case ASN1_OP_END_SET_OF:
case ASN1_OP_END_SEQ_OF:
case ASN1_OP_END_SEQ_ACT:
case ASN1_OP_END_SET_OF_ACT:
case ASN1_OP_END_SEQ_OF_ACT:
if (unlikely(csp <= 0))
goto cons_stack_underflow;
csp--;
tdp = cons_dp_stack[csp];
hdr = cons_hdrlen_stack[csp];
len = datalen;
datalen = cons_datalen_stack[csp];
pr_debug("- end cons t=%zu dp=%zu l=%zu/%zu\n",
tdp, dp, len, datalen);
if (datalen == 0) {
/* Indefinite length - check for the EOC. */
datalen = len;
if (unlikely(datalen - dp < 2))
goto data_overrun_error;
if (data[dp++] != 0) {
if (op & ASN1_OP_END__OF) {
dp--;
csp++;
pc = machine[pc + 1];
pr_debug("- continue\n");
goto next_op;
}
goto missing_eoc;
}
if (data[dp++] != 0)
goto invalid_eoc;
len = dp - tdp - 2;
} else {
if (dp < len && (op & ASN1_OP_END__OF)) {
datalen = len;
csp++;
pc = machine[pc + 1];
pr_debug("- continue\n");
goto next_op;
}
if (dp != len)
goto cons_length_error;
len -= tdp;
pr_debug("- cons len l=%zu d=%zu\n", len, dp - tdp);
}
if (op & ASN1_OP_END__ACT) {
unsigned char act;
if (op & ASN1_OP_END__OF)
act = machine[pc + 2];
else
act = machine[pc + 1];
ret = actions[act](context, hdr, 0, data + tdp, len);
}
pc += asn1_op_lengths[op];
goto next_op;
case ASN1_OP_MAYBE_ACT:
if (!(flags & FLAG_LAST_MATCHED)) {
pc += asn1_op_lengths[op];
goto next_op;
}
case ASN1_OP_ACT:
ret = actions[machine[pc + 1]](context, hdr, tag, data + tdp, len);
if (ret < 0)
return ret;
pc += asn1_op_lengths[op];
goto next_op;
case ASN1_OP_RETURN:
if (unlikely(jsp <= 0))
goto jump_stack_underflow;
pc = jump_stack[--jsp];
flags |= FLAG_MATCHED | FLAG_LAST_MATCHED;
goto next_op;
default:
break;
}
/* Shouldn't reach here */
pr_err("ASN.1 decoder error: Found reserved opcode (%u) pc=%zu\n",
op, pc);
return -EBADMSG;
data_overrun_error:
errmsg = "Data overrun error";
goto error;
machine_overrun_error:
errmsg = "Machine overrun error";
goto error;
jump_stack_underflow:
errmsg = "Jump stack underflow";
goto error;
jump_stack_overflow:
errmsg = "Jump stack overflow";
goto error;
cons_stack_underflow:
errmsg = "Cons stack underflow";
goto error;
cons_stack_overflow:
errmsg = "Cons stack overflow";
goto error;
cons_length_error:
errmsg = "Cons length error";
goto error;
missing_eoc:
errmsg = "Missing EOC in indefinite len cons";
goto error;
invalid_eoc:
errmsg = "Invalid length EOC";
goto error;
length_too_long:
errmsg = "Unsupported length";
goto error;
indefinite_len_primitive:
errmsg = "Indefinite len primitive not permitted";
goto error;
tag_mismatch:
errmsg = "Unexpected tag";
goto error;
long_tag_not_supported:
errmsg = "Long tag not supported";
error:
pr_debug("\nASN1: %s [m=%zu d=%zu ot=%02x t=%02x l=%zu]\n",
errmsg, pc, dp, optag, tag, len);
return -EBADMSG;
}
Commit Message: ASN.1: Fix non-match detection failure on data overrun
If the ASN.1 decoder is asked to parse a sequence of objects, non-optional
matches get skipped if there's no more data to be had rather than a
data-overrun error being reported.
This is due to the code segment that decides whether to skip optional
matches (ie. matches that could get ignored because an element is marked
OPTIONAL in the grammar) due to a lack of data also skips non-optional
elements if the data pointer has reached the end of the buffer.
This can be tested with the data decoder for the new RSA akcipher algorithm
that takes three non-optional integers. Currently, it skips the last
integer if there is insufficient data.
Without the fix, #defining DEBUG in asn1_decoder.c will show something
like:
next_op: pc=0/13 dp=0/270 C=0 J=0
- match? 30 30 00
- TAG: 30 266 CONS
next_op: pc=2/13 dp=4/270 C=1 J=0
- match? 02 02 00
- TAG: 02 257
- LEAF: 257
next_op: pc=5/13 dp=265/270 C=1 J=0
- match? 02 02 00
- TAG: 02 3
- LEAF: 3
next_op: pc=8/13 dp=270/270 C=1 J=0
next_op: pc=11/13 dp=270/270 C=1 J=0
- end cons t=4 dp=270 l=270/270
The next_op line for pc=8/13 should be followed by a match line.
This is not exploitable for X.509 certificates by means of shortening the
message and fixing up the ASN.1 CONS tags because:
(1) The relevant records being built up are cleared before use.
(2) If the message is shortened sufficiently to remove the public key, the
ASN.1 parse of the RSA key will fail quickly due to a lack of data.
(3) Extracted signature data is either turned into MPIs (which cope with a
0 length) or is simpler integers specifying algoritms and suchlike
(which can validly be 0); and
(4) The AKID and SKID extensions are optional and their removal is handled
without risking passing a NULL to asymmetric_key_generate_id().
(5) If the certificate is truncated sufficiently to remove the subject,
issuer or serialNumber then the ASN.1 decoder will fail with a 'Cons
stack underflow' return.
This is not exploitable for PKCS#7 messages by means of removal of elements
from such a message from the tail end of a sequence:
(1) Any shortened X.509 certs embedded in the PKCS#7 message are survivable
as detailed above.
(2) The message digest content isn't used if it shows a NULL pointer,
similarly, the authattrs aren't used if that shows a NULL pointer.
(3) A missing signature results in a NULL MPI - which the MPI routines deal
with.
(4) If data is NULL, it is expected that the message has detached content and
that is handled appropriately.
(5) If the serialNumber is excised, the unconditional action associated
with it will pick up the containing SEQUENCE instead, so no NULL
pointer will be seen here.
If both the issuer and the serialNumber are excised, the ASN.1 decode
will fail with an 'Unexpected tag' return.
In either case, there's no way to get to asymmetric_key_generate_id()
with a NULL pointer.
(6) Other fields are decoded to simple integers. Shortening the message
to omit an algorithm ID field will cause checks on this to fail early
in the verification process.
This can also be tested by snipping objects off of the end of the ASN.1 stream
such that mandatory tags are removed - or even from the end of internal
SEQUENCEs. If any mandatory tag is missing, the error EBADMSG *should* be
produced. Without this patch ERANGE or ENOPKG might be produced or the parse
may apparently succeed, perhaps with ENOKEY or EKEYREJECTED being produced
later, depending on what gets snipped.
Just snipping off the final BIT_STRING or OCTET_STRING from either sample
should be a start since both are mandatory and neither will cause an EBADMSG
without the patches
Reported-by: Marcel Holtmann <[email protected]>
Signed-off-by: David Howells <[email protected]>
Tested-by: Marcel Holtmann <[email protected]>
Reviewed-by: David Woodhouse <[email protected]>
CWE ID: CWE-310
Target: 1
Example 2:
Code: send_response_tail( httpd_conn* hc )
{
char buf[1000];
(void) my_snprintf( buf, sizeof(buf), "\
<HR>\n\
<ADDRESS><A HREF=\"%s\">%s</A></ADDRESS>\n\
</BODY>\n\
</HTML>\n",
SERVER_ADDRESS, EXPOSED_SERVER_SOFTWARE );
add_response( hc, buf );
}
Commit Message: Fix heap buffer overflow in de_dotdot
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int smacker_decode_tree(BitstreamContext *bc, HuffContext *hc,
uint32_t prefix, int length)
{
if (!bitstream_read_bit(bc)) { // Leaf
if(hc->current >= 256){
av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n");
return AVERROR_INVALIDDATA;
}
if(length){
hc->bits[hc->current] = prefix;
hc->lengths[hc->current] = length;
} else {
hc->bits[hc->current] = 0;
hc->lengths[hc->current] = 0;
}
hc->values[hc->current] = bitstream_read(bc, 8);
hc->current++;
if(hc->maxlength < length)
hc->maxlength = length;
return 0;
} else { //Node
int r;
length++;
r = smacker_decode_tree(bc, hc, prefix, length);
if(r)
return r;
return smacker_decode_tree(bc, hc, prefix | (1 << (length - 1)), length);
}
}
Commit Message: smacker: add sanity check for length in smacker_decode_tree()
Signed-off-by: Michael Niedermayer <[email protected]>
Bug-Id: 1098
Cc: [email protected]
Signed-off-by: Sean McGovern <[email protected]>
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int do_new_mount(struct path *path, const char *fstype, int flags,
int mnt_flags, const char *name, void *data)
{
struct file_system_type *type;
struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns;
struct vfsmount *mnt;
int err;
if (!fstype)
return -EINVAL;
type = get_fs_type(fstype);
if (!type)
return -ENODEV;
if (user_ns != &init_user_ns) {
if (!(type->fs_flags & FS_USERNS_MOUNT)) {
put_filesystem(type);
return -EPERM;
}
/* Only in special cases allow devices from mounts
* created outside the initial user namespace.
*/
if (!(type->fs_flags & FS_USERNS_DEV_MOUNT)) {
flags |= MS_NODEV;
mnt_flags |= MNT_NODEV;
}
}
mnt = vfs_kern_mount(type, flags, name, data);
if (!IS_ERR(mnt) && (type->fs_flags & FS_HAS_SUBTYPE) &&
!mnt->mnt_sb->s_subtype)
mnt = fs_set_subtype(mnt, fstype);
put_filesystem(type);
if (IS_ERR(mnt))
return PTR_ERR(mnt);
err = do_add_mount(real_mount(mnt), path, mnt_flags);
if (err)
mntput(mnt);
return err;
}
Commit Message: mnt: Correct permission checks in do_remount
While invesgiating the issue where in "mount --bind -oremount,ro ..."
would result in later "mount --bind -oremount,rw" succeeding even if
the mount started off locked I realized that there are several
additional mount flags that should be locked and are not.
In particular MNT_NOSUID, MNT_NODEV, MNT_NOEXEC, and the atime
flags in addition to MNT_READONLY should all be locked. These
flags are all per superblock, can all be changed with MS_BIND,
and should not be changable if set by a more privileged user.
The following additions to the current logic are added in this patch.
- nosuid may not be clearable by a less privileged user.
- nodev may not be clearable by a less privielged user.
- noexec may not be clearable by a less privileged user.
- atime flags may not be changeable by a less privileged user.
The logic with atime is that always setting atime on access is a
global policy and backup software and auditing software could break if
atime bits are not updated (when they are configured to be updated),
and serious performance degradation could result (DOS attack) if atime
updates happen when they have been explicitly disabled. Therefore an
unprivileged user should not be able to mess with the atime bits set
by a more privileged user.
The additional restrictions are implemented with the addition of
MNT_LOCK_NOSUID, MNT_LOCK_NODEV, MNT_LOCK_NOEXEC, and MNT_LOCK_ATIME
mnt flags.
Taken together these changes and the fixes for MNT_LOCK_READONLY
should make it safe for an unprivileged user to create a user
namespace and to call "mount --bind -o remount,... ..." without
the danger of mount flags being changed maliciously.
Cc: [email protected]
Acked-by: Serge E. Hallyn <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int register_ftrace_profiler(void)
{
return register_ftrace_graph(&profile_graph_return,
&profile_graph_entry);
}
Commit Message: tracing: Fix possible NULL pointer dereferences
Currently set_ftrace_pid and set_graph_function files use seq_lseek
for their fops. However seq_open() is called only for FMODE_READ in
the fops->open() so that if an user tries to seek one of those file
when she open it for writing, it sees NULL seq_file and then panic.
It can be easily reproduced with following command:
$ cd /sys/kernel/debug/tracing
$ echo 1234 | sudo tee -a set_ftrace_pid
In this example, GNU coreutils' tee opens the file with fopen(, "a")
and then the fopen() internally calls lseek().
Link: http://lkml.kernel.org/r/[email protected]
Cc: Frederic Weisbecker <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Namhyung Kim <[email protected]>
Cc: [email protected]
Signed-off-by: Namhyung Kim <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int nsv_parse_NSVf_header(AVFormatContext *s)
{
NSVContext *nsv = s->priv_data;
AVIOContext *pb = s->pb;
unsigned int av_unused file_size;
unsigned int size;
int64_t duration;
int strings_size;
int table_entries;
int table_entries_used;
nsv->state = NSV_UNSYNC; /* in case we fail */
size = avio_rl32(pb);
if (size < 28)
return -1;
nsv->NSVf_end = size;
file_size = (uint32_t)avio_rl32(pb);
av_log(s, AV_LOG_TRACE, "NSV NSVf chunk_size %u\n", size);
av_log(s, AV_LOG_TRACE, "NSV NSVf file_size %u\n", file_size);
nsv->duration = duration = avio_rl32(pb); /* in ms */
av_log(s, AV_LOG_TRACE, "NSV NSVf duration %"PRId64" ms\n", duration);
strings_size = avio_rl32(pb);
table_entries = avio_rl32(pb);
table_entries_used = avio_rl32(pb);
av_log(s, AV_LOG_TRACE, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n",
strings_size, table_entries, table_entries_used);
if (avio_feof(pb))
return -1;
av_log(s, AV_LOG_TRACE, "NSV got header; filepos %"PRId64"\n", avio_tell(pb));
if (strings_size > 0) {
char *strings; /* last byte will be '\0' to play safe with str*() */
char *p, *endp;
char *token, *value;
char quote;
p = strings = av_mallocz((size_t)strings_size + 1);
if (!p)
return AVERROR(ENOMEM);
endp = strings + strings_size;
avio_read(pb, strings, strings_size);
while (p < endp) {
while (*p == ' ')
p++; /* strip out spaces */
if (p >= endp-2)
break;
token = p;
p = strchr(p, '=');
if (!p || p >= endp-2)
break;
*p++ = '\0';
quote = *p++;
value = p;
p = strchr(p, quote);
if (!p || p >= endp)
break;
*p++ = '\0';
av_log(s, AV_LOG_TRACE, "NSV NSVf INFO: %s='%s'\n", token, value);
av_dict_set(&s->metadata, token, value, 0);
}
av_free(strings);
}
if (avio_feof(pb))
return -1;
av_log(s, AV_LOG_TRACE, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb));
if (table_entries_used > 0) {
int i;
nsv->index_entries = table_entries_used;
if((unsigned)table_entries_used >= UINT_MAX / sizeof(uint32_t))
return -1;
nsv->nsvs_file_offset = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t));
if (!nsv->nsvs_file_offset)
return AVERROR(ENOMEM);
for(i=0;i<table_entries_used;i++)
nsv->nsvs_file_offset[i] = avio_rl32(pb) + size;
if(table_entries > table_entries_used &&
avio_rl32(pb) == MKTAG('T','O','C','2')) {
nsv->nsvs_timestamps = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t));
if (!nsv->nsvs_timestamps)
return AVERROR(ENOMEM);
for(i=0;i<table_entries_used;i++) {
nsv->nsvs_timestamps[i] = avio_rl32(pb);
}
}
}
av_log(s, AV_LOG_TRACE, "NSV got index; filepos %"PRId64"\n", avio_tell(pb));
avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */
if (avio_feof(pb))
return -1;
nsv->state = NSV_HAS_READ_NSVF;
return 0;
}
Commit Message: avformat/nsvdec: Fix DoS due to lack of eof check in nsvs_file_offset loop.
Fixes: 20170829.nsv
Co-Author: 张洪亮(望初)" <[email protected]>
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-834
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderSVGImage::paint(PaintInfo& paintInfo, const LayoutPoint&)
{
ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
if (paintInfo.context->paintingDisabled() || style()->visibility() == HIDDEN || !m_imageResource->hasImage())
return;
FloatRect boundingBox = repaintRectInLocalCoordinates();
if (!SVGRenderSupport::paintInfoIntersectsRepaintRect(boundingBox, m_localTransform, paintInfo))
return;
PaintInfo childPaintInfo(paintInfo);
bool drawsOutline = style()->outlineWidth() && (childPaintInfo.phase == PaintPhaseOutline || childPaintInfo.phase == PaintPhaseSelfOutline);
if (drawsOutline || childPaintInfo.phase == PaintPhaseForeground) {
GraphicsContextStateSaver stateSaver(*childPaintInfo.context);
childPaintInfo.applyTransform(m_localTransform);
if (childPaintInfo.phase == PaintPhaseForeground) {
SVGRenderingContext renderingContext(this, childPaintInfo);
if (renderingContext.isRenderingPrepared()) {
if (style()->svgStyle()->bufferedRendering() == BR_STATIC && renderingContext.bufferForeground(m_bufferedForeground))
return;
paintForeground(childPaintInfo);
}
}
if (drawsOutline)
paintOutline(childPaintInfo, IntRect(boundingBox));
}
}
Commit Message: Avoid drawing SVG image content when the image is of zero size.
R=pdr
BUG=330420
Review URL: https://codereview.chromium.org/109753004
git-svn-id: svn://svn.chromium.org/blink/trunk@164536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void plugin_instance_invalidate(PluginInstance *plugin)
{
destroy_window(plugin);
/* NPP instance is no longer valid beyond this point. Drop the link
to the PluginInstance now so that future RPC with this
PluginInstance will actually emit a NULL instance, which the
other side will deal as a no-op for all functions but
NPN_GetValue().
However, don't free() the NPP instance yet as it could be used
later, e.g. in some NPObject::Invalidate()... Note: this also
means we forbid that function to call into the browser in an NPP
instance. */
if (plugin->instance_id) {
id_remove(plugin->instance_id);
plugin->instance_id = 0;
}
}
Commit Message: Support all the new variables added
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int mac80211_hwsim_config(struct ieee80211_hw *hw, u32 changed)
{
struct mac80211_hwsim_data *data = hw->priv;
struct ieee80211_conf *conf = &hw->conf;
static const char *smps_modes[IEEE80211_SMPS_NUM_MODES] = {
[IEEE80211_SMPS_AUTOMATIC] = "auto",
[IEEE80211_SMPS_OFF] = "off",
[IEEE80211_SMPS_STATIC] = "static",
[IEEE80211_SMPS_DYNAMIC] = "dynamic",
};
int idx;
if (conf->chandef.chan)
wiphy_dbg(hw->wiphy,
"%s (freq=%d(%d - %d)/%s idle=%d ps=%d smps=%s)\n",
__func__,
conf->chandef.chan->center_freq,
conf->chandef.center_freq1,
conf->chandef.center_freq2,
hwsim_chanwidths[conf->chandef.width],
!!(conf->flags & IEEE80211_CONF_IDLE),
!!(conf->flags & IEEE80211_CONF_PS),
smps_modes[conf->smps_mode]);
else
wiphy_dbg(hw->wiphy,
"%s (freq=0 idle=%d ps=%d smps=%s)\n",
__func__,
!!(conf->flags & IEEE80211_CONF_IDLE),
!!(conf->flags & IEEE80211_CONF_PS),
smps_modes[conf->smps_mode]);
data->idle = !!(conf->flags & IEEE80211_CONF_IDLE);
WARN_ON(conf->chandef.chan && data->use_chanctx);
mutex_lock(&data->mutex);
if (data->scanning && conf->chandef.chan) {
for (idx = 0; idx < ARRAY_SIZE(data->survey_data); idx++) {
if (data->survey_data[idx].channel == data->channel) {
data->survey_data[idx].start =
data->survey_data[idx].next_start;
data->survey_data[idx].end = jiffies;
break;
}
}
data->channel = conf->chandef.chan;
for (idx = 0; idx < ARRAY_SIZE(data->survey_data); idx++) {
if (data->survey_data[idx].channel &&
data->survey_data[idx].channel != data->channel)
continue;
data->survey_data[idx].channel = data->channel;
data->survey_data[idx].next_start = jiffies;
break;
}
} else {
data->channel = conf->chandef.chan;
}
mutex_unlock(&data->mutex);
if (!data->started || !data->beacon_int)
tasklet_hrtimer_cancel(&data->beacon_timer);
else if (!hrtimer_is_queued(&data->beacon_timer.timer)) {
u64 tsf = mac80211_hwsim_get_tsf(hw, NULL);
u32 bcn_int = data->beacon_int;
u64 until_tbtt = bcn_int - do_div(tsf, bcn_int);
tasklet_hrtimer_start(&data->beacon_timer,
ns_to_ktime(until_tbtt * 1000),
HRTIMER_MODE_REL);
}
return 0;
}
Commit Message: mac80211_hwsim: fix possible memory leak in hwsim_new_radio_nl()
'hwname' is malloced in hwsim_new_radio_nl() and should be freed
before leaving from the error handling cases, otherwise it will cause
memory leak.
Fixes: ff4dd73dd2b4 ("mac80211_hwsim: check HWSIM_ATTR_RADIO_NAME length")
Signed-off-by: Wei Yongjun <[email protected]>
Reviewed-by: Ben Hutchings <[email protected]>
Signed-off-by: Johannes Berg <[email protected]>
CWE ID: CWE-772
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void mpeg4_encode_gop_header(MpegEncContext *s)
{
int hours, minutes, seconds;
int64_t time;
put_bits(&s->pb, 16, 0);
put_bits(&s->pb, 16, GOP_STARTCODE);
time = s->current_picture_ptr->f->pts;
if (s->reordered_input_picture[1])
time = FFMIN(time, s->reordered_input_picture[1]->f->pts);
time = time * s->avctx->time_base.num;
s->last_time_base = FFUDIV(time, s->avctx->time_base.den);
seconds = FFUDIV(time, s->avctx->time_base.den);
minutes = FFUDIV(seconds, 60); seconds = FFUMOD(seconds, 60);
hours = FFUDIV(minutes, 60); minutes = FFUMOD(minutes, 60);
hours = FFUMOD(hours , 24);
put_bits(&s->pb, 5, hours);
put_bits(&s->pb, 6, minutes);
put_bits(&s->pb, 1, 1);
put_bits(&s->pb, 6, seconds);
put_bits(&s->pb, 1, !!(s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP));
put_bits(&s->pb, 1, 0); // broken link == NO
ff_mpeg4_stuffing(&s->pb);
}
Commit Message: avcodec/mpeg4videoenc: Use 64 bit for times in mpeg4_encode_gop_header()
Fixes truncation
Fixes Assertion n <= 31 && value < (1U << n) failed at libavcodec/put_bits.h:169
Fixes: ffmpeg_crash_2.avi
Found-by: Thuan Pham <[email protected]>, Marcel Böhme, Andrew Santosa and Alexandru RazvanCaciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool Get(int64 metahandle, syncable::IsDelField field) {
return GetField(metahandle, field, false);
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: launch_location_update_from_file (LaunchLocation *location,
NautilusFile *file)
{
nautilus_file_unref (location->file);
g_free (location->uri);
location->file = nautilus_file_ref (file);
location->uri = nautilus_file_get_uri (file);
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int aac_send_raw_srb(struct aac_dev* dev, void __user * arg)
{
struct fib* srbfib;
int status;
struct aac_srb *srbcmd = NULL;
struct user_aac_srb *user_srbcmd = NULL;
struct user_aac_srb __user *user_srb = arg;
struct aac_srb_reply __user *user_reply;
struct aac_srb_reply* reply;
u32 fibsize = 0;
u32 flags = 0;
s32 rcode = 0;
u32 data_dir;
void __user *sg_user[32];
void *sg_list[32];
u32 sg_indx = 0;
u32 byte_count = 0;
u32 actual_fibsize64, actual_fibsize = 0;
int i;
if (dev->in_reset) {
dprintk((KERN_DEBUG"aacraid: send raw srb -EBUSY\n"));
return -EBUSY;
}
if (!capable(CAP_SYS_ADMIN)){
dprintk((KERN_DEBUG"aacraid: No permission to send raw srb\n"));
return -EPERM;
}
/*
* Allocate and initialize a Fib then setup a SRB command
*/
if (!(srbfib = aac_fib_alloc(dev))) {
return -ENOMEM;
}
aac_fib_init(srbfib);
/* raw_srb FIB is not FastResponseCapable */
srbfib->hw_fib_va->header.XferState &= ~cpu_to_le32(FastResponseCapable);
srbcmd = (struct aac_srb*) fib_data(srbfib);
memset(sg_list, 0, sizeof(sg_list)); /* cleanup may take issue */
if(copy_from_user(&fibsize, &user_srb->count,sizeof(u32))){
dprintk((KERN_DEBUG"aacraid: Could not copy data size from user\n"));
rcode = -EFAULT;
goto cleanup;
}
if (fibsize > (dev->max_fib_size - sizeof(struct aac_fibhdr))) {
rcode = -EINVAL;
goto cleanup;
}
user_srbcmd = kmalloc(fibsize, GFP_KERNEL);
if (!user_srbcmd) {
dprintk((KERN_DEBUG"aacraid: Could not make a copy of the srb\n"));
rcode = -ENOMEM;
goto cleanup;
}
if(copy_from_user(user_srbcmd, user_srb,fibsize)){
dprintk((KERN_DEBUG"aacraid: Could not copy srb from user\n"));
rcode = -EFAULT;
goto cleanup;
}
user_reply = arg+fibsize;
flags = user_srbcmd->flags; /* from user in cpu order */
srbcmd->function = cpu_to_le32(SRBF_ExecuteScsi); // Force this
srbcmd->channel = cpu_to_le32(user_srbcmd->channel);
srbcmd->id = cpu_to_le32(user_srbcmd->id);
srbcmd->lun = cpu_to_le32(user_srbcmd->lun);
srbcmd->timeout = cpu_to_le32(user_srbcmd->timeout);
srbcmd->flags = cpu_to_le32(flags);
srbcmd->retry_limit = 0; // Obsolete parameter
srbcmd->cdb_size = cpu_to_le32(user_srbcmd->cdb_size);
memcpy(srbcmd->cdb, user_srbcmd->cdb, sizeof(srbcmd->cdb));
switch (flags & (SRB_DataIn | SRB_DataOut)) {
case SRB_DataOut:
data_dir = DMA_TO_DEVICE;
break;
case (SRB_DataIn | SRB_DataOut):
data_dir = DMA_BIDIRECTIONAL;
break;
case SRB_DataIn:
data_dir = DMA_FROM_DEVICE;
break;
default:
data_dir = DMA_NONE;
}
if (user_srbcmd->sg.count > ARRAY_SIZE(sg_list)) {
dprintk((KERN_DEBUG"aacraid: too many sg entries %d\n",
le32_to_cpu(srbcmd->sg.count)));
rcode = -EINVAL;
goto cleanup;
}
actual_fibsize = sizeof(struct aac_srb) - sizeof(struct sgentry) +
((user_srbcmd->sg.count & 0xff) * sizeof(struct sgentry));
actual_fibsize64 = actual_fibsize + (user_srbcmd->sg.count & 0xff) *
(sizeof(struct sgentry64) - sizeof(struct sgentry));
/* User made a mistake - should not continue */
if ((actual_fibsize != fibsize) && (actual_fibsize64 != fibsize)) {
dprintk((KERN_DEBUG"aacraid: Bad Size specified in "
"Raw SRB command calculated fibsize=%lu;%lu "
"user_srbcmd->sg.count=%d aac_srb=%lu sgentry=%lu;%lu "
"issued fibsize=%d\n",
actual_fibsize, actual_fibsize64, user_srbcmd->sg.count,
sizeof(struct aac_srb), sizeof(struct sgentry),
sizeof(struct sgentry64), fibsize));
rcode = -EINVAL;
goto cleanup;
}
if ((data_dir == DMA_NONE) && user_srbcmd->sg.count) {
dprintk((KERN_DEBUG"aacraid: SG with no direction specified in Raw SRB command\n"));
rcode = -EINVAL;
goto cleanup;
}
byte_count = 0;
if (dev->adapter_info.options & AAC_OPT_SGMAP_HOST64) {
struct user_sgmap64* upsg = (struct user_sgmap64*)&user_srbcmd->sg;
struct sgmap64* psg = (struct sgmap64*)&srbcmd->sg;
/*
* This should also catch if user used the 32 bit sgmap
*/
if (actual_fibsize64 == fibsize) {
actual_fibsize = actual_fibsize64;
for (i = 0; i < upsg->count; i++) {
u64 addr;
void* p;
if (upsg->sg[i].count >
((dev->adapter_info.options &
AAC_OPT_NEW_COMM) ?
(dev->scsi_host_ptr->max_sectors << 9) :
65536)) {
rcode = -EINVAL;
goto cleanup;
}
/* Does this really need to be GFP_DMA? */
p = kmalloc(upsg->sg[i].count,GFP_KERNEL|__GFP_DMA);
if(!p) {
dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n",
upsg->sg[i].count,i,upsg->count));
rcode = -ENOMEM;
goto cleanup;
}
addr = (u64)upsg->sg[i].addr[0];
addr += ((u64)upsg->sg[i].addr[1]) << 32;
sg_user[i] = (void __user *)(uintptr_t)addr;
sg_list[i] = p; // save so we can clean up later
sg_indx = i;
if (flags & SRB_DataOut) {
if(copy_from_user(p,sg_user[i],upsg->sg[i].count)){
dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
addr = pci_map_single(dev->pdev, p, upsg->sg[i].count, data_dir);
psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff);
psg->sg[i].addr[1] = cpu_to_le32(addr>>32);
byte_count += upsg->sg[i].count;
psg->sg[i].count = cpu_to_le32(upsg->sg[i].count);
}
} else {
struct user_sgmap* usg;
usg = kmalloc(actual_fibsize - sizeof(struct aac_srb)
+ sizeof(struct sgmap), GFP_KERNEL);
if (!usg) {
dprintk((KERN_DEBUG"aacraid: Allocation error in Raw SRB command\n"));
rcode = -ENOMEM;
goto cleanup;
}
memcpy (usg, upsg, actual_fibsize - sizeof(struct aac_srb)
+ sizeof(struct sgmap));
actual_fibsize = actual_fibsize64;
for (i = 0; i < usg->count; i++) {
u64 addr;
void* p;
if (usg->sg[i].count >
((dev->adapter_info.options &
AAC_OPT_NEW_COMM) ?
(dev->scsi_host_ptr->max_sectors << 9) :
65536)) {
kfree(usg);
rcode = -EINVAL;
goto cleanup;
}
/* Does this really need to be GFP_DMA? */
p = kmalloc(usg->sg[i].count,GFP_KERNEL|__GFP_DMA);
if(!p) {
dprintk((KERN_DEBUG "aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n",
usg->sg[i].count,i,usg->count));
kfree(usg);
rcode = -ENOMEM;
goto cleanup;
}
sg_user[i] = (void __user *)(uintptr_t)usg->sg[i].addr;
sg_list[i] = p; // save so we can clean up later
sg_indx = i;
if (flags & SRB_DataOut) {
if(copy_from_user(p,sg_user[i],upsg->sg[i].count)){
kfree (usg);
dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
addr = pci_map_single(dev->pdev, p, usg->sg[i].count, data_dir);
psg->sg[i].addr[0] = cpu_to_le32(addr & 0xffffffff);
psg->sg[i].addr[1] = cpu_to_le32(addr>>32);
byte_count += usg->sg[i].count;
psg->sg[i].count = cpu_to_le32(usg->sg[i].count);
}
kfree (usg);
}
srbcmd->count = cpu_to_le32(byte_count);
psg->count = cpu_to_le32(sg_indx+1);
status = aac_fib_send(ScsiPortCommand64, srbfib, actual_fibsize, FsaNormal, 1, 1,NULL,NULL);
} else {
struct user_sgmap* upsg = &user_srbcmd->sg;
struct sgmap* psg = &srbcmd->sg;
if (actual_fibsize64 == fibsize) {
struct user_sgmap64* usg = (struct user_sgmap64 *)upsg;
for (i = 0; i < upsg->count; i++) {
uintptr_t addr;
void* p;
if (usg->sg[i].count >
((dev->adapter_info.options &
AAC_OPT_NEW_COMM) ?
(dev->scsi_host_ptr->max_sectors << 9) :
65536)) {
rcode = -EINVAL;
goto cleanup;
}
/* Does this really need to be GFP_DMA? */
p = kmalloc(usg->sg[i].count,GFP_KERNEL|__GFP_DMA);
if(!p) {
dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n",
usg->sg[i].count,i,usg->count));
rcode = -ENOMEM;
goto cleanup;
}
addr = (u64)usg->sg[i].addr[0];
addr += ((u64)usg->sg[i].addr[1]) << 32;
sg_user[i] = (void __user *)addr;
sg_list[i] = p; // save so we can clean up later
sg_indx = i;
if (flags & SRB_DataOut) {
if(copy_from_user(p,sg_user[i],usg->sg[i].count)){
dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
addr = pci_map_single(dev->pdev, p, usg->sg[i].count, data_dir);
psg->sg[i].addr = cpu_to_le32(addr & 0xffffffff);
byte_count += usg->sg[i].count;
psg->sg[i].count = cpu_to_le32(usg->sg[i].count);
}
} else {
for (i = 0; i < upsg->count; i++) {
dma_addr_t addr;
void* p;
if (upsg->sg[i].count >
((dev->adapter_info.options &
AAC_OPT_NEW_COMM) ?
(dev->scsi_host_ptr->max_sectors << 9) :
65536)) {
rcode = -EINVAL;
goto cleanup;
}
p = kmalloc(upsg->sg[i].count, GFP_KERNEL);
if (!p) {
dprintk((KERN_DEBUG"aacraid: Could not allocate SG buffer - size = %d buffer number %d of %d\n",
upsg->sg[i].count, i, upsg->count));
rcode = -ENOMEM;
goto cleanup;
}
sg_user[i] = (void __user *)(uintptr_t)upsg->sg[i].addr;
sg_list[i] = p; // save so we can clean up later
sg_indx = i;
if (flags & SRB_DataOut) {
if(copy_from_user(p, sg_user[i],
upsg->sg[i].count)) {
dprintk((KERN_DEBUG"aacraid: Could not copy sg data from user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
addr = pci_map_single(dev->pdev, p,
upsg->sg[i].count, data_dir);
psg->sg[i].addr = cpu_to_le32(addr);
byte_count += upsg->sg[i].count;
psg->sg[i].count = cpu_to_le32(upsg->sg[i].count);
}
}
srbcmd->count = cpu_to_le32(byte_count);
psg->count = cpu_to_le32(sg_indx+1);
status = aac_fib_send(ScsiPortCommand, srbfib, actual_fibsize, FsaNormal, 1, 1, NULL, NULL);
}
if (status == -ERESTARTSYS) {
rcode = -ERESTARTSYS;
goto cleanup;
}
if (status != 0){
dprintk((KERN_DEBUG"aacraid: Could not send raw srb fib to hba\n"));
rcode = -ENXIO;
goto cleanup;
}
if (flags & SRB_DataIn) {
for(i = 0 ; i <= sg_indx; i++){
byte_count = le32_to_cpu(
(dev->adapter_info.options & AAC_OPT_SGMAP_HOST64)
? ((struct sgmap64*)&srbcmd->sg)->sg[i].count
: srbcmd->sg.sg[i].count);
if(copy_to_user(sg_user[i], sg_list[i], byte_count)){
dprintk((KERN_DEBUG"aacraid: Could not copy sg data to user\n"));
rcode = -EFAULT;
goto cleanup;
}
}
}
reply = (struct aac_srb_reply *) fib_data(srbfib);
if(copy_to_user(user_reply,reply,sizeof(struct aac_srb_reply))){
dprintk((KERN_DEBUG"aacraid: Could not copy reply to user\n"));
rcode = -EFAULT;
goto cleanup;
}
cleanup:
kfree(user_srbcmd);
for(i=0; i <= sg_indx; i++){
kfree(sg_list[i]);
}
if (rcode != -ERESTARTSYS) {
aac_fib_complete(srbfib);
aac_fib_free(srbfib);
}
return rcode;
}
Commit Message: aacraid: prevent invalid pointer dereference
It appears that driver runs into a problem here if fibsize is too small
because we allocate user_srbcmd with fibsize size only but later we
access it until user_srbcmd->sg.count to copy it over to srbcmd.
It is not correct to test (fibsize < sizeof(*user_srbcmd)) because this
structure already includes one sg element and this is not needed for
commands without data. So, we would recommend to add the following
(instead of test for fibsize == 0).
Signed-off-by: Mahesh Rajashekhara <[email protected]>
Reported-by: Nico Golde <[email protected]>
Reported-by: Fabian Yamaguchi <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void __br_multicast_send_query(struct net_bridge *br,
struct net_bridge_port *port,
struct br_ip *ip)
{
struct sk_buff *skb;
skb = br_multicast_alloc_query(br, ip);
if (!skb)
return;
if (port) {
__skb_push(skb, sizeof(struct ethhdr));
skb->dev = port->dev;
NF_HOOK(NFPROTO_BRIDGE, NF_BR_LOCAL_OUT, skb, NULL, skb->dev,
dev_queue_xmit);
} else
netif_rx(skb);
}
Commit Message: bridge: Fix mglist corruption that leads to memory corruption
The list mp->mglist is used to indicate whether a multicast group
is active on the bridge interface itself as opposed to one of the
constituent interfaces in the bridge.
Unfortunately the operation that adds the mp->mglist node to the
list neglected to check whether it has already been added. This
leads to list corruption in the form of nodes pointing to itself.
Normally this would be quite obvious as it would cause an infinite
loop when walking the list. However, as this list is never actually
walked (which means that we don't really need it, I'll get rid of
it in a subsequent patch), this instead is hidden until we perform
a delete operation on the affected nodes.
As the same node may now be pointed to by more than one node, the
delete operations can then cause modification of freed memory.
This was observed in practice to cause corruption in 512-byte slabs,
most commonly leading to crashes in jbd2.
Thanks to Josef Bacik for pointing me in the right direction.
Reported-by: Ian Page Hands <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void free_http_req_rules(struct list *r)
{
struct act_rule *tr, *pr;
list_for_each_entry_safe(pr, tr, r, list) {
LIST_DEL(&pr->list);
if (pr->action == ACT_HTTP_REQ_AUTH)
free(pr->arg.auth.realm);
regex_free(&pr->arg.hdr_add.re);
free(pr);
}
}
Commit Message:
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: mp_capable_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_capable *mpc = (const struct mp_capable *) opt;
if (!(opt_len == 12 && flags & TH_SYN) &&
!(opt_len == 20 && (flags & (TH_SYN | TH_ACK)) == TH_ACK))
return 0;
if (MP_CAPABLE_OPT_VERSION(mpc->sub_ver) != 0) {
ND_PRINT((ndo, " Unknown Version (%d)", MP_CAPABLE_OPT_VERSION(mpc->sub_ver)));
return 1;
}
if (mpc->flags & MP_CAPABLE_C)
ND_PRINT((ndo, " csum"));
ND_PRINT((ndo, " {0x%" PRIx64, EXTRACT_64BITS(mpc->sender_key)));
if (opt_len == 20) /* ACK */
ND_PRINT((ndo, ",0x%" PRIx64, EXTRACT_64BITS(mpc->receiver_key)));
ND_PRINT((ndo, "}"));
return 1;
}
Commit Message: CVE-2017-13040/MPTCP: Clean up printing DSS suboption.
Do the length checking inline; that means we print stuff up to the point
at which we run out of option data.
First check to make sure we have at least 4 bytes of option, so we have
flags to check.
This fixes a buffer over-read discovered by Kim Gwan Yeong.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void crypto_authenc_esn_exit_tfm(struct crypto_tfm *tfm)
{
struct crypto_authenc_esn_ctx *ctx = crypto_tfm_ctx(tfm);
crypto_free_ahash(ctx->auth);
crypto_free_ablkcipher(ctx->enc);
}
Commit Message: crypto: include crypto- module prefix in template
This adds the module loading prefix "crypto-" to the template lookup
as well.
For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly
includes the "crypto-" prefix at every level, correctly rejecting "vfat":
net-pf-38
algif-hash
crypto-vfat(blowfish)
crypto-vfat(blowfish)-all
crypto-vfat
Reported-by: Mathias Krause <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Acked-by: Mathias Krause <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int nfsd_mountpoint(struct dentry *dentry, struct svc_export *exp)
{
if (d_mountpoint(dentry))
return 1;
if (nfsd4_is_junction(dentry))
return 1;
if (!(exp->ex_flags & NFSEXP_V4ROOT))
return 0;
return d_inode(dentry) != NULL;
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void AddSimpleRectChunk(TestPaintArtifact& artifact) {
artifact
.Chunk(TransformPaintPropertyNode::Root(),
ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root())
.RectDrawing(FloatRect(100, 100, 200, 100), Color::kBlack);
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID:
Target: 1
Example 2:
Code: static struct fib_nh_exception *find_exception(struct fib_nh *nh, __be32 daddr)
{
struct fnhe_hash_bucket *hash = rcu_dereference(nh->nh_exceptions);
struct fib_nh_exception *fnhe;
u32 hval;
if (!hash)
return NULL;
hval = fnhe_hashfun(daddr);
for (fnhe = rcu_dereference(hash[hval].chain); fnhe;
fnhe = rcu_dereference(fnhe->fnhe_next)) {
if (fnhe->fnhe_daddr == daddr)
return fnhe;
}
return NULL;
}
Commit Message: ipv4: try to cache dst_entries which would cause a redirect
Not caching dst_entries which cause redirects could be exploited by hosts
on the same subnet, causing a severe DoS attack. This effect aggravated
since commit f88649721268999 ("ipv4: fix dst race in sk_dst_get()").
Lookups causing redirects will be allocated with DST_NOCACHE set which
will force dst_release to free them via RCU. Unfortunately waiting for
RCU grace period just takes too long, we can end up with >1M dst_entries
waiting to be released and the system will run OOM. rcuos threads cannot
catch up under high softirq load.
Attaching the flag to emit a redirect later on to the specific skb allows
us to cache those dst_entries thus reducing the pressure on allocation
and deallocation.
This issue was discovered by Marcelo Leitner.
Cc: Julian Anastasov <[email protected]>
Signed-off-by: Marcelo Leitner <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: Julian Anastasov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-17
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
{
int port;
char buf[128];
const char *cp, *addr_part, *port_part;
int is_ipv6;
/* recognized formats are:
* [ipv6]:port
* ipv6
* [ipv6]
* ipv4:port
* ipv4
*/
cp = strchr(ip_as_string, ':');
if (*ip_as_string == '[') {
int len;
if (!(cp = strchr(ip_as_string, ']'))) {
return -1;
}
len = (int) ( cp-(ip_as_string + 1) );
if (len > (int)sizeof(buf)-1) {
return -1;
}
memcpy(buf, ip_as_string+1, len);
buf[len] = '\0';
addr_part = buf;
if (cp[1] == ':')
port_part = cp+2;
else
port_part = NULL;
is_ipv6 = 1;
} else if (cp && strchr(cp+1, ':')) {
is_ipv6 = 1;
addr_part = ip_as_string;
port_part = NULL;
} else if (cp) {
is_ipv6 = 0;
if (cp - ip_as_string > (int)sizeof(buf)-1) {
return -1;
}
memcpy(buf, ip_as_string, cp-ip_as_string);
buf[cp-ip_as_string] = '\0';
addr_part = buf;
port_part = cp+1;
} else {
addr_part = ip_as_string;
port_part = NULL;
is_ipv6 = 0;
}
if (port_part == NULL) {
port = 0;
} else {
port = atoi(port_part);
if (port <= 0 || port > 65535) {
return -1;
}
}
if (!addr_part)
return -1; /* Should be impossible. */
#ifdef AF_INET6
if (is_ipv6)
{
struct sockaddr_in6 sin6;
memset(&sin6, 0, sizeof(sin6));
#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
sin6.sin6_len = sizeof(sin6);
#endif
sin6.sin6_family = AF_INET6;
sin6.sin6_port = htons(port);
if (1 != evutil_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr))
return -1;
if ((int)sizeof(sin6) > *outlen)
return -1;
memset(out, 0, *outlen);
memcpy(out, &sin6, sizeof(sin6));
*outlen = sizeof(sin6);
return 0;
}
else
#endif
{
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
sin.sin_len = sizeof(sin);
#endif
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr))
return -1;
if ((int)sizeof(sin) > *outlen)
return -1;
memset(out, 0, *outlen);
memcpy(out, &sin, sizeof(sin));
*outlen = sizeof(sin);
return 0;
}
}
Commit Message: evutil_parse_sockaddr_port(): fix buffer overflow
@asn-the-goblin-slayer:
"Length between '[' and ']' is cast to signed 32 bit integer on line 1815. Is
the length is more than 2<<31 (INT_MAX), len will hold a negative value.
Consequently, it will pass the check at line 1816. Segfault happens at line
1819.
Generate a resolv.conf with generate-resolv.conf, then compile and run
poc.c. See entry-functions.txt for functions in tor that might be
vulnerable.
Please credit 'Guido Vranken' for this discovery through the Tor bug bounty
program."
Reproducer for gdb (https://gist.github.com/azat/be2b0d5e9417ba0dfe2c):
start
p (1ULL<<31)+1ULL
# $1 = 2147483649
p malloc(sizeof(struct sockaddr))
# $2 = (void *) 0x646010
p malloc(sizeof(int))
# $3 = (void *) 0x646030
p malloc($1)
# $4 = (void *) 0x7fff76a2a010
p memset($4, 1, $1)
# $5 = 1990369296
p (char *)$4
# $6 = 0x7fff76a2a010 '\001' <repeats 200 times>...
set $6[0]='['
set $6[$1]=']'
p evutil_parse_sockaddr_port($4, $2, $3)
# $7 = -1
Before:
$ gdb bin/http-connect < gdb
(gdb) $1 = 2147483649
(gdb) (gdb) $2 = (void *) 0x646010
(gdb) (gdb) $3 = (void *) 0x646030
(gdb) (gdb) $4 = (void *) 0x7fff76a2a010
(gdb) (gdb) $5 = 1990369296
(gdb) (gdb) $6 = 0x7fff76a2a010 '\001' <repeats 200 times>...
(gdb) (gdb) (gdb) (gdb)
Program received signal SIGSEGV, Segmentation fault.
__memcpy_sse2_unaligned () at memcpy-sse2-unaligned.S:36
After:
$ gdb bin/http-connect < gdb
(gdb) $1 = 2147483649
(gdb) (gdb) $2 = (void *) 0x646010
(gdb) (gdb) $3 = (void *) 0x646030
(gdb) (gdb) $4 = (void *) 0x7fff76a2a010
(gdb) (gdb) $5 = 1990369296
(gdb) (gdb) $6 = 0x7fff76a2a010 '\001' <repeats 200 times>...
(gdb) (gdb) (gdb) (gdb) $7 = -1
(gdb) (gdb) quit
Fixes: #318
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SPL_METHOD(SplFileObject, hasChildren)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_FALSE;
} /* }}} */
/* {{{ proto bool SplFileObject::getChildren()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
Target: 1
Example 2:
Code: static spl_ptr_heap *spl_ptr_heap_init(spl_ptr_heap_cmp_func cmp, spl_ptr_heap_ctor_func ctor, spl_ptr_heap_dtor_func dtor) /* {{{ */
{
spl_ptr_heap *heap = emalloc(sizeof(spl_ptr_heap));
heap->dtor = dtor;
heap->ctor = ctor;
heap->cmp = cmp;
heap->elements = safe_emalloc(sizeof(spl_ptr_heap_element), PTR_HEAP_BLOCK_SIZE, 0);
heap->max_size = PTR_HEAP_BLOCK_SIZE;
heap->count = 0;
heap->flags = 0;
return heap;
}
/* }}} */
Commit Message:
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PageCaptureCustomBindings::PageCaptureCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("CreateBlob",
base::Bind(&PageCaptureCustomBindings::CreateBlob,
base::Unretained(this)));
RouteFunction("SendResponseAck",
base::Bind(&PageCaptureCustomBindings::SendResponseAck,
base::Unretained(this)));
}
Commit Message: [Extensions] Add more bindings access checks
BUG=598165
Review URL: https://codereview.chromium.org/1854983002
Cr-Commit-Position: refs/heads/master@{#385282}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static av_cold int vqa_decode_init(AVCodecContext *avctx)
{
VqaContext *s = avctx->priv_data;
int i, j, codebook_index;
s->avctx = avctx;
avctx->pix_fmt = PIX_FMT_PAL8;
/* make sure the extradata made it */
if (s->avctx->extradata_size != VQA_HEADER_SIZE) {
av_log(s->avctx, AV_LOG_ERROR, " VQA video: expected extradata size of %d\n", VQA_HEADER_SIZE);
return -1;
}
/* load up the VQA parameters from the header */
s->vqa_version = s->avctx->extradata[0];
s->width = AV_RL16(&s->avctx->extradata[6]);
s->height = AV_RL16(&s->avctx->extradata[8]);
if(av_image_check_size(s->width, s->height, 0, avctx)){
s->width= s->height= 0;
return -1;
}
s->vector_width = s->avctx->extradata[10];
s->vector_height = s->avctx->extradata[11];
s->partial_count = s->partial_countdown = s->avctx->extradata[13];
/* the vector dimensions have to meet very stringent requirements */
if ((s->vector_width != 4) ||
((s->vector_height != 2) && (s->vector_height != 4))) {
/* return without further initialization */
return -1;
}
/* allocate codebooks */
s->codebook_size = MAX_CODEBOOK_SIZE;
s->codebook = av_malloc(s->codebook_size);
/* allocate decode buffer */
s->decode_buffer_size = (s->width / s->vector_width) *
(s->height / s->vector_height) * 2;
s->decode_buffer = av_malloc(s->decode_buffer_size);
if (!s->decode_buffer)
goto fail;
/* initialize the solid-color vectors */
if (s->vector_height == 4) {
codebook_index = 0xFF00 * 16;
for (i = 0; i < 256; i++)
for (j = 0; j < 16; j++)
s->codebook[codebook_index++] = i;
} else {
codebook_index = 0xF00 * 8;
for (i = 0; i < 256; i++)
for (j = 0; j < 8; j++)
s->codebook[codebook_index++] = i;
}
s->next_codebook_buffer_index = 0;
s->frame.data[0] = NULL;
return 0;
fail:
av_freep(&s->codebook);
av_freep(&s->next_codebook_buffer);
av_freep(&s->decode_buffer);
return AVERROR(ENOMEM);
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: void RenderWidgetHostViewGtk::DidUpdateBackingStore(
const gfx::Rect& scroll_rect,
const gfx::Vector2d& scroll_delta,
const std::vector<gfx::Rect>& copy_rects) {
TRACE_EVENT0("ui::gtk", "RenderWidgetHostViewGtk::DidUpdateBackingStore");
if (is_hidden_)
return;
if (about_to_validate_and_paint_)
invalid_rect_.Union(scroll_rect);
else
Paint(scroll_rect);
for (size_t i = 0; i < copy_rects.size(); ++i) {
gfx::Rect rect = gfx::SubtractRects(copy_rects[i], scroll_rect);
if (rect.IsEmpty())
continue;
if (about_to_validate_and_paint_)
invalid_rect_.Union(rect);
else
Paint(rect);
}
}
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:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool omx_vdec::omx_cmd_queue::pop_entry(unsigned long *p1, unsigned long *p2, unsigned long *id)
{
bool ret = true;
if (m_size > 0) {
*id = m_q[m_read].id;
*p1 = m_q[m_read].param1;
*p2 = m_q[m_read].param2;
++m_read;
--m_size;
if (m_read >= OMX_CORE_CONTROL_CMDQ_SIZE) {
m_read = 0;
}
} else {
ret = false;
}
return ret;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27890802
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVdec problem #6)
CRs-Fixed: 1008882
Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: WindowOpenDisposition TestBrowserWindow::GetDispositionForPopupBounds(
const gfx::Rect& bounds) {
return WindowOpenDisposition::NEW_POPUP;
}
Commit Message: Mac: turn popups into new tabs while in fullscreen.
It's platform convention to show popups as new tabs while in
non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.)
This was implemented for Cocoa in a BrowserWindow override, but
it makes sense to just stick it into Browser and remove a ton
of override code put in just to support this.
BUG=858929, 868416
TEST=as in bugs
Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d
Reviewed-on: https://chromium-review.googlesource.com/1153455
Reviewed-by: Sidney San Martín <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#578755}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt)
{
KLVPacket klv;
MXFContext *mxf = s->priv_data;
int ret;
while ((ret = klv_read_packet(&klv, s->pb)) == 0) {
PRINT_KEY(s, "read packet", klv.key);
av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset);
if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) {
ret = mxf_decrypt_triplet(s, pkt, &klv);
if (ret < 0) {
av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n");
return ret;
}
return 0;
}
if (IS_KLV_KEY(klv.key, mxf_essence_element_key) ||
IS_KLV_KEY(klv.key, mxf_canopus_essence_element_key) ||
IS_KLV_KEY(klv.key, mxf_avid_essence_element_key)) {
int index = mxf_get_stream_index(s, &klv);
int64_t next_ofs, next_klv;
AVStream *st;
MXFTrack *track;
AVCodecParameters *par;
if (index < 0) {
av_log(s, AV_LOG_ERROR,
"error getting stream index %"PRIu32"\n",
AV_RB32(klv.key + 12));
goto skip;
}
st = s->streams[index];
track = st->priv_data;
if (s->streams[index]->discard == AVDISCARD_ALL)
goto skip;
next_klv = avio_tell(s->pb) + klv.length;
next_ofs = mxf_set_current_edit_unit(mxf, klv.offset);
if (next_ofs >= 0 && next_klv > next_ofs) {
/* if this check is hit then it's possible OPAtom was treated as OP1a
* truncate the packet since it's probably very large (>2 GiB is common) */
avpriv_request_sample(s,
"OPAtom misinterpreted as OP1a? "
"KLV for edit unit %i extending into "
"next edit unit",
mxf->current_edit_unit);
klv.length = next_ofs - avio_tell(s->pb);
}
/* check for 8 channels AES3 element */
if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) {
ret = mxf_get_d10_aes3_packet(s->pb, s->streams[index],
pkt, klv.length);
if (ret < 0) {
av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n");
return ret;
}
} else {
ret = av_get_packet(s->pb, pkt, klv.length);
if (ret < 0)
return ret;
}
pkt->stream_index = index;
pkt->pos = klv.offset;
par = st->codecpar;
if (par->codec_type == AVMEDIA_TYPE_VIDEO && next_ofs >= 0) {
/* mxf->current_edit_unit good - see if we have an
* index table to derive timestamps from */
MXFIndexTable *t = &mxf->index_tables[0];
if (mxf->nb_index_tables >= 1 && mxf->current_edit_unit < t->nb_ptses) {
pkt->dts = mxf->current_edit_unit + t->first_dts;
pkt->pts = t->ptses[mxf->current_edit_unit];
} else if (track && track->intra_only) {
/* intra-only -> PTS = EditUnit.
* let utils.c figure out DTS since it can be < PTS if low_delay = 0 (Sony IMX30) */
pkt->pts = mxf->current_edit_unit;
}
} else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
ret = mxf_set_audio_pts(mxf, par, pkt);
if (ret < 0)
return ret;
}
/* seek for truncated packets */
avio_seek(s->pb, next_klv, SEEK_SET);
return 0;
} else
skip:
avio_skip(s->pb, klv.length);
}
return avio_feof(s->pb) ? AVERROR_EOF : ret;
}
Commit Message: avformat/mxfdec: Fix DoS issues in mxf_read_index_entry_array()
Fixes: 20170829A.mxf
Co-Author: 张洪亮(望初)" <[email protected]>
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-834
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void HTMLMediaElement::timeChanged() {
BLINK_MEDIA_LOG << "timeChanged(" << (void*)this << ")";
cueTimeline().updateActiveCues(currentTime());
if (m_seeking && m_readyState >= kHaveCurrentData &&
!webMediaPlayer()->seeking())
finishSeek();
scheduleTimeupdateEvent(false);
double now = currentPlaybackPosition();
double dur = duration();
if (!std::isnan(dur) && dur && now >= dur &&
getDirectionOfPlayback() == Forward) {
if (loop()) {
seek(earliestPossiblePosition());
} else {
if (!m_paused) {
m_paused = true;
scheduleEvent(EventTypeNames::pause);
scheduleRejectPlayPromises(AbortError);
}
scheduleEvent(EventTypeNames::ended);
}
}
updatePlayState();
}
Commit Message: [Blink>Media] Allow autoplay muted on Android by default
There was a mistake causing autoplay muted is shipped on Android
but it will be disabled if the chromium embedder doesn't specify
content setting for "AllowAutoplay" preference. This CL makes the
AllowAutoplay preference true by default so that it is allowed by
embedders (including AndroidWebView) unless they explicitly
disable it.
Intent to ship:
https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ
BUG=689018
Review-Url: https://codereview.chromium.org/2677173002
Cr-Commit-Position: refs/heads/master@{#448423}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long keyctl_update_key(key_serial_t id,
const void __user *_payload,
size_t plen)
{
key_ref_t key_ref;
void *payload;
long ret;
ret = -EINVAL;
if (plen > PAGE_SIZE)
goto error;
/* pull the payload in if one was supplied */
payload = NULL;
if (_payload) {
ret = -ENOMEM;
payload = kmalloc(plen, GFP_KERNEL);
if (!payload)
goto error;
ret = -EFAULT;
if (copy_from_user(payload, _payload, plen) != 0)
goto error2;
}
/* find the target key (which must be writable) */
key_ref = lookup_user_key(id, 0, KEY_NEED_WRITE);
if (IS_ERR(key_ref)) {
ret = PTR_ERR(key_ref);
goto error2;
}
/* update the key */
ret = key_update(key_ref, payload, plen);
key_ref_put(key_ref);
error2:
kfree(payload);
error:
return ret;
}
Commit Message: KEYS: fix dereferencing NULL payload with nonzero length
sys_add_key() and the KEYCTL_UPDATE operation of sys_keyctl() allowed a
NULL payload with nonzero length to be passed to the key type's
->preparse(), ->instantiate(), and/or ->update() methods. Various key
types including asymmetric, cifs.idmap, cifs.spnego, and pkcs7_test did
not handle this case, allowing an unprivileged user to trivially cause a
NULL pointer dereference (kernel oops) if one of these key types was
present. Fix it by doing the copy_from_user() when 'plen' is nonzero
rather than when '_payload' is non-NULL, causing the syscall to fail
with EFAULT as expected when an invalid buffer is specified.
Cc: [email protected] # 2.6.10+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: ScopedResolvedFrameBufferBinder::ScopedResolvedFrameBufferBinder(
GLES2DecoderImpl* decoder, bool enforce_internal_framebuffer, bool internal)
: decoder_(decoder) {
resolve_and_bind_ = (decoder_->offscreen_target_frame_buffer_.get() &&
decoder_->IsOffscreenBufferMultisampled() &&
(!decoder_->bound_read_framebuffer_.get() ||
enforce_internal_framebuffer));
if (!resolve_and_bind_)
return;
ScopedGLErrorSuppressor suppressor(decoder_);
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT,
decoder_->offscreen_target_frame_buffer_->id());
GLuint targetid;
if (internal) {
if (!decoder_->offscreen_resolved_frame_buffer_.get()) {
decoder_->offscreen_resolved_frame_buffer_.reset(
new FrameBuffer(decoder_));
decoder_->offscreen_resolved_frame_buffer_->Create();
decoder_->offscreen_resolved_color_texture_.reset(new Texture(decoder_));
decoder_->offscreen_resolved_color_texture_->Create();
DCHECK(decoder_->offscreen_saved_color_format_);
decoder_->offscreen_resolved_color_texture_->AllocateStorage(
decoder_->offscreen_size_, decoder_->offscreen_saved_color_format_);
decoder_->offscreen_resolved_frame_buffer_->AttachRenderTexture(
decoder_->offscreen_resolved_color_texture_.get());
if (decoder_->offscreen_resolved_frame_buffer_->CheckStatus() !=
GL_FRAMEBUFFER_COMPLETE) {
LOG(ERROR) << "ScopedResolvedFrameBufferBinder failed "
<< "because offscreen resolved FBO was incomplete.";
return;
}
}
targetid = decoder_->offscreen_resolved_frame_buffer_->id();
} else {
targetid = decoder_->offscreen_saved_frame_buffer_->id();
}
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, targetid);
const int width = decoder_->offscreen_size_.width();
const int height = decoder_->offscreen_size_.height();
glDisable(GL_SCISSOR_TEST);
if (IsAngle()) {
glBlitFramebufferANGLE(0, 0, width, height, 0, 0, width, height,
GL_COLOR_BUFFER_BIT, GL_NEAREST);
} else {
glBlitFramebufferEXT(0, 0, width, height, 0, 0, width, height,
GL_COLOR_BUFFER_BIT, GL_NEAREST);
}
glBindFramebufferEXT(GL_FRAMEBUFFER, targetid);
}
Commit Message: Revert "Revert 100494 - Fix bug in SimulateAttrib0."""
TEST=none
BUG=95625
[email protected]
Review URL: http://codereview.chromium.org/7796016
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@100507 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void atrtr_set_default(struct net_device *dev)
{
atrtr_default.dev = dev;
atrtr_default.flags = RTF_UP;
atrtr_default.gateway.s_net = htons(0);
atrtr_default.gateway.s_node = 0;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
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 == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1;
image=AcquireImage(image_info,exception);
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;
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(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->resolution.x=BitmapHeader1.HorzRes/470.0;
image->resolution.y=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);
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors,exception))
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->resolution.x=BitmapHeader2.HorzRes/470.0;
image->resolution.y=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
{
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=(PixelInfo *) 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,exception) < 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);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&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);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&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);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
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);
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors,exception) == 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;
if ((image->colors == 0) && (bpp != 24))
{
size_t
one;
one=1;
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors,exception))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelInfo *) 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,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(image,BImgBuff,i,bpp,exception);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);;
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp,exception) < 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);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&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);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&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,exception);
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");
}
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
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/120
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void needsStyleRecalcCallback(Node* node, unsigned data)
{
node->setNeedsStyleRecalc(static_cast<StyleChangeType>(data));
}
Commit Message: https://bugs.webkit.org/show_bug.cgi?id=93587
Node::replaceChild() can create bad DOM topology with MutationEvent, Part 2
Reviewed by Kent Tamura.
Source/WebCore:
This is a followup of r124156. replaceChild() has yet another hidden
MutationEvent trigger. This change added a guard for it.
Test: fast/events/mutation-during-replace-child-2.html
* dom/ContainerNode.cpp:
(WebCore::ContainerNode::replaceChild):
LayoutTests:
* fast/events/mutation-during-replace-child-2-expected.txt: Added.
* fast/events/mutation-during-replace-child-2.html: Added.
git-svn-id: svn://svn.chromium.org/blink/trunk@125237 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ip6mr_rule_compare(struct fib_rule *rule, struct fib_rule_hdr *frh,
struct nlattr **tb)
{
return 1;
}
Commit Message: ipv6: check sk sk_type and protocol early in ip_mroute_set/getsockopt
Commit 5e1859fbcc3c ("ipv4: ipmr: various fixes and cleanups") fixed
the issue for ipv4 ipmr:
ip_mroute_setsockopt() & ip_mroute_getsockopt() should not
access/set raw_sk(sk)->ipmr_table before making sure the socket
is a raw socket, and protocol is IGMP
The same fix should be done for ipv6 ipmr as well.
This patch can fix the panic caused by overwriting the same offset
as ipmr_table as in raw_sk(sk) when accessing other type's socket
by ip_mroute_setsockopt().
Signed-off-by: Xin Long <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: AudioRendererHost::AudioRendererHost(int render_process_id,
media::AudioManager* audio_manager,
AudioMirroringManager* mirroring_manager,
MediaStreamManager* media_stream_manager,
const std::string& salt)
: BrowserMessageFilter(AudioMsgStart),
render_process_id_(render_process_id),
audio_manager_(audio_manager),
mirroring_manager_(mirroring_manager),
media_stream_manager_(media_stream_manager),
salt_(salt),
validate_render_frame_id_function_(&ValidateRenderFrameId),
authorization_handler_(audio_manager_,
media_stream_manager,
render_process_id_,
salt) {
DCHECK(audio_manager_);
}
Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one.
BUG=672468
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Review-Url: https://codereview.chromium.org/2692203003
Cr-Commit-Position: refs/heads/master@{#450939}
CWE ID:
Target: 1
Example 2:
Code: static bool migrate_task(struct task_struct *p, int dest_cpu)
{
struct rq *rq = task_rq(p);
/*
* If the task is not on a runqueue (and not running), then
* the next wake-up will properly place the task.
*/
return p->se.on_rq || task_running(rq, p);
}
Commit Message: Sched: fix skip_clock_update optimization
idle_balance() drops/retakes rq->lock, leaving the previous task
vulnerable to set_tsk_need_resched(). Clear it after we return
from balancing instead, and in setup_thread_stack() as well, so
no successfully descheduled or never scheduled task has it set.
Need resched confused the skip_clock_update logic, which assumes
that the next call to update_rq_clock() will come nearly immediately
after being set. Make the optimization robust against the waking
a sleeper before it sucessfully deschedules case by checking that
the current task has not been dequeued before setting the flag,
since it is that useless clock update we're trying to save, and
clear unconditionally in schedule() proper instead of conditionally
in put_prev_task().
Signed-off-by: Mike Galbraith <[email protected]>
Reported-by: Bjoern B. Brandenburg <[email protected]>
Tested-by: Yong Zhang <[email protected]>
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: [email protected]
LKML-Reference: <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: box_gt(PG_FUNCTION_ARGS)
{
BOX *box1 = PG_GETARG_BOX_P(0);
BOX *box2 = PG_GETARG_BOX_P(1);
PG_RETURN_BOOL(FPgt(box_ar(box1), box_ar(box2)));
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void perf_log_throttle(struct perf_event *event, int enable)
{
struct perf_output_handle handle;
struct perf_sample_data sample;
int ret;
struct {
struct perf_event_header header;
u64 time;
u64 id;
u64 stream_id;
} throttle_event = {
.header = {
.type = PERF_RECORD_THROTTLE,
.misc = 0,
.size = sizeof(throttle_event),
},
.time = perf_clock(),
.id = primary_event_id(event),
.stream_id = event->id,
};
if (enable)
throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
perf_event_header__init_id(&throttle_event.header, &sample, event);
ret = perf_output_begin(&handle, event,
throttle_event.header.size, 1, 0);
if (ret)
return;
perf_output_put(&handle, throttle_event);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
}
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
Target: 1
Example 2:
Code: inter_lb(PG_FUNCTION_ARGS)
{
LINE *line = PG_GETARG_LINE_P(0);
BOX *box = PG_GETARG_BOX_P(1);
LSEG bseg;
Point p1,
p2;
/* pairwise check lseg intersections */
p1.x = box->low.x;
p1.y = box->low.y;
p2.x = box->low.x;
p2.y = box->high.y;
statlseg_construct(&bseg, &p1, &p2);
if (has_interpt_sl(&bseg, line))
PG_RETURN_BOOL(true);
p1.x = box->high.x;
p1.y = box->high.y;
statlseg_construct(&bseg, &p1, &p2);
if (has_interpt_sl(&bseg, line))
PG_RETURN_BOOL(true);
p2.x = box->high.x;
p2.y = box->low.y;
statlseg_construct(&bseg, &p1, &p2);
if (has_interpt_sl(&bseg, line))
PG_RETURN_BOOL(true);
p1.x = box->low.x;
p1.y = box->low.y;
statlseg_construct(&bseg, &p1, &p2);
if (has_interpt_sl(&bseg, line))
PG_RETURN_BOOL(true);
/* if we dropped through, no intersection */
PG_RETURN_BOOL(false);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ProfileDependencyManager* ProfileDependencyManager::GetInstance() {
return Singleton<ProfileDependencyManager>::get();
}
Commit Message: DIAL (Discovery and Launch protocol) extension API skeleton.
This implements the skeleton for a new Chrome extension API for local device discovery. The API will first be restricted to whitelisted extensions only. The API will allow extensions to receive events from a DIAL service running within Chrome which notifies of devices being discovered on the local network.
Spec available here:
https://docs.google.com/a/google.com/document/d/14FI-VKWrsMG7pIy3trgM3ybnKS-o5TULkt8itiBNXlQ/edit
BUG=163288
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11444020
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@172243 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: get_princs_2_svc(gprincs_arg *arg, struct svc_req *rqstp)
{
static gprincs_ret ret;
char *prime_arg;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gprincs_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
prime_arg = arg->exp;
if (prime_arg == NULL)
prime_arg = "*";
if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_LIST,
NULL,
NULL)) {
ret.code = KADM5_AUTH_LIST;
log_unauth("kadm5_get_principals", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_get_principals((void *)handle,
arg->exp, &ret.princs,
&ret.count);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_principals", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119
Target: 1
Example 2:
Code: WebKit::WebFrame* PrintWebViewHelper::PrintPreviewContext::frame() const {
return frame_;
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ExtensionTtsPlatformImpl* ExtensionTtsPlatformImpl::GetInstance() {
return ExtensionTtsPlatformImplLinux::GetInstance();
}
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
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec,
WORD32 num_mb_skip,
UWORD8 u1_is_idr_slice,
UWORD16 u2_frame_num,
pocstruct_t *ps_cur_poc,
WORD32 prev_slice_err)
{
WORD32 i2_cur_mb_addr;
UWORD32 u1_num_mbs, u1_num_mbsNby2;
UWORD32 u1_mb_idx = ps_dec->u1_mb_idx;
UWORD32 i2_mb_skip_run;
UWORD32 u1_num_mbs_next, u1_end_of_row;
const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
UWORD32 u1_slice_end;
UWORD32 u1_tfr_n_mb;
UWORD32 u1_decode_nmb;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
deblk_mb_t *ps_cur_deblk_mb;
dec_mb_info_t *ps_cur_mb_info;
parse_pmbarams_t *ps_parse_mb_data;
UWORD32 u1_inter_mb_type;
UWORD32 u1_deblk_mb_type;
UWORD16 u2_total_mbs_coded;
UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag;
parse_part_params_t *ps_part_info;
WORD32 ret;
if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC)
{
ih264d_err_pic_dispbuf_mgr(ps_dec);
return 0;
}
ps_dec->ps_dpb_cmds->u1_long_term_reference_flag = 0;
if(prev_slice_err == 1)
{
/* first slice - missing/header corruption */
ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num;
if(!ps_dec->u1_first_slice_in_stream)
{
ih264d_end_of_pic(ps_dec, u1_is_idr_slice,
ps_dec->ps_cur_slice->u2_frame_num);
ps_dec->s_cur_pic_poc.u2_frame_num =
ps_dec->ps_cur_slice->u2_frame_num;
}
{
WORD32 i, j, poc = 0;
ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0;
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff;
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_bp;
if(ps_dec->ps_cur_pic != NULL)
poc = ps_dec->ps_cur_pic->i4_poc + 2;
j = 0;
for(i = 0; i < MAX_NUM_PIC_PARAMS; i++)
if(ps_dec->ps_pps[i].u1_is_valid == TRUE)
j = i;
{
ps_dec->ps_cur_slice->u1_slice_type = P_SLICE;
ps_dec->ps_cur_slice->u1_nal_ref_idc = 1;
ps_dec->ps_cur_slice->u1_nal_unit_type = 1;
ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc,
ps_dec->ps_cur_slice->u2_frame_num,
&ps_dec->ps_pps[j]);
if(ret != OK)
{
return ret;
}
}
ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0;
ps_dec->u4_output_present = 0;
{
ih264d_get_next_display_field(ps_dec,
ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
/* If error code is non-zero then there is no buffer available for display,
hence avoid format conversion */
if(0 != ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht;
}
else
ps_dec->u4_output_present = 1;
}
if(ps_dec->u1_separate_parse == 1)
{
if(ps_dec->u4_dec_thread_created == 0)
{
ithread_create(ps_dec->pv_dec_thread_handle, NULL,
(void *)ih264d_decode_picture_thread,
(void *)ps_dec);
ps_dec->u4_dec_thread_created = 1;
}
if((ps_dec->u4_num_cores == 3) &&
((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag)
&& (ps_dec->u4_bs_deblk_thread_created == 0))
{
ps_dec->u4_start_recon_deblk = 0;
ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL,
(void *)ih264d_recon_deblk_thread,
(void *)ps_dec);
ps_dec->u4_bs_deblk_thread_created = 1;
}
}
}
}
else
{
dec_slice_struct_t *ps_parse_cur_slice;
ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num;
if(ps_dec->u1_slice_header_done
&& ps_parse_cur_slice == ps_dec->ps_parse_cur_slice)
{
u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb;
if(u1_num_mbs)
{
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1;
}
else
{
if(ps_dec->u1_separate_parse)
{
ps_cur_mb_info = ps_dec->ps_nmb_info - 1;
}
else
{
ps_cur_mb_info = ps_dec->ps_nmb_info
+ ps_dec->u4_num_mbs_prev_nmb - 1;
}
}
ps_dec->u2_mby = ps_cur_mb_info->u2_mby;
ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx;
ps_dec->u1_mb_ngbr_availablity =
ps_cur_mb_info->u1_mb_ngbr_availablity;
ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data;
ps_dec->u2_cur_mb_addr--;
ps_dec->i4_submb_ofst -= SUB_BLK_SIZE;
if(u1_num_mbs)
{
if (ps_dec->u1_pr_sl_type == P_SLICE
|| ps_dec->u1_pr_sl_type == B_SLICE)
{
ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs);
ps_dec->ps_part = ps_dec->ps_parse_part_params;
}
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next)
&& (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_slice_end = 1;
u1_tfr_n_mb = 1;
ps_cur_mb_info->u1_end_of_slice = u1_slice_end;
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
ps_dec->u1_mb_idx = 0;
ps_dec->u4_num_mbs_cur_nmb = 0;
}
if(ps_dec->u2_total_mbs_coded
>= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
ps_dec->u1_pic_decode_done = 1;
return 0;
}
ps_dec->u2_cur_slice_num++;
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
ps_dec->ps_parse_cur_slice++;
}
else
{
ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf
+ ps_dec->u2_cur_slice_num;
}
}
/******************************************************/
/* Initializations to new slice */
/******************************************************/
{
WORD32 num_entries;
WORD32 size;
UWORD8 *pu1_buf;
num_entries = MAX_FRAMES;
if((1 >= ps_dec->ps_cur_sps->u1_num_ref_frames) &&
(0 == ps_dec->i4_display_delay))
{
num_entries = 1;
}
num_entries = ((2 * num_entries) + 1);
if(BASE_PROFILE_IDC != ps_dec->ps_cur_sps->u1_profile_idc)
{
num_entries *= 2;
}
size = num_entries * sizeof(void *);
size += PAD_MAP_IDX_POC * sizeof(void *);
pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf;
pu1_buf += size * ps_dec->u2_cur_slice_num;
ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = (volatile void **)pu1_buf;
}
ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff;
ps_dec->ps_cur_slice->i1_slice_alpha_c0_offset = 0;
ps_dec->ps_cur_slice->i1_slice_beta_offset = 0;
if(ps_dec->ps_cur_slice->u1_field_pic_flag)
ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num;
ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff;
ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd;
if(ps_dec->u1_separate_parse)
{
ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data;
}
else
{
ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
}
/******************************************************/
/* Initializations specific to P slice */
/******************************************************/
u1_inter_mb_type = P_MB;
u1_deblk_mb_type = D_INTER_MB;
ps_dec->ps_cur_slice->u1_slice_type = P_SLICE;
ps_dec->ps_parse_cur_slice->slice_type = P_SLICE;
ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
/******************************************************/
/* Parsing / decoding the slice */
/******************************************************/
ps_dec->u1_slice_header_done = 2;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mb_idx = ps_dec->u1_mb_idx;
ps_parse_mb_data = ps_dec->ps_parse_mb_data;
u1_num_mbs = u1_mb_idx;
u1_slice_end = 0;
u1_tfr_n_mb = 0;
u1_decode_nmb = 0;
u1_num_mbsNby2 = 0;
i2_cur_mb_addr = ps_dec->u2_total_mbs_coded;
i2_mb_skip_run = num_mb_skip;
while(!u1_slice_end)
{
UWORD8 u1_mb_type;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
break;
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_cur_mb_info->u1_Mux = 0;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
ps_cur_mb_info->u1_end_of_slice = 0;
/* Storing Default partition info */
ps_parse_mb_data->u1_num_part = 1;
ps_parse_mb_data->u1_isI_mb = 0;
/**************************************************************/
/* Get the required information for decoding of MB */
/**************************************************************/
/* mb_x, mb_y, neighbor availablity, */
if (u1_mbaff)
ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run);
else
ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run);
/* Set the deblocking parameters for this MB */
if(ps_dec->u4_app_disable_deblk_frm == 0)
{
ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
}
/* Set appropriate flags in ps_cur_mb_info and ps_dec */
ps_dec->i1_prev_mb_qp_delta = 0;
ps_dec->u1_sub_mb_num = 0;
ps_cur_mb_info->u1_mb_type = MB_SKIP;
ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16;
ps_cur_mb_info->u1_cbp = 0;
/* Storing Skip partition info */
ps_part_info = ps_dec->ps_part;
ps_part_info->u1_is_direct = PART_DIRECT_16x16;
ps_part_info->u1_sub_mb_num = 0;
ps_dec->ps_part++;
/* Update Nnzs */
ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC);
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
i2_mb_skip_run--;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
if (u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/**************************************************************/
/* Get next Macroblock address */
/**************************************************************/
i2_cur_mb_addr++;
u1_num_mbs++;
u1_num_mbsNby2++;
ps_parse_mb_data++;
/****************************************************************/
/* Check for End Of Row and other flags that determine when to */
/* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */
/* N-Mb */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_slice_end = !i2_mb_skip_run;
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| u1_slice_end;
u1_decode_nmb = u1_tfr_n_mb || u1_slice_end;
ps_cur_mb_info->u1_end_of_slice = u1_slice_end;
if(u1_decode_nmb)
{
ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs);
u1_num_mbsNby2 = 0;
ps_parse_mb_data = ps_dec->ps_parse_mb_data;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next,
u1_tfr_n_mb, u1_end_of_row);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice;
H264_DEC_DEBUG_PRINT("Mbs in slice: %d\n", ps_dec->ps_cur_slice->u4_mbs_in_slice);
ps_dec->u2_cur_slice_num++;
/* incremented here only if first slice is inserted */
if(ps_dec->u4_first_slice_in_pic != 0)
ps_dec->ps_parse_cur_slice++;
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
if(ps_dec->u2_total_mbs_coded
>= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
ps_dec->u1_pic_decode_done = 1;
}
return 0;
}
Commit Message: Decoder: Fix slice number increment for error clips
Bug: 28673410
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int __init seqiv_module_init(void)
{
return crypto_register_template(&seqiv_tmpl);
}
Commit Message: crypto: include crypto- module prefix in template
This adds the module loading prefix "crypto-" to the template lookup
as well.
For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly
includes the "crypto-" prefix at every level, correctly rejecting "vfat":
net-pf-38
algif-hash
crypto-vfat(blowfish)
crypto-vfat(blowfish)-all
crypto-vfat
Reported-by: Mathias Krause <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Acked-by: Mathias Krause <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void StorageHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
process_ = process_host;
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: process_tgs_req(struct server_handle *handle, krb5_data *pkt,
const krb5_fulladdr *from, krb5_data **response)
{
krb5_keyblock * subkey = 0;
krb5_keyblock *header_key = NULL;
krb5_kdc_req *request = 0;
krb5_db_entry *server = NULL;
krb5_db_entry *stkt_server = NULL;
krb5_kdc_rep reply;
krb5_enc_kdc_rep_part reply_encpart;
krb5_ticket ticket_reply, *header_ticket = 0;
int st_idx = 0;
krb5_enc_tkt_part enc_tkt_reply;
int newtransited = 0;
krb5_error_code retval = 0;
krb5_keyblock encrypting_key;
krb5_timestamp kdc_time, authtime = 0;
krb5_keyblock session_key;
krb5_keyblock *reply_key = NULL;
krb5_key_data *server_key;
krb5_principal cprinc = NULL, sprinc = NULL, altcprinc = NULL;
krb5_last_req_entry *nolrarray[2], nolrentry;
int errcode;
const char *status = 0;
krb5_enc_tkt_part *header_enc_tkt = NULL; /* TGT */
krb5_enc_tkt_part *subject_tkt = NULL; /* TGT or evidence ticket */
krb5_db_entry *client = NULL, *header_server = NULL;
krb5_db_entry *local_tgt, *local_tgt_storage = NULL;
krb5_pa_s4u_x509_user *s4u_x509_user = NULL; /* protocol transition request */
krb5_authdata **kdc_issued_auth_data = NULL; /* auth data issued by KDC */
unsigned int c_flags = 0, s_flags = 0; /* client/server KDB flags */
krb5_boolean is_referral;
const char *emsg = NULL;
krb5_kvno ticket_kvno = 0;
struct kdc_request_state *state = NULL;
krb5_pa_data *pa_tgs_req; /*points into request*/
krb5_data scratch;
krb5_pa_data **e_data = NULL;
kdc_realm_t *kdc_active_realm = NULL;
krb5_audit_state *au_state = NULL;
krb5_data **auth_indicators = NULL;
memset(&reply, 0, sizeof(reply));
memset(&reply_encpart, 0, sizeof(reply_encpart));
memset(&ticket_reply, 0, sizeof(ticket_reply));
memset(&enc_tkt_reply, 0, sizeof(enc_tkt_reply));
session_key.contents = NULL;
retval = decode_krb5_tgs_req(pkt, &request);
if (retval)
return retval;
/* Save pointer to client-requested service principal, in case of
* errors before a successful call to search_sprinc(). */
sprinc = request->server;
if (request->msg_type != KRB5_TGS_REQ) {
krb5_free_kdc_req(handle->kdc_err_context, request);
return KRB5_BADMSGTYPE;
}
/*
* setup_server_realm() sets up the global realm-specific data pointer.
*/
kdc_active_realm = setup_server_realm(handle, request->server);
if (kdc_active_realm == NULL) {
krb5_free_kdc_req(handle->kdc_err_context, request);
return KRB5KDC_ERR_WRONG_REALM;
}
errcode = kdc_make_rstate(kdc_active_realm, &state);
if (errcode !=0) {
krb5_free_kdc_req(handle->kdc_err_context, request);
return errcode;
}
/* Initialize audit state. */
errcode = kau_init_kdc_req(kdc_context, request, from, &au_state);
if (errcode) {
krb5_free_kdc_req(handle->kdc_err_context, request);
return errcode;
}
/* Seed the audit trail with the request ID and basic information. */
kau_tgs_req(kdc_context, TRUE, au_state);
errcode = kdc_process_tgs_req(kdc_active_realm,
request, from, pkt, &header_ticket,
&header_server, &header_key, &subkey,
&pa_tgs_req);
if (header_ticket && header_ticket->enc_part2)
cprinc = header_ticket->enc_part2->client;
if (errcode) {
status = "PROCESS_TGS";
goto cleanup;
}
if (!header_ticket) {
errcode = KRB5_NO_TKT_SUPPLIED; /* XXX? */
status="UNEXPECTED NULL in header_ticket";
goto cleanup;
}
errcode = kau_make_tkt_id(kdc_context, header_ticket,
&au_state->tkt_in_id);
if (errcode) {
status = "GENERATE_TICKET_ID";
goto cleanup;
}
scratch.length = pa_tgs_req->length;
scratch.data = (char *) pa_tgs_req->contents;
errcode = kdc_find_fast(&request, &scratch, subkey,
header_ticket->enc_part2->session, state, NULL);
/* Reset sprinc because kdc_find_fast() can replace request. */
sprinc = request->server;
if (errcode !=0) {
status = "FIND_FAST";
goto cleanup;
}
errcode = get_local_tgt(kdc_context, &sprinc->realm, header_server,
&local_tgt, &local_tgt_storage);
if (errcode) {
status = "GET_LOCAL_TGT";
goto cleanup;
}
/* Ignore (for now) the request modification due to FAST processing. */
au_state->request = request;
/*
* Pointer to the encrypted part of the header ticket, which may be
* replaced to point to the encrypted part of the evidence ticket
* if constrained delegation is used. This simplifies the number of
* special cases for constrained delegation.
*/
header_enc_tkt = header_ticket->enc_part2;
/*
* We've already dealt with the AP_REQ authentication, so we can
* use header_ticket freely. The encrypted part (if any) has been
* decrypted with the session key.
*/
au_state->stage = SRVC_PRINC;
/* XXX make sure server here has the proper realm...taken from AP_REQ
header? */
setflag(s_flags, KRB5_KDB_FLAG_ALIAS_OK);
if (isflagset(request->kdc_options, KDC_OPT_CANONICALIZE)) {
setflag(c_flags, KRB5_KDB_FLAG_CANONICALIZE);
setflag(s_flags, KRB5_KDB_FLAG_CANONICALIZE);
}
errcode = search_sprinc(kdc_active_realm, request, s_flags, &server,
&status);
if (errcode != 0)
goto cleanup;
sprinc = server->princ;
/* If we got a cross-realm TGS which is not the requested server, we are
* issuing a referral (or alternate TGT, which we treat similarly). */
is_referral = is_cross_tgs_principal(server->princ) &&
!krb5_principal_compare(kdc_context, request->server, server->princ);
au_state->stage = VALIDATE_POL;
if ((errcode = krb5_timeofday(kdc_context, &kdc_time))) {
status = "TIME_OF_DAY";
goto cleanup;
}
if ((retval = validate_tgs_request(kdc_active_realm,
request, *server, header_ticket,
kdc_time, &status, &e_data))) {
if (!status)
status = "UNKNOWN_REASON";
if (retval == KDC_ERR_POLICY || retval == KDC_ERR_BADOPTION)
au_state->violation = PROT_CONSTRAINT;
errcode = retval + ERROR_TABLE_BASE_krb5;
goto cleanup;
}
if (!is_local_principal(kdc_active_realm, header_enc_tkt->client))
setflag(c_flags, KRB5_KDB_FLAG_CROSS_REALM);
/* Check for protocol transition */
errcode = kdc_process_s4u2self_req(kdc_active_realm,
request,
header_enc_tkt->client,
server,
subkey,
header_enc_tkt->session,
kdc_time,
&s4u_x509_user,
&client,
&status);
if (s4u_x509_user != NULL || errcode != 0) {
if (s4u_x509_user != NULL)
au_state->s4u2self_user = s4u_x509_user->user_id.user;
if (errcode == KDC_ERR_POLICY || errcode == KDC_ERR_BADOPTION)
au_state->violation = PROT_CONSTRAINT;
au_state->status = status;
kau_s4u2self(kdc_context, errcode ? FALSE : TRUE, au_state);
au_state->s4u2self_user = NULL;
}
if (errcode)
goto cleanup;
if (s4u_x509_user != NULL) {
setflag(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION);
if (is_referral) {
/* The requesting server appears to no longer exist, and we found
* a referral instead. Treat this as a server lookup failure. */
errcode = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
status = "LOOKING_UP_SERVER";
goto cleanup;
}
}
/* Deal with user-to-user and constrained delegation */
errcode = decrypt_2ndtkt(kdc_active_realm, request, c_flags,
&stkt_server, &status);
if (errcode)
goto cleanup;
if (isflagset(request->kdc_options, KDC_OPT_CNAME_IN_ADDL_TKT)) {
/* Do constrained delegation protocol and authorization checks */
errcode = kdc_process_s4u2proxy_req(kdc_active_realm,
request,
request->second_ticket[st_idx]->enc_part2,
stkt_server,
header_ticket->enc_part2->client,
request->server,
&status);
if (errcode == KDC_ERR_POLICY || errcode == KDC_ERR_BADOPTION)
au_state->violation = PROT_CONSTRAINT;
else if (errcode)
au_state->violation = LOCAL_POLICY;
au_state->status = status;
retval = kau_make_tkt_id(kdc_context, request->second_ticket[st_idx],
&au_state->evid_tkt_id);
if (retval) {
status = "GENERATE_TICKET_ID";
errcode = retval;
goto cleanup;
}
kau_s4u2proxy(kdc_context, errcode ? FALSE : TRUE, au_state);
if (errcode)
goto cleanup;
setflag(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION);
assert(krb5_is_tgs_principal(header_ticket->server));
assert(client == NULL); /* assured by kdc_process_s4u2self_req() */
client = stkt_server;
stkt_server = NULL;
} else if (request->kdc_options & KDC_OPT_ENC_TKT_IN_SKEY) {
krb5_db_free_principal(kdc_context, stkt_server);
stkt_server = NULL;
} else
assert(stkt_server == NULL);
au_state->stage = ISSUE_TKT;
errcode = gen_session_key(kdc_active_realm, request, server, &session_key,
&status);
if (errcode)
goto cleanup;
/*
* subject_tkt will refer to the evidence ticket (for constrained
* delegation) or the TGT. The distinction from header_enc_tkt is
* necessary because the TGS signature only protects some fields:
* the others could be forged by a malicious server.
*/
if (isflagset(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION))
subject_tkt = request->second_ticket[st_idx]->enc_part2;
else
subject_tkt = header_enc_tkt;
authtime = subject_tkt->times.authtime;
/* Extract auth indicators from the subject ticket, except for S4U2Proxy
* requests (where the client didn't authenticate). */
if (s4u_x509_user == NULL) {
errcode = get_auth_indicators(kdc_context, subject_tkt, local_tgt,
&auth_indicators);
if (errcode) {
status = "GET_AUTH_INDICATORS";
goto cleanup;
}
}
errcode = check_indicators(kdc_context, server, auth_indicators);
if (errcode) {
status = "HIGHER_AUTHENTICATION_REQUIRED";
goto cleanup;
}
if (is_referral)
ticket_reply.server = server->princ;
else
ticket_reply.server = request->server; /* XXX careful for realm... */
enc_tkt_reply.flags = OPTS2FLAGS(request->kdc_options);
enc_tkt_reply.flags |= COPY_TKT_FLAGS(header_enc_tkt->flags);
enc_tkt_reply.times.starttime = 0;
if (isflagset(server->attributes, KRB5_KDB_OK_AS_DELEGATE))
setflag(enc_tkt_reply.flags, TKT_FLG_OK_AS_DELEGATE);
/* Indicate support for encrypted padata (RFC 6806). */
setflag(enc_tkt_reply.flags, TKT_FLG_ENC_PA_REP);
/* don't use new addresses unless forwarded, see below */
enc_tkt_reply.caddrs = header_enc_tkt->caddrs;
/* noaddrarray[0] = 0; */
reply_encpart.caddrs = 0;/* optional...don't put it in */
reply_encpart.enc_padata = NULL;
/*
* It should be noted that local policy may affect the
* processing of any of these flags. For example, some
* realms may refuse to issue renewable tickets
*/
if (isflagset(request->kdc_options, KDC_OPT_FORWARDABLE)) {
if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION)) {
/*
* If S4U2Self principal is not forwardable, then mark ticket as
* unforwardable. This behaviour matches Windows, but it is
* different to the MIT AS-REQ path, which returns an error
* (KDC_ERR_POLICY) if forwardable tickets cannot be issued.
*
* Consider this block the S4U2Self equivalent to
* validate_forwardable().
*/
if (client != NULL &&
isflagset(client->attributes, KRB5_KDB_DISALLOW_FORWARDABLE))
clear(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE);
/*
* Forwardable flag is propagated along referral path.
*/
else if (!isflagset(header_enc_tkt->flags, TKT_FLG_FORWARDABLE))
clear(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE);
/*
* OK_TO_AUTH_AS_DELEGATE must be set on the service requesting
* S4U2Self in order for forwardable tickets to be returned.
*/
else if (!is_referral &&
!isflagset(server->attributes,
KRB5_KDB_OK_TO_AUTH_AS_DELEGATE))
clear(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE);
}
}
if (isflagset(request->kdc_options, KDC_OPT_FORWARDED) ||
isflagset(request->kdc_options, KDC_OPT_PROXY)) {
/* include new addresses in ticket & reply */
enc_tkt_reply.caddrs = request->addresses;
reply_encpart.caddrs = request->addresses;
}
/* We don't currently handle issuing anonymous tickets based on
* non-anonymous ones, so just ignore the option. */
if (isflagset(request->kdc_options, KDC_OPT_REQUEST_ANONYMOUS) &&
!isflagset(header_enc_tkt->flags, TKT_FLG_ANONYMOUS))
clear(enc_tkt_reply.flags, TKT_FLG_ANONYMOUS);
if (isflagset(request->kdc_options, KDC_OPT_POSTDATED)) {
setflag(enc_tkt_reply.flags, TKT_FLG_INVALID);
enc_tkt_reply.times.starttime = request->from;
} else
enc_tkt_reply.times.starttime = kdc_time;
if (isflagset(request->kdc_options, KDC_OPT_VALIDATE)) {
assert(isflagset(c_flags, KRB5_KDB_FLAGS_S4U) == 0);
/* BEWARE of allocation hanging off of ticket & enc_part2, it belongs
to the caller */
ticket_reply = *(header_ticket);
enc_tkt_reply = *(header_ticket->enc_part2);
enc_tkt_reply.authorization_data = NULL;
clear(enc_tkt_reply.flags, TKT_FLG_INVALID);
}
if (isflagset(request->kdc_options, KDC_OPT_RENEW)) {
krb5_timestamp old_starttime;
krb5_deltat old_life;
assert(isflagset(c_flags, KRB5_KDB_FLAGS_S4U) == 0);
/* BEWARE of allocation hanging off of ticket & enc_part2, it belongs
to the caller */
ticket_reply = *(header_ticket);
enc_tkt_reply = *(header_ticket->enc_part2);
enc_tkt_reply.authorization_data = NULL;
old_starttime = enc_tkt_reply.times.starttime ?
enc_tkt_reply.times.starttime : enc_tkt_reply.times.authtime;
old_life = ts_delta(enc_tkt_reply.times.endtime, old_starttime);
enc_tkt_reply.times.starttime = kdc_time;
enc_tkt_reply.times.endtime =
ts_min(header_ticket->enc_part2->times.renew_till,
ts_incr(kdc_time, old_life));
} else {
/* not a renew request */
enc_tkt_reply.times.starttime = kdc_time;
kdc_get_ticket_endtime(kdc_active_realm, enc_tkt_reply.times.starttime,
header_enc_tkt->times.endtime, request->till,
client, server, &enc_tkt_reply.times.endtime);
}
kdc_get_ticket_renewtime(kdc_active_realm, request, header_enc_tkt, client,
server, &enc_tkt_reply);
/*
* Set authtime to be the same as header or evidence ticket's
*/
enc_tkt_reply.times.authtime = authtime;
/* starttime is optional, and treated as authtime if not present.
so we can nuke it if it matches */
if (enc_tkt_reply.times.starttime == enc_tkt_reply.times.authtime)
enc_tkt_reply.times.starttime = 0;
if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION)) {
altcprinc = s4u_x509_user->user_id.user;
} else if (isflagset(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION)) {
altcprinc = subject_tkt->client;
} else {
altcprinc = NULL;
}
if (isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY)) {
krb5_enc_tkt_part *t2enc = request->second_ticket[st_idx]->enc_part2;
encrypting_key = *(t2enc->session);
} else {
/*
* Find the server key
*/
if ((errcode = krb5_dbe_find_enctype(kdc_context, server,
-1, /* ignore keytype */
-1, /* Ignore salttype */
0, /* Get highest kvno */
&server_key))) {
status = "FINDING_SERVER_KEY";
goto cleanup;
}
/*
* Convert server.key into a real key
* (it may be encrypted in the database)
*/
if ((errcode = krb5_dbe_decrypt_key_data(kdc_context, NULL,
server_key, &encrypting_key,
NULL))) {
status = "DECRYPT_SERVER_KEY";
goto cleanup;
}
}
if (isflagset(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION)) {
/*
* Don't allow authorization data to be disabled if constrained
* delegation is requested. We don't want to deny the server
* the ability to validate that delegation was used.
*/
clear(server->attributes, KRB5_KDB_NO_AUTH_DATA_REQUIRED);
}
if (isflagset(server->attributes, KRB5_KDB_NO_AUTH_DATA_REQUIRED) == 0) {
/*
* If we are not doing protocol transition/constrained delegation
* try to lookup the client principal so plugins can add additional
* authorization information.
*
* Always validate authorization data for constrained delegation
* because we must validate the KDC signatures.
*/
if (!isflagset(c_flags, KRB5_KDB_FLAGS_S4U)) {
/* Generate authorization data so we can include it in ticket */
setflag(c_flags, KRB5_KDB_FLAG_INCLUDE_PAC);
/* Map principals from foreign (possibly non-AD) realms */
setflag(c_flags, KRB5_KDB_FLAG_MAP_PRINCIPALS);
assert(client == NULL); /* should not have been set already */
errcode = krb5_db_get_principal(kdc_context, subject_tkt->client,
c_flags, &client);
}
}
if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION) &&
!isflagset(c_flags, KRB5_KDB_FLAG_CROSS_REALM))
enc_tkt_reply.client = s4u_x509_user->user_id.user;
else
enc_tkt_reply.client = subject_tkt->client;
enc_tkt_reply.session = &session_key;
enc_tkt_reply.transited.tr_type = KRB5_DOMAIN_X500_COMPRESS;
enc_tkt_reply.transited.tr_contents = empty_string; /* equivalent of "" */
/*
* Only add the realm of the presented tgt to the transited list if
* it is different than the local realm (cross-realm) and it is different
* than the realm of the client (since the realm of the client is already
* implicitly part of the transited list and should not be explicitly
* listed).
*/
/* realm compare is like strcmp, but knows how to deal with these args */
if (krb5_realm_compare(kdc_context, header_ticket->server, tgs_server) ||
krb5_realm_compare(kdc_context, header_ticket->server,
enc_tkt_reply.client)) {
/* tgt issued by local realm or issued by realm of client */
enc_tkt_reply.transited = header_enc_tkt->transited;
} else {
/* tgt issued by some other realm and not the realm of the client */
/* assemble new transited field into allocated storage */
if (header_enc_tkt->transited.tr_type !=
KRB5_DOMAIN_X500_COMPRESS) {
status = "VALIDATE_TRANSIT_TYPE";
errcode = KRB5KDC_ERR_TRTYPE_NOSUPP;
goto cleanup;
}
memset(&enc_tkt_reply.transited, 0, sizeof(enc_tkt_reply.transited));
enc_tkt_reply.transited.tr_type = KRB5_DOMAIN_X500_COMPRESS;
if ((errcode =
add_to_transited(&header_enc_tkt->transited.tr_contents,
&enc_tkt_reply.transited.tr_contents,
header_ticket->server,
enc_tkt_reply.client,
request->server))) {
status = "ADD_TO_TRANSITED_LIST";
goto cleanup;
}
newtransited = 1;
}
if (isflagset(c_flags, KRB5_KDB_FLAG_CROSS_REALM)) {
errcode = validate_transit_path(kdc_context, header_enc_tkt->client,
server, header_server);
if (errcode) {
status = "NON_TRANSITIVE";
goto cleanup;
}
}
if (!isflagset (request->kdc_options, KDC_OPT_DISABLE_TRANSITED_CHECK)) {
errcode = kdc_check_transited_list (kdc_active_realm,
&enc_tkt_reply.transited.tr_contents,
krb5_princ_realm (kdc_context, header_enc_tkt->client),
krb5_princ_realm (kdc_context, request->server));
if (errcode == 0) {
setflag (enc_tkt_reply.flags, TKT_FLG_TRANSIT_POLICY_CHECKED);
} else {
log_tgs_badtrans(kdc_context, cprinc, sprinc,
&enc_tkt_reply.transited.tr_contents, errcode);
}
} else
krb5_klog_syslog(LOG_INFO, _("not checking transit path"));
if (kdc_active_realm->realm_reject_bad_transit &&
!isflagset(enc_tkt_reply.flags, TKT_FLG_TRANSIT_POLICY_CHECKED)) {
errcode = KRB5KDC_ERR_POLICY;
status = "BAD_TRANSIT";
au_state->violation = LOCAL_POLICY;
goto cleanup;
}
errcode = handle_authdata(kdc_context, c_flags, client, server,
header_server, local_tgt,
subkey != NULL ? subkey :
header_ticket->enc_part2->session,
&encrypting_key, /* U2U or server key */
header_key,
pkt,
request,
s4u_x509_user ?
s4u_x509_user->user_id.user : NULL,
subject_tkt,
auth_indicators,
&enc_tkt_reply);
if (errcode) {
krb5_klog_syslog(LOG_INFO, _("TGS_REQ : handle_authdata (%d)"),
errcode);
status = "HANDLE_AUTHDATA";
goto cleanup;
}
ticket_reply.enc_part2 = &enc_tkt_reply;
/*
* If we are doing user-to-user authentication, then make sure
* that the client for the second ticket matches the request
* server, and then encrypt the ticket using the session key of
* the second ticket.
*/
if (isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY)) {
/*
* Make sure the client for the second ticket matches
* requested server.
*/
krb5_enc_tkt_part *t2enc = request->second_ticket[st_idx]->enc_part2;
krb5_principal client2 = t2enc->client;
if (!krb5_principal_compare(kdc_context, request->server, client2)) {
altcprinc = client2;
errcode = KRB5KDC_ERR_SERVER_NOMATCH;
status = "2ND_TKT_MISMATCH";
au_state->status = status;
kau_u2u(kdc_context, FALSE, au_state);
goto cleanup;
}
ticket_kvno = 0;
ticket_reply.enc_part.enctype = t2enc->session->enctype;
kau_u2u(kdc_context, TRUE, au_state);
st_idx++;
} else {
ticket_kvno = server_key->key_data_kvno;
}
errcode = krb5_encrypt_tkt_part(kdc_context, &encrypting_key,
&ticket_reply);
if (!isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY))
krb5_free_keyblock_contents(kdc_context, &encrypting_key);
if (errcode) {
status = "ENCRYPT_TICKET";
goto cleanup;
}
ticket_reply.enc_part.kvno = ticket_kvno;
/* Start assembling the response */
au_state->stage = ENCR_REP;
reply.msg_type = KRB5_TGS_REP;
if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION) &&
krb5int_find_pa_data(kdc_context, request->padata,
KRB5_PADATA_S4U_X509_USER) != NULL) {
errcode = kdc_make_s4u2self_rep(kdc_context,
subkey,
header_ticket->enc_part2->session,
s4u_x509_user,
&reply,
&reply_encpart);
if (errcode) {
status = "MAKE_S4U2SELF_PADATA";
au_state->status = status;
}
kau_s4u2self(kdc_context, errcode ? FALSE : TRUE, au_state);
if (errcode)
goto cleanup;
}
reply.client = enc_tkt_reply.client;
reply.enc_part.kvno = 0;/* We are using the session key */
reply.ticket = &ticket_reply;
reply_encpart.session = &session_key;
reply_encpart.nonce = request->nonce;
/* copy the time fields */
reply_encpart.times = enc_tkt_reply.times;
nolrentry.lr_type = KRB5_LRQ_NONE;
nolrentry.value = 0;
nolrentry.magic = 0;
nolrarray[0] = &nolrentry;
nolrarray[1] = 0;
reply_encpart.last_req = nolrarray; /* not available for TGS reqs */
reply_encpart.key_exp = 0;/* ditto */
reply_encpart.flags = enc_tkt_reply.flags;
reply_encpart.server = ticket_reply.server;
/* use the session key in the ticket, unless there's a subsession key
in the AP_REQ */
reply.enc_part.enctype = subkey ? subkey->enctype :
header_ticket->enc_part2->session->enctype;
errcode = kdc_fast_response_handle_padata(state, request, &reply,
subkey ? subkey->enctype : header_ticket->enc_part2->session->enctype);
if (errcode !=0 ) {
status = "MAKE_FAST_RESPONSE";
goto cleanup;
}
errcode =kdc_fast_handle_reply_key(state,
subkey?subkey:header_ticket->enc_part2->session, &reply_key);
if (errcode) {
status = "MAKE_FAST_REPLY_KEY";
goto cleanup;
}
errcode = return_enc_padata(kdc_context, pkt, request,
reply_key, server, &reply_encpart,
is_referral &&
isflagset(s_flags,
KRB5_KDB_FLAG_CANONICALIZE));
if (errcode) {
status = "KDC_RETURN_ENC_PADATA";
goto cleanup;
}
errcode = kau_make_tkt_id(kdc_context, &ticket_reply, &au_state->tkt_out_id);
if (errcode) {
status = "GENERATE_TICKET_ID";
goto cleanup;
}
if (kdc_fast_hide_client(state))
reply.client = (krb5_principal)krb5_anonymous_principal();
errcode = krb5_encode_kdc_rep(kdc_context, KRB5_TGS_REP, &reply_encpart,
subkey ? 1 : 0,
reply_key,
&reply, response);
if (errcode) {
status = "ENCODE_KDC_REP";
} else {
status = "ISSUE";
}
memset(ticket_reply.enc_part.ciphertext.data, 0,
ticket_reply.enc_part.ciphertext.length);
free(ticket_reply.enc_part.ciphertext.data);
/* these parts are left on as a courtesy from krb5_encode_kdc_rep so we
can use them in raw form if needed. But, we don't... */
memset(reply.enc_part.ciphertext.data, 0,
reply.enc_part.ciphertext.length);
free(reply.enc_part.ciphertext.data);
cleanup:
assert(status != NULL);
if (reply_key)
krb5_free_keyblock(kdc_context, reply_key);
if (errcode)
emsg = krb5_get_error_message (kdc_context, errcode);
au_state->status = status;
if (!errcode)
au_state->reply = &reply;
kau_tgs_req(kdc_context, errcode ? FALSE : TRUE, au_state);
kau_free_kdc_req(au_state);
log_tgs_req(kdc_context, from, request, &reply, cprinc,
sprinc, altcprinc, authtime,
c_flags, status, errcode, emsg);
if (errcode) {
krb5_free_error_message (kdc_context, emsg);
emsg = NULL;
}
if (errcode) {
int got_err = 0;
if (status == 0) {
status = krb5_get_error_message (kdc_context, errcode);
got_err = 1;
}
errcode -= ERROR_TABLE_BASE_krb5;
if (errcode < 0 || errcode > KRB_ERR_MAX)
errcode = KRB_ERR_GENERIC;
retval = prepare_error_tgs(state, request, header_ticket, errcode,
(server != NULL) ? server->princ : NULL,
response, status, e_data);
if (got_err) {
krb5_free_error_message (kdc_context, status);
status = 0;
}
}
if (header_ticket != NULL)
krb5_free_ticket(kdc_context, header_ticket);
if (request != NULL)
krb5_free_kdc_req(kdc_context, request);
if (state)
kdc_free_rstate(state);
krb5_db_free_principal(kdc_context, server);
krb5_db_free_principal(kdc_context, stkt_server);
krb5_db_free_principal(kdc_context, header_server);
krb5_db_free_principal(kdc_context, client);
krb5_db_free_principal(kdc_context, local_tgt_storage);
if (session_key.contents != NULL)
krb5_free_keyblock_contents(kdc_context, &session_key);
if (newtransited)
free(enc_tkt_reply.transited.tr_contents.data);
if (s4u_x509_user != NULL)
krb5_free_pa_s4u_x509_user(kdc_context, s4u_x509_user);
if (kdc_issued_auth_data != NULL)
krb5_free_authdata(kdc_context, kdc_issued_auth_data);
if (subkey != NULL)
krb5_free_keyblock(kdc_context, subkey);
if (header_key != NULL)
krb5_free_keyblock(kdc_context, header_key);
if (reply.padata)
krb5_free_pa_data(kdc_context, reply.padata);
if (reply_encpart.enc_padata)
krb5_free_pa_data(kdc_context, reply_encpart.enc_padata);
if (enc_tkt_reply.authorization_data != NULL)
krb5_free_authdata(kdc_context, enc_tkt_reply.authorization_data);
krb5_free_pa_data(kdc_context, e_data);
k5_free_data_ptr_list(auth_indicators);
return retval;
}
Commit Message: Prevent KDC unset status assertion failures
Assign status values if S4U2Self padata fails to decode, if an
S4U2Proxy request uses invalid KDC options, or if an S4U2Proxy request
uses an evidence ticket which does not match the canonicalized request
server principal name. Reported by Samuel Cabrero.
If a status value is not assigned during KDC processing, default to
"UNKNOWN_REASON" rather than failing an assertion. This change will
prevent future denial of service bugs due to similar mistakes, and
will allow us to omit assigning status values for unlikely errors such
as small memory allocation failures.
CVE-2017-11368:
In MIT krb5 1.7 and later, an authenticated attacker can cause an
assertion failure in krb5kdc by sending an invalid S4U2Self or
S4U2Proxy request.
CVSSv3 Vector: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H/E:H/RL:O/RC:C
ticket: 8599 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-617
Target: 1
Example 2:
Code: static inline void php_register_server_variables(TSRMLS_D)
{
zval *array_ptr = NULL;
ALLOC_ZVAL(array_ptr);
array_init(array_ptr);
INIT_PZVAL(array_ptr);
if (PG(http_globals)[TRACK_VARS_SERVER]) {
zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_SERVER]);
}
PG(http_globals)[TRACK_VARS_SERVER] = array_ptr;
/* Server variables */
if (sapi_module.register_server_variables) {
sapi_module.register_server_variables(array_ptr TSRMLS_CC);
}
/* PHP Authentication support */
if (SG(request_info).auth_user) {
php_register_variable("PHP_AUTH_USER", SG(request_info).auth_user, array_ptr TSRMLS_CC);
}
if (SG(request_info).auth_password) {
php_register_variable("PHP_AUTH_PW", SG(request_info).auth_password, array_ptr TSRMLS_CC);
}
if (SG(request_info).auth_digest) {
php_register_variable("PHP_AUTH_DIGEST", SG(request_info).auth_digest, array_ptr TSRMLS_CC);
}
/* store request init time */
{
zval request_time_float, request_time_long;
Z_TYPE(request_time_float) = IS_DOUBLE;
Z_DVAL(request_time_float) = sapi_get_request_time(TSRMLS_C);
php_register_variable_ex("REQUEST_TIME_FLOAT", &request_time_float, array_ptr TSRMLS_CC);
Z_TYPE(request_time_long) = IS_LONG;
Z_LVAL(request_time_long) = zend_dval_to_lval(Z_DVAL(request_time_float));
php_register_variable_ex("REQUEST_TIME", &request_time_long, array_ptr TSRMLS_CC);
}
}
Commit Message: Fix bug #73807
CWE ID: CWE-400
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ResourcePtr<RawResource> ResourceFetcher::fetchRawResource(FetchRequest& request)
{
return toRawResource(requestResource(Resource::Raw, request));
}
Commit Message: Enforce SVG image security rules
SVG images have unique security rules that prevent them from loading
any external resources. This patch enforces these rules in
ResourceFetcher::canRequest for all non-data-uri resources. This locks
down our SVG resource handling and fixes two security bugs.
In the case of SVG images that reference other images, we had a bug
where a cached subresource would be used directly from the cache.
This has been fixed because the canRequest check occurs before we use
cached resources.
In the case of SVG images that use CSS imports, we had a bug where
imports were blindly requested. This has been fixed by stopping all
non-data-uri requests in SVG images.
With this patch we now match Gecko's behavior on both testcases.
BUG=380885, 382296
Review URL: https://codereview.chromium.org/320763002
git-svn-id: svn://svn.chromium.org/blink/trunk@176084 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag,
uint32_t lun, void *hba_private)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
SCSIRequest *req;
SCSIDiskReq *r;
req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);
r = DO_UPCAST(SCSIDiskReq, req, req);
r->iov.iov_base = qemu_blockalign(s->bs, SCSI_DMA_BUF_SIZE);
return req;
}
Commit Message: scsi-disk: lazily allocate bounce buffer
It will not be needed for reads and writes if the HBA provides a sglist.
In addition, this lets scsi-disk refuse commands with an excessive
allocation length, as well as limit memory on usual well-behaved guests.
Signed-off-by: Paolo Bonzini <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: CStarter::WriteRecoveryFile( ClassAd *recovery_ad )
{
MyString tmp_file;
FILE *tmp_fp;
if ( recovery_ad == NULL ) {
return;
}
if ( m_recoveryFile.Length() == 0 ) {
m_recoveryFile.sprintf( "%s%cdir_%ld.recover", Execute,
DIR_DELIM_CHAR, (long)daemonCore->getpid() );
}
tmp_file.sprintf( "%s.tmp", m_recoveryFile.Value() );
tmp_fp = safe_fcreate_replace_if_exists( tmp_file.Value(), "w" );
if ( tmp_fp == NULL ) {
dprintf( D_ALWAYS, "Failed to open recovery file %s\n", tmp_file.Value() );
return;
}
if ( recovery_ad->fPrint( tmp_fp ) == FALSE ) {
dprintf( D_ALWAYS, "Failed to write recovery file\n" );
fclose( tmp_fp );
return;
}
if ( fclose( tmp_fp ) != 0 ) {
dprintf( D_ALWAYS, "Failed close recovery file\n" );
unlink( tmp_file.Value() );
return;
}
if ( rotate_file( tmp_file.Value(), m_recoveryFile.Value() ) != 0 ) {
dprintf( D_ALWAYS, "Failed to rename recovery file\n" );
unlink( tmp_file.Value() );
}
}
Commit Message:
CWE ID: CWE-134
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static HB_Error Lookup_MarkMarkPos( GPOS_Instance* gpi,
HB_GPOS_SubTable* st,
HB_Buffer buffer,
HB_UShort flags,
HB_UShort context_length,
int nesting_level )
{
HB_UShort i, j, mark1_index, mark2_index, property, class;
HB_Fixed x_mark1_value, y_mark1_value,
x_mark2_value, y_mark2_value;
HB_Error error;
HB_GPOSHeader* gpos = gpi->gpos;
HB_MarkMarkPos* mmp = &st->markmark;
HB_MarkArray* ma1;
HB_Mark2Array* ma2;
HB_Mark2Record* m2r;
HB_Anchor* mark1_anchor;
HB_Anchor* mark2_anchor;
HB_Position o;
HB_UNUSED(nesting_level);
if ( context_length != 0xFFFF && context_length < 1 )
return HB_Err_Not_Covered;
if ( flags & HB_LOOKUP_FLAG_IGNORE_MARKS )
return HB_Err_Not_Covered;
if ( CHECK_Property( gpos->gdef, IN_CURITEM(),
flags, &property ) )
return error;
error = _HB_OPEN_Coverage_Index( &mmp->Mark1Coverage, IN_CURGLYPH(),
&mark1_index );
if ( error )
return error;
/* now we search backwards for a suitable mark glyph until a non-mark
glyph */
if ( buffer->in_pos == 0 )
return HB_Err_Not_Covered;
i = 1;
j = buffer->in_pos - 1;
while ( i <= buffer->in_pos )
{
error = HB_GDEF_Get_Glyph_Property( gpos->gdef, IN_GLYPH( j ),
&property );
if ( error )
return error;
if ( !( property == HB_GDEF_MARK || property & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS ) )
return HB_Err_Not_Covered;
if ( flags & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS )
{
if ( property == (flags & 0xFF00) )
break;
}
else
break;
i++;
j--;
}
error = _HB_OPEN_Coverage_Index( &mmp->Mark2Coverage, IN_GLYPH( j ),
&mark2_index );
if ( error )
if ( mark1_index >= ma1->MarkCount )
return ERR(HB_Err_Invalid_SubTable);
class = ma1->MarkRecord[mark1_index].Class;
mark1_anchor = &ma1->MarkRecord[mark1_index].MarkAnchor;
if ( class >= mmp->ClassCount )
return ERR(HB_Err_Invalid_SubTable);
ma2 = &mmp->Mark2Array;
if ( mark2_index >= ma2->Mark2Count )
return ERR(HB_Err_Invalid_SubTable);
m2r = &ma2->Mark2Record[mark2_index];
mark2_anchor = &m2r->Mark2Anchor[class];
error = Get_Anchor( gpi, mark1_anchor, IN_CURGLYPH(),
&x_mark1_value, &y_mark1_value );
if ( error )
return error;
error = Get_Anchor( gpi, mark2_anchor, IN_GLYPH( j ),
&x_mark2_value, &y_mark2_value );
if ( error )
return error;
/* anchor points are not cumulative */
o = POSITION( buffer->in_pos );
o->x_pos = x_mark2_value - x_mark1_value;
o->y_pos = y_mark2_value - y_mark1_value;
o->x_advance = 0;
o->y_advance = 0;
o->back = 1;
(buffer->in_pos)++;
return HB_Err_Ok;
}
Commit Message:
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: P2PQuicStreamImpl::P2PQuicStreamImpl(quic::QuicStreamId id,
quic::QuicSession* session)
: quic::QuicStream(id, session, /*is_static=*/false, quic::BIDIRECTIONAL) {}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <[email protected]>
Reviewed-by: Henrik Boström <[email protected]>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284
Target: 1
Example 2:
Code: void NavigatorImpl::RequestTransferURL(
RenderFrameHostImpl* render_frame_host,
const GURL& url,
SiteInstance* source_site_instance,
const std::vector<GURL>& redirect_chain,
const Referrer& referrer,
ui::PageTransition page_transition,
const GlobalRequestID& transferred_global_request_id,
bool should_replace_current_entry,
const std::string& method,
scoped_refptr<ResourceRequestBodyImpl> post_body,
const std::string& extra_headers) {
if (method != "POST" && post_body) {
NOTREACHED();
post_body = nullptr;
}
DCHECK(!render_frame_host->GetParent() ||
SiteIsolationPolicy::AreCrossProcessFramesPossible());
if (!delegate_->ShouldTransferNavigation(
render_frame_host->frame_tree_node()->IsMainFrame()))
return;
GURL dest_url(url);
Referrer referrer_to_use(referrer);
FrameTreeNode* node = render_frame_host->frame_tree_node();
SiteInstance* current_site_instance = render_frame_host->GetSiteInstance();
if (!GetContentClient()->browser()->ShouldAllowOpenURL(current_site_instance,
url)) {
dest_url = GURL(url::kAboutBlankURL);
}
bool is_renderer_initiated = true;
if (render_frame_host->web_ui()) {
if (ui::PageTransitionCoreTypeIs(page_transition, ui::PAGE_TRANSITION_LINK))
page_transition = render_frame_host->web_ui()->GetLinkTransitionType();
referrer_to_use = Referrer();
is_renderer_initiated = false;
}
std::unique_ptr<NavigationEntryImpl> entry;
if (!node->IsMainFrame()) {
CHECK(SiteIsolationPolicy::UseSubframeNavigationEntries());
if (controller_->GetLastCommittedEntry()) {
entry = controller_->GetLastCommittedEntry()->Clone();
entry->set_extra_headers(extra_headers);
} else {
entry = NavigationEntryImpl::FromNavigationEntry(
controller_->CreateNavigationEntry(
GURL(url::kAboutBlankURL), referrer_to_use, page_transition,
is_renderer_initiated, extra_headers,
controller_->GetBrowserContext()));
}
entry->AddOrUpdateFrameEntry(
node, -1, -1, nullptr,
static_cast<SiteInstanceImpl*>(source_site_instance),
dest_url, referrer_to_use, redirect_chain, PageState(), method,
-1);
} else {
entry = NavigationEntryImpl::FromNavigationEntry(
controller_->CreateNavigationEntry(
dest_url, referrer_to_use, page_transition, is_renderer_initiated,
extra_headers, controller_->GetBrowserContext()));
entry->root_node()->frame_entry->set_source_site_instance(
static_cast<SiteInstanceImpl*>(source_site_instance));
entry->SetRedirectChain(redirect_chain);
}
if (should_replace_current_entry && controller_->GetEntryCount() > 0)
entry->set_should_replace_entry(true);
if (controller_->GetLastCommittedEntry() &&
controller_->GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
entry->SetIsOverridingUserAgent(true);
}
entry->set_transferred_global_request_id(transferred_global_request_id);
scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
if (!frame_entry) {
frame_entry = new FrameNavigationEntry(
node->unique_name(), -1, -1, nullptr,
static_cast<SiteInstanceImpl*>(source_site_instance), dest_url,
referrer_to_use, method, -1);
}
NavigateToEntry(node, *frame_entry, *entry.get(), ReloadType::NONE, false,
false, false, post_body);
}
Commit Message: Drop navigations to NavigationEntry with invalid virtual URLs.
BUG=657720
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2452443002
Cr-Commit-Position: refs/heads/master@{#428056}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int __ext4_journal_stop(const char *where, unsigned int line, handle_t *handle)
{
struct super_block *sb;
int err;
int rc;
if (!ext4_handle_valid(handle)) {
ext4_put_nojournal(handle);
return 0;
}
if (!handle->h_transaction) {
err = jbd2_journal_stop(handle);
return handle->h_err ? handle->h_err : err;
}
sb = handle->h_transaction->t_journal->j_private;
err = handle->h_err;
rc = jbd2_journal_stop(handle);
if (!err)
err = rc;
if (err)
__ext4_std_error(sb, where, line, err);
return err;
}
Commit Message: ext4: fix potential use after free in __ext4_journal_stop
There is a use-after-free possibility in __ext4_journal_stop() in the
case that we free the handle in the first jbd2_journal_stop() because
we're referencing handle->h_err afterwards. This was introduced in
9705acd63b125dee8b15c705216d7186daea4625 and it is wrong. Fix it by
storing the handle->h_err value beforehand and avoid referencing
potentially freed handle.
Fixes: 9705acd63b125dee8b15c705216d7186daea4625
Signed-off-by: Lukas Czerner <[email protected]>
Reviewed-by: Andreas Dilger <[email protected]>
Cc: [email protected]
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int mwifiex_update_vs_ie(const u8 *ies, int ies_len,
struct mwifiex_ie **ie_ptr, u16 mask,
unsigned int oui, u8 oui_type)
{
struct ieee_types_header *vs_ie;
struct mwifiex_ie *ie = *ie_ptr;
const u8 *vendor_ie;
vendor_ie = cfg80211_find_vendor_ie(oui, oui_type, ies, ies_len);
if (vendor_ie) {
if (!*ie_ptr) {
*ie_ptr = kzalloc(sizeof(struct mwifiex_ie),
GFP_KERNEL);
if (!*ie_ptr)
return -ENOMEM;
ie = *ie_ptr;
}
vs_ie = (struct ieee_types_header *)vendor_ie;
memcpy(ie->ie_buffer + le16_to_cpu(ie->ie_length),
vs_ie, vs_ie->len + 2);
le16_unaligned_add_cpu(&ie->ie_length, vs_ie->len + 2);
ie->mgmt_subtype_mask = cpu_to_le16(mask);
ie->ie_index = cpu_to_le16(MWIFIEX_AUTO_IDX_MASK);
}
*ie_ptr = ie;
return 0;
}
Commit Message: mwifiex: Fix three heap overflow at parsing element in cfg80211_ap_settings
mwifiex_update_vs_ie(),mwifiex_set_uap_rates() and
mwifiex_set_wmm_params() call memcpy() without checking
the destination size.Since the source is given from
user-space, this may trigger a heap buffer overflow.
Fix them by putting the length check before performing memcpy().
This fix addresses CVE-2019-14814,CVE-2019-14815,CVE-2019-14816.
Signed-off-by: Wen Huang <[email protected]>
Acked-by: Ganapathi Bhat <[email protected]>
Signed-off-by: Kalle Valo <[email protected]>
CWE ID: CWE-120
Target: 1
Example 2:
Code: RTCPeerConnectionHandler::RTCPeerConnectionHandler(
blink::WebRTCPeerConnectionHandlerClient* client,
PeerConnectionDependencyFactory* dependency_factory,
scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: id_(base::ToUpperASCII(base::UnguessableToken::Create().ToString())),
initialize_called_(false),
client_(client),
is_closed_(false),
dependency_factory_(dependency_factory),
track_adapter_map_(
new WebRtcMediaStreamTrackAdapterMap(dependency_factory_,
task_runner)),
task_runner_(std::move(task_runner)),
weak_factory_(this) {
CHECK(client_);
GetPeerConnectionHandlers()->insert(this);
}
Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl
Bug: 912074
Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8
Reviewed-on: https://chromium-review.googlesource.com/c/1411916
Commit-Queue: Guido Urdaneta <[email protected]>
Reviewed-by: Henrik Boström <[email protected]>
Cr-Commit-Position: refs/heads/master@{#622945}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void VRDisplay::OnDisconnected() {
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
EventTypeNames::vrdisplaydisconnect, true, false, this, "disconnect"));
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BrowserCommandController::RemoveInterstitialObservers(
TabContents* contents) {
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED,
content::Source<WebContents>(contents->web_contents()));
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_DETACHED,
content::Source<WebContents>(contents->web_contents()));
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 1
Example 2:
Code: void skb_tstamp_tx(struct sk_buff *orig_skb,
struct skb_shared_hwtstamps *hwtstamps)
{
return __skb_tstamp_tx(orig_skb, hwtstamps, orig_skb->sk,
SCM_TSTAMP_SND);
}
Commit Message: tcp: fix SCM_TIMESTAMPING_OPT_STATS for normal skbs
__sock_recv_timestamp can be called for both normal skbs (for
receive timestamps) and for skbs on the error queue (for transmit
timestamps).
Commit 1c885808e456
(tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING)
assumes any skb passed to __sock_recv_timestamp are from
the error queue, containing OPT_STATS in the content of the skb.
This results in accessing invalid memory or generating junk
data.
To fix this, set skb->pkt_type to PACKET_OUTGOING for packets
on the error queue. This is safe because on the receive path
on local sockets skb->pkt_type is never set to PACKET_OUTGOING.
With that, copy OPT_STATS from a packet, only if its pkt_type
is PACKET_OUTGOING.
Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING")
Reported-by: JongHwan Kim <[email protected]>
Signed-off-by: Soheil Hassas Yeganeh <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: Willem de Bruijn <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void TestProcessOverflow() {
int tab_count = 1;
int host_count = 1;
WebContents* tab1 = NULL;
WebContents* tab2 = NULL;
content::RenderProcessHost* rph1 = NULL;
content::RenderProcessHost* rph2 = NULL;
content::RenderProcessHost* rph3 = NULL;
const extensions::Extension* extension =
LoadExtension(test_data_dir_.AppendASCII("options_page"));
GURL omnibox(chrome::kChromeUIOmniboxURL);
ui_test_utils::NavigateToURL(browser(), omnibox);
EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());
tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);
rph1 = tab1->GetMainFrame()->GetProcess();
EXPECT_EQ(omnibox, tab1->GetURL());
EXPECT_EQ(host_count, RenderProcessHostCount());
GURL page1("data:text/html,hello world1");
ui_test_utils::WindowedTabAddedNotificationObserver observer1(
content::NotificationService::AllSources());
::ShowSingletonTab(browser(), page1);
observer1.Wait();
tab_count++;
host_count++;
EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());
tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);
rph2 = tab1->GetMainFrame()->GetProcess();
EXPECT_EQ(tab1->GetURL(), page1);
EXPECT_EQ(host_count, RenderProcessHostCount());
EXPECT_NE(rph1, rph2);
GURL page2("data:text/html,hello world2");
ui_test_utils::WindowedTabAddedNotificationObserver observer2(
content::NotificationService::AllSources());
::ShowSingletonTab(browser(), page2);
observer2.Wait();
tab_count++;
if (content::AreAllSitesIsolatedForTesting())
host_count++;
EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());
tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);
EXPECT_EQ(tab2->GetURL(), page2);
EXPECT_EQ(host_count, RenderProcessHostCount());
if (content::AreAllSitesIsolatedForTesting())
EXPECT_NE(tab2->GetMainFrame()->GetProcess(), rph2);
else
EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph2);
GURL history(chrome::kChromeUIHistoryURL);
ui_test_utils::WindowedTabAddedNotificationObserver observer3(
content::NotificationService::AllSources());
::ShowSingletonTab(browser(), history);
observer3.Wait();
tab_count++;
EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());
tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);
EXPECT_EQ(tab2->GetURL(), GURL(history));
EXPECT_EQ(host_count, RenderProcessHostCount());
EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph1);
GURL extension_url("chrome-extension://" + extension->id());
ui_test_utils::WindowedTabAddedNotificationObserver observer4(
content::NotificationService::AllSources());
::ShowSingletonTab(browser(), extension_url);
observer4.Wait();
tab_count++;
host_count++;
EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());
tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);
rph3 = tab1->GetMainFrame()->GetProcess();
EXPECT_EQ(tab1->GetURL(), extension_url);
EXPECT_EQ(host_count, RenderProcessHostCount());
EXPECT_NE(rph1, rph3);
EXPECT_NE(rph2, rph3);
}
Commit Message: Allow origin lock for WebUI pages.
Returning true for WebUI pages in DoesSiteRequireDedicatedProcess helps
to keep enforcing a SiteInstance swap during chrome://foo ->
chrome://bar navigation, even after relaxing
BrowsingInstance::GetSiteInstanceForURL to consider RPH::IsSuitableHost
(see https://crrev.com/c/783470 for that fixes process sharing in
isolated(b(c),d(c)) scenario).
I've manually tested this CL by visiting the following URLs:
- chrome://welcome/
- chrome://settings
- chrome://extensions
- chrome://history
- chrome://help and chrome://chrome (both redirect to chrome://settings/help)
Bug: 510588, 847127
Change-Id: I55073bce00f32cb8bc5c1c91034438ff9a3f8971
Reviewed-on: https://chromium-review.googlesource.com/1237392
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: François Doray <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#595259}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline int unicode_cp_is_allowed(unsigned uni_cp, int document_type)
{
/* XML 1.0 HTML 4.01 HTML 5
* 0x09..0x0A 0x09..0x0A 0x09..0x0A
* 0x0D 0x0D 0x0C..0x0D
* 0x0020..0xD7FF 0x20..0x7E 0x20..0x7E
* 0x00A0..0xD7FF 0x00A0..0xD7FF
* 0xE000..0xFFFD 0xE000..0x10FFFF 0xE000..0xFDCF
* 0x010000..0x10FFFF 0xFDF0..0x10FFFF (*)
*
* (*) exclude code points where ((code & 0xFFFF) >= 0xFFFE)
*
* References:
* XML 1.0: <http://www.w3.org/TR/REC-xml/#charsets>
* HTML 4.01: <http://www.w3.org/TR/1999/PR-html40-19990824/sgml/sgmldecl.html>
* HTML 5: <http://dev.w3.org/html5/spec/Overview.html#preprocessing-the-input-stream>
*
* Not sure this is the relevant part for HTML 5, though. I opted to
* disallow the characters that would result in a parse error when
* preprocessing of the input stream. See also section 8.1.3.
*
* It's unclear if XHTML 1.0 allows C1 characters. I'll opt to apply to
* XHTML 1.0 the same rules as for XML 1.0.
* See <http://cmsmcq.com/2007/C1.xml>.
*/
switch (document_type) {
case ENT_HTML_DOC_HTML401:
return (uni_cp >= 0x20 && uni_cp <= 0x7E) ||
(uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) ||
(uni_cp >= 0xA0 && uni_cp <= 0xD7FF) ||
(uni_cp >= 0xE000 && uni_cp <= 0x10FFFF);
case ENT_HTML_DOC_HTML5:
return (uni_cp >= 0x20 && uni_cp <= 0x7E) ||
(uni_cp >= 0x09 && uni_cp <= 0x0D && uni_cp != 0x0B) || /* form feed U+0C allowed */
(uni_cp >= 0xA0 && uni_cp <= 0xD7FF) ||
(uni_cp >= 0xE000 && uni_cp <= 0x10FFFF &&
((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */
(uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */
case ENT_HTML_DOC_XHTML:
case ENT_HTML_DOC_XML1:
return (uni_cp >= 0x20 && uni_cp <= 0xD7FF) ||
(uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) ||
(uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && uni_cp != 0xFFFE && uni_cp != 0xFFFF);
default:
return 1;
}
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190
Target: 1
Example 2:
Code: int out_bounce_conn_queues(conn_t out, int err)
{
char *rkey;
int rkeylen;
int pktcount = 0;
/* bounce queues for all domains handled by this connection - iterate through routes */
if (xhash_iter_first(out->routes)) {
do {
xhash_iter_get(out->routes, (const char **) &rkey, &rkeylen, NULL);
pktcount += out_bounce_route_queue(out->s2s, rkey, rkeylen, err);
} while(xhash_iter_next(out->routes));
}
return pktcount;
}
Commit Message: Fixed possibility of Unsolicited Dialback Attacks
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: GURL DevToolsWindow::GetDevToolsURL(Profile* profile,
const GURL& base_url,
bool shared_worker_frontend,
bool v8_only_frontend,
const std::string& remote_frontend,
bool can_dock,
const std::string& panel) {
if (base_url.SchemeIs("data"))
return base_url;
std::string frontend_url(
!remote_frontend.empty() ?
remote_frontend :
base_url.is_empty() ? chrome::kChromeUIDevToolsURL : base_url.spec());
std::string url_string(
frontend_url +
((frontend_url.find("?") == std::string::npos) ? "?" : "&"));
if (shared_worker_frontend)
url_string += "&isSharedWorker=true";
if (v8_only_frontend)
url_string += "&v8only=true";
if (remote_frontend.size()) {
url_string += "&remoteFrontend=true";
} else {
url_string += "&remoteBase=" + DevToolsUI::GetRemoteBaseURL().spec();
}
if (can_dock)
url_string += "&can_dock=true";
if (panel.size())
url_string += "&panel=" + panel;
return DevToolsUI::SanitizeFrontendURL(GURL(url_string));
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void _out_result(conn_t out, nad_t nad) {
int attr;
jid_t from, to;
char *rkey;
int rkeylen;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db result packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db result packet");
jid_free(from);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
rkeylen = strlen(rkey);
/* key is valid */
if(nad_find_attr(nad, 0, -1, "type", "valid") >= 0) {
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now valid%s%s", out->fd->fd, out->ip, out->port, rkey, (out->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", out->s->compressed ? ", ZLIB compression enabled" : "");
xhash_put(out->states, pstrdup(xhash_pool(out->states), rkey), (void *) conn_VALID); /* !!! small leak here */
log_debug(ZONE, "%s valid, flushing queue", rkey);
/* flush the queue */
out_flush_route_queue(out->s2s, rkey, rkeylen);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* invalid */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now invalid", out->fd->fd, out->ip, out->port, rkey);
/* close connection */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] closing connection", out->fd->fd, out->ip, out->port);
/* report stream error */
sx_error(out->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the stream */
sx_close(out->s);
/* bounce queue */
out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
}
Commit Message: Fixed possibility of Unsolicited Dialback Attacks
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int softnet_seq_show(struct seq_file *seq, void *v)
{
struct netif_rx_stats *s = v;
seq_printf(seq, "%08x %08x %08x %08x %08x %08x %08x %08x %08x\n",
s->total, s->dropped, s->time_squeeze, 0,
0, 0, 0, 0, /* was fastroute */
s->cpu_collision);
return 0;
}
Commit Message: veth: Dont kfree_skb() after dev_forward_skb()
In case of congestion, netif_rx() frees the skb, so we must assume
dev_forward_skb() also consume skb.
Bug introduced by commit 445409602c092
(veth: move loopback logic to common location)
We must change dev_forward_skb() to always consume skb, and veth to not
double free it.
Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3
Reported-by: Martín Ferrari <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int proc_test_super(struct super_block *sb, void *data)
{
return sb->s_fs_info == data;
}
Commit Message: procfs: fix a vfsmount longterm reference leak
kern_mount() doesn't pair with plain mntput()...
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ClipPaintPropertyNode* ClipPaintPropertyNode::Root() {
DEFINE_STATIC_REF(
ClipPaintPropertyNode, root,
(ClipPaintPropertyNode::Create(
nullptr, State{TransformPaintPropertyNode::Root(),
FloatRoundedRect(LayoutRect::InfiniteIntRect())})));
return root;
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID:
Target: 1
Example 2:
Code: int dom_document_version_write(dom_object *obj, zval *newval TSRMLS_DC)
{
zval value_copy;
xmlDoc *docp;
docp = (xmlDocPtr) dom_object_get_node(obj);
if (docp == NULL) {
php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC);
return FAILURE;
}
if (docp->version != NULL) {
xmlFree((xmlChar *) docp->version );
}
if (newval->type != IS_STRING) {
if(Z_REFCOUNT_P(newval) > 1) {
value_copy = *newval;
zval_copy_ctor(&value_copy);
newval = &value_copy;
}
convert_to_string(newval);
}
docp->version = xmlStrdup((const xmlChar *) Z_STRVAL_P(newval));
if (newval == &value_copy) {
zval_dtor(newval);
}
return SUCCESS;
}
Commit Message:
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt,
uint8_t* buf, int buf_size)
{
int size, i;
uint8_t *ppcm[4] = {0};
if (buf_size < DV_PROFILE_BYTES ||
!(c->sys = avpriv_dv_frame_profile(c->sys, buf, buf_size)) ||
buf_size < c->sys->frame_size) {
return -1; /* Broken frame, or not enough data */
}
/* Queueing audio packet */
/* FIXME: in case of no audio/bad audio we have to do something */
size = dv_extract_audio_info(c, buf);
for (i = 0; i < c->ach; i++) {
c->audio_pkt[i].size = size;
c->audio_pkt[i].pts = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate;
ppcm[i] = c->audio_buf[i];
}
dv_extract_audio(buf, ppcm, c->sys);
/* We work with 720p frames split in half, thus even frames have
* channels 0,1 and odd 2,3. */
if (buf[1] & 0x0C) {
c->audio_pkt[2].size = c->audio_pkt[3].size = 0;
} else {
c->audio_pkt[0].size = c->audio_pkt[1].size = 0;
c->abytes += size;
}
} else {
c->abytes += size;
}
Commit Message:
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PluginChannel::~PluginChannel() {
if (renderer_handle_)
base::CloseProcessHandle(renderer_handle_);
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&PluginReleaseCallback),
base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes));
}
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:
Target: 1
Example 2:
Code: bool Editor::Command::IsSupported() const {
if (!command_)
return false;
switch (source_) {
case kCommandFromMenuOrKeyBinding:
return true;
case kCommandFromDOM:
return command_->is_supported_from_dom(frame_.Get());
}
NOTREACHED();
return false;
}
Commit Message: Move Editor::Transpose() out of Editor class
This patch moves |Editor::Transpose()| out of |Editor| class as preparation of
expanding it into |ExecutTranspose()| in "EditorCommand.cpp" to make |Editor|
class simpler for improving code health.
Following patch will expand |Transpose()| into |ExecutTranspose()|.
Bug: 672405
Change-Id: Icde253623f31813d2b4517c4da7d4798bd5fadf6
Reviewed-on: https://chromium-review.googlesource.com/583880
Reviewed-by: Xiaocheng Hu <[email protected]>
Commit-Queue: Yoshifumi Inoue <[email protected]>
Cr-Commit-Position: refs/heads/master@{#489518}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PHP_FUNCTION(imageloadfont)
{
char *file;
int file_name, hdr_size = sizeof(gdFont) - sizeof(char *);
int ind, body_size, n = 0, b, i, body_size_check;
gdFontPtr font;
php_stream *stream;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &file, &file_name) == FAILURE) {
return;
}
stream = php_stream_open_wrapper(file, "rb", IGNORE_PATH | IGNORE_URL_WIN | REPORT_ERRORS, NULL);
if (stream == NULL) {
RETURN_FALSE;
}
/* Only supports a architecture-dependent binary dump format
* at the moment.
* The file format is like this on machines with 32-byte integers:
*
* byte 0-3: (int) number of characters in the font
* byte 4-7: (int) value of first character in the font (often 32, space)
* byte 8-11: (int) pixel width of each character
* byte 12-15: (int) pixel height of each character
* bytes 16-: (char) array with character data, one byte per pixel
* in each character, for a total of
* (nchars*width*height) bytes.
*/
font = (gdFontPtr) emalloc(sizeof(gdFont));
b = 0;
while (b < hdr_size && (n = php_stream_read(stream, (char*)&font[b], hdr_size - b))) {
b += n;
}
if (!n) {
efree(font);
if (php_stream_eof(stream)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading header");
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading header");
}
php_stream_close(stream);
RETURN_FALSE;
}
i = php_stream_tell(stream);
php_stream_seek(stream, 0, SEEK_END);
body_size_check = php_stream_tell(stream) - hdr_size;
php_stream_seek(stream, i, SEEK_SET);
body_size = font->w * font->h * font->nchars;
if (body_size != body_size_check) {
font->w = FLIPWORD(font->w);
font->h = FLIPWORD(font->h);
font->nchars = FLIPWORD(font->nchars);
body_size = font->w * font->h * font->nchars;
}
if (overflow2(font->nchars, font->h)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font, invalid font header");
efree(font);
php_stream_close(stream);
RETURN_FALSE;
}
if (overflow2(font->nchars * font->h, font->w )) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font, invalid font header");
efree(font);
php_stream_close(stream);
RETURN_FALSE;
}
if (body_size != body_size_check) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font");
efree(font);
php_stream_close(stream);
RETURN_FALSE;
}
font->data = emalloc(body_size);
b = 0;
while (b < body_size && (n = php_stream_read(stream, &font->data[b], body_size - b))) {
b += n;
}
if (!n) {
efree(font->data);
efree(font);
if (php_stream_eof(stream)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading body");
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading body");
}
php_stream_close(stream);
RETURN_FALSE;
}
php_stream_close(stream);
/* Adding 5 to the font index so we will never have font indices
* that overlap with the old fonts (with indices 1-5). The first
* list index given out is always 1.
*/
ind = 5 + zend_list_insert(font, le_gd_font TSRMLS_CC);
RETURN_LONG(ind);
}
Commit Message:
CWE ID: CWE-254
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline signed short ReadPropertySignedShort(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) ((buffer[1] << 8) | buffer[0]);
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) |
((unsigned char *) buffer)[1]);
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125
Target: 1
Example 2:
Code: gst_asf_demux_handle_seek_event (GstASFDemux * demux, GstEvent * event)
{
GstClockTime idx_time;
GstSegment segment;
GstSeekFlags flags;
GstSeekType cur_type, stop_type;
GstFormat format;
gboolean only_need_update;
gboolean after, before, next;
gboolean flush;
gdouble rate;
gint64 cur, stop;
gint64 seek_time;
guint packet, speed_count = 1;
gboolean eos;
guint32 seqnum;
GstEvent *fevent;
gint i;
gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
&stop_type, &stop);
if (G_UNLIKELY (format != GST_FORMAT_TIME)) {
GST_LOG_OBJECT (demux, "seeking is only supported in TIME format");
return FALSE;
}
/* upstream might handle TIME seek, e.g. mms or rtsp, or not, e.g. http,
* so first try to let it handle the seek event. */
if (gst_pad_push_event (demux->sinkpad, gst_event_ref (event)))
return TRUE;
if (G_UNLIKELY (demux->seekable == FALSE || demux->packet_size == 0 ||
demux->num_packets == 0 || demux->play_time == 0)) {
GST_LOG_OBJECT (demux, "stream is not seekable");
return FALSE;
}
if (G_UNLIKELY (!demux->activated_streams)) {
GST_LOG_OBJECT (demux, "streams not yet activated, ignoring seek");
return FALSE;
}
if (G_UNLIKELY (rate <= 0.0)) {
GST_LOG_OBJECT (demux, "backward playback");
demux->seek_to_cur_pos = TRUE;
for (i = 0; i < demux->num_streams; i++) {
demux->stream[i].reverse_kf_ready = FALSE;
}
}
seqnum = gst_event_get_seqnum (event);
flush = ((flags & GST_SEEK_FLAG_FLUSH) == GST_SEEK_FLAG_FLUSH);
demux->accurate =
((flags & GST_SEEK_FLAG_ACCURATE) == GST_SEEK_FLAG_ACCURATE);
demux->keyunit_sync =
((flags & GST_SEEK_FLAG_KEY_UNIT) == GST_SEEK_FLAG_KEY_UNIT);
after = ((flags & GST_SEEK_FLAG_SNAP_AFTER) == GST_SEEK_FLAG_SNAP_AFTER);
before = ((flags & GST_SEEK_FLAG_SNAP_BEFORE) == GST_SEEK_FLAG_SNAP_BEFORE);
next = after && !before;
if (G_UNLIKELY (demux->streaming)) {
/* support it safely needs more segment handling, e.g. closing etc */
if (!flush) {
GST_LOG_OBJECT (demux, "streaming; non-flushing seek not supported");
return FALSE;
}
/* we can (re)construct the start later on, but not the end */
if (stop_type != GST_SEEK_TYPE_NONE &&
(stop_type != GST_SEEK_TYPE_SET || GST_CLOCK_TIME_IS_VALID (stop))) {
GST_LOG_OBJECT (demux, "streaming; end position must be NONE");
return FALSE;
}
return gst_asf_demux_handle_seek_push (demux, event);
}
/* unlock the streaming thread */
if (G_LIKELY (flush)) {
fevent = gst_event_new_flush_start ();
gst_event_set_seqnum (fevent, seqnum);
gst_pad_push_event (demux->sinkpad, gst_event_ref (fevent));
gst_asf_demux_send_event_unlocked (demux, fevent);
} else {
gst_pad_pause_task (demux->sinkpad);
}
/* grab the stream lock so that streaming cannot continue, for
* non flushing seeks when the element is in PAUSED this could block
* forever */
GST_PAD_STREAM_LOCK (demux->sinkpad);
/* we now can stop flushing, since we have the stream lock now */
fevent = gst_event_new_flush_stop (TRUE);
gst_event_set_seqnum (fevent, seqnum);
gst_pad_push_event (demux->sinkpad, gst_event_ref (fevent));
if (G_LIKELY (flush))
gst_asf_demux_send_event_unlocked (demux, fevent);
else
gst_event_unref (fevent);
/* operating on copy of segment until we know the seek worked */
segment = demux->segment;
if (G_UNLIKELY (demux->segment_running && !flush)) {
GstSegment newsegment;
GstEvent *newseg;
/* create the segment event to close the current segment */
gst_segment_copy_into (&segment, &newsegment);
newseg = gst_event_new_segment (&newsegment);
gst_event_set_seqnum (newseg, seqnum);
gst_asf_demux_send_event_unlocked (demux, newseg);
}
gst_segment_do_seek (&segment, rate, format, flags, cur_type,
cur, stop_type, stop, &only_need_update);
GST_DEBUG_OBJECT (demux, "seeking to time %" GST_TIME_FORMAT ", segment: "
"%" GST_SEGMENT_FORMAT, GST_TIME_ARGS (segment.start), &segment);
if (cur_type != GST_SEEK_TYPE_SET)
seek_time = segment.start;
else
seek_time = cur;
/* FIXME: should check the KEY_UNIT flag; need to adjust position to
* real start of data and segment_start to indexed time for key unit seek*/
if (G_UNLIKELY (!gst_asf_demux_seek_index_lookup (demux, &packet, seek_time,
&idx_time, &speed_count, next, &eos))) {
gint64 offset;
if (eos) {
demux->packet = demux->num_packets;
goto skip;
}
/* First try to query our source to see if it can convert for us. This is
the case when our source is an mms stream, notice that in this case
gstmms will do a time based seek to get the byte offset, this is not a
problem as the seek to this offset needs to happen anway. */
if (gst_pad_peer_query_convert (demux->sinkpad, GST_FORMAT_TIME, seek_time,
GST_FORMAT_BYTES, &offset)) {
packet = (offset - demux->data_offset) / demux->packet_size;
GST_LOG_OBJECT (demux, "convert %" GST_TIME_FORMAT
" to bytes query result: %" G_GINT64_FORMAT ", data_ofset: %"
G_GINT64_FORMAT ", packet_size: %u," " resulting packet: %u\n",
GST_TIME_ARGS (seek_time), offset, demux->data_offset,
demux->packet_size, packet);
} else {
/* FIXME: For streams containing video, seek to an earlier position in
* the hope of hitting a keyframe and let the sinks throw away the stuff
* before the segment start. For audio-only this is unnecessary as every
* frame is 'key'. */
if (flush && (demux->accurate || (demux->keyunit_sync && !next))
&& demux->num_video_streams > 0) {
seek_time -= 5 * GST_SECOND;
if (seek_time < 0)
seek_time = 0;
}
packet = (guint) gst_util_uint64_scale (demux->num_packets,
seek_time, demux->play_time);
if (packet > demux->num_packets)
packet = demux->num_packets;
}
} else {
if (G_LIKELY (demux->keyunit_sync && !demux->accurate)) {
GST_DEBUG_OBJECT (demux, "key unit seek, adjust seek_time = %"
GST_TIME_FORMAT " to index_time = %" GST_TIME_FORMAT,
GST_TIME_ARGS (seek_time), GST_TIME_ARGS (idx_time));
segment.start = idx_time;
segment.position = idx_time;
segment.time = idx_time;
}
}
GST_DEBUG_OBJECT (demux, "seeking to packet %u (%d)", packet, speed_count);
GST_OBJECT_LOCK (demux);
demux->segment = segment;
if (GST_ASF_DEMUX_IS_REVERSE_PLAYBACK (demux->segment)) {
demux->packet = (gint64) gst_util_uint64_scale (demux->num_packets,
stop, demux->play_time);
} else {
demux->packet = packet;
}
demux->need_newsegment = TRUE;
demux->segment_seqnum = seqnum;
demux->speed_packets =
GST_ASF_DEMUX_IS_REVERSE_PLAYBACK (demux->segment) ? 1 : speed_count;
gst_asf_demux_reset_stream_state_after_discont (demux);
GST_OBJECT_UNLOCK (demux);
skip:
/* restart our task since it might have been stopped when we did the flush */
gst_pad_start_task (demux->sinkpad, (GstTaskFunction) gst_asf_demux_loop,
demux, NULL);
/* streaming can continue now */
GST_PAD_STREAM_UNLOCK (demux->sinkpad);
return TRUE;
}
Commit Message: asfdemux: Check that we have enough data available before parsing bool/uint extended content descriptors
https://bugzilla.gnome.org/show_bug.cgi?id=777955
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: std::unique_ptr<JSONObject> TransformPaintPropertyNode::ToJSON() const {
auto json = JSONObject::Create();
if (Parent())
json->SetString("parent", String::Format("%p", Parent()));
if (!state_.matrix.IsIdentity())
json->SetString("matrix", state_.matrix.ToString());
if (!state_.matrix.IsIdentityOrTranslation())
json->SetString("origin", state_.origin.ToString());
if (!state_.flattens_inherited_transform)
json->SetBoolean("flattensInheritedTransform", false);
if (state_.backface_visibility != BackfaceVisibility::kInherited) {
json->SetString("backface",
state_.backface_visibility == BackfaceVisibility::kVisible
? "visible"
: "hidden");
}
if (state_.rendering_context_id) {
json->SetString("renderingContextId",
String::Format("%x", state_.rendering_context_id));
}
if (state_.direct_compositing_reasons != CompositingReason::kNone) {
json->SetString(
"directCompositingReasons",
CompositingReason::ToString(state_.direct_compositing_reasons));
}
if (state_.compositor_element_id) {
json->SetString("compositorElementId",
state_.compositor_element_id.ToString().c_str());
}
if (state_.scroll)
json->SetString("scroll", String::Format("%p", state_.scroll.get()));
return json;
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs)
{
kref_put(&ubufs->kref, vhost_net_zerocopy_done_signal);
wait_event(ubufs->wait, !atomic_read(&ubufs->kref.refcount));
kfree(ubufs);
}
Commit Message: vhost-net: fix use-after-free in vhost_net_flush
vhost_net_ubuf_put_and_wait has a confusing name:
it will actually also free it's argument.
Thus since commit 1280c27f8e29acf4af2da914e80ec27c3dbd5c01
"vhost-net: flush outstanding DMAs on memory change"
vhost_net_flush tries to use the argument after passing it
to vhost_net_ubuf_put_and_wait, this results
in use after free.
To fix, don't free the argument in vhost_net_ubuf_put_and_wait,
add an new API for callers that want to free ubufs.
Acked-by: Asias He <[email protected]>
Acked-by: Jason Wang <[email protected]>
Signed-off-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: int ip_mc_gsfget(struct sock *sk, struct group_filter *gsf,
struct group_filter __user *optval, int __user *optlen)
{
int err, i, count, copycount;
struct sockaddr_in *psin;
__be32 addr;
struct ip_mc_socklist *pmc;
struct inet_sock *inet = inet_sk(sk);
struct ip_sf_socklist *psl;
psin = (struct sockaddr_in *)&gsf->gf_group;
if (psin->sin_family != AF_INET)
return -EINVAL;
addr = psin->sin_addr.s_addr;
if (!ipv4_is_multicast(addr))
return -EINVAL;
rtnl_lock();
err = -EADDRNOTAVAIL;
for_each_pmc_rtnl(inet, pmc) {
if (pmc->multi.imr_multiaddr.s_addr == addr &&
pmc->multi.imr_ifindex == gsf->gf_interface)
break;
}
if (!pmc) /* must have a prior join */
goto done;
gsf->gf_fmode = pmc->sfmode;
psl = rtnl_dereference(pmc->sflist);
rtnl_unlock();
count = psl ? psl->sl_count : 0;
copycount = count < gsf->gf_numsrc ? count : gsf->gf_numsrc;
gsf->gf_numsrc = count;
if (put_user(GROUP_FILTER_SIZE(copycount), optlen) ||
copy_to_user(optval, gsf, GROUP_FILTER_SIZE(0))) {
return -EFAULT;
}
for (i=0; i<copycount; i++) {
struct sockaddr_storage ss;
psin = (struct sockaddr_in *)&ss;
memset(&ss, 0, sizeof(ss));
psin->sin_family = AF_INET;
psin->sin_addr.s_addr = psl->sl_addr[i];
if (copy_to_user(&optval->gf_slist[i], &ss, sizeof(ss)))
return -EFAULT;
}
return 0;
done:
rtnl_unlock();
return err;
}
Commit Message: igmp: Avoid zero delay when receiving odd mixture of IGMP queries
Commit 5b7c84066733c5dfb0e4016d939757b38de189e4 ('ipv4: correct IGMP
behavior on v3 query during v2-compatibility mode') added yet another
case for query parsing, which can result in max_delay = 0. Substitute
a value of 1, as in the usual v3 case.
Reported-by: Simon McVittie <[email protected]>
References: http://bugs.debian.org/654876
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void DesktopWindowTreeHostX11::DispatchKeyEvent(ui::KeyEvent* event) {
if (native_widget_delegate_->AsWidget()->IsActive())
SendEventToSink(event);
}
Commit Message: Fix PIP window being blank after minimize/show
DesktopWindowTreeHostX11::SetVisible only made the call into
OnNativeWidgetVisibilityChanged when transitioning from shown
to minimized and not vice versa. This is because this change
https://chromium-review.googlesource.com/c/chromium/src/+/1437263
considered IsVisible to be true when minimized, which made
IsVisible always true in this case. This caused layers to be hidden
but never shown again.
This is a reland of:
https://chromium-review.googlesource.com/c/chromium/src/+/1580103
Bug: 949199
Change-Id: I2151cd09e537d8ce8781897f43a3b8e9cec75996
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1584617
Reviewed-by: Scott Violet <[email protected]>
Commit-Queue: enne <[email protected]>
Cr-Commit-Position: refs/heads/master@{#654280}
CWE ID: CWE-284
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static enum led_brightness k90_backlight_get(struct led_classdev *led_cdev)
{
int ret;
struct k90_led *led = container_of(led_cdev, struct k90_led, cdev);
struct device *dev = led->cdev.dev->parent;
struct usb_interface *usbif = to_usb_interface(dev->parent);
struct usb_device *usbdev = interface_to_usbdev(usbif);
int brightness;
char data[8];
ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),
K90_REQUEST_STATUS,
USB_DIR_IN | USB_TYPE_VENDOR |
USB_RECIP_DEVICE, 0, 0, data, 8,
USB_CTRL_SET_TIMEOUT);
if (ret < 0) {
dev_warn(dev, "Failed to get K90 initial state (error %d).\n",
ret);
return -EIO;
}
brightness = data[4];
if (brightness < 0 || brightness > 3) {
dev_warn(dev,
"Read invalid backlight brightness: %02hhx.\n",
data[4]);
return -EIO;
}
return brightness;
}
Commit Message: HID: corsair: fix DMA buffers on stack
Not all platforms support DMA to the stack, and specifically since v4.9
this is no longer supported on x86 with VMAP_STACK either.
Note that the macro-mode buffer was larger than necessary.
Fixes: 6f78193ee9ea ("HID: corsair: Add Corsair Vengeance K90 driver")
Cc: stable <[email protected]>
Signed-off-by: Johan Hovold <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: check_table_height(struct table *t)
{
int i, j, k;
struct {
short *row;
short *rowspan;
short *indexarray;
short maxcell;
short size;
short *height;
} cell;
int space = 0;
cell.size = 0;
cell.maxcell = -1;
for (j = 0; j <= t->maxrow; j++) {
if (!t->tabattr[j])
continue;
for (i = 0; i <= t->maxcol; i++) {
int t_dep, rowspan;
if (t->tabattr[j][i] & (HTT_X | HTT_Y))
continue;
if (t->tabdata[j][i] == NULL)
t_dep = 0;
else
t_dep = t->tabdata[j][i]->nitem;
rowspan = table_rowspan(t, j, i);
if (rowspan > 1) {
int c = cell.maxcell + 1;
k = bsearch_2short(rowspan, cell.rowspan,
j, cell.row, t->maxrow + 1, cell.indexarray,
c);
if (k <= cell.maxcell) {
int idx = cell.indexarray[k];
if (cell.row[idx] == j && cell.rowspan[idx] == rowspan)
c = idx;
}
if (c >= MAXROWCELL)
continue;
if (c >= cell.size) {
if (cell.size == 0) {
cell.size = max(MAXCELL, c + 1);
cell.row = NewAtom_N(short, cell.size);
cell.rowspan = NewAtom_N(short, cell.size);
cell.indexarray = NewAtom_N(short, cell.size);
cell.height = NewAtom_N(short, cell.size);
}
else {
cell.size = max(cell.size + MAXCELL, c + 1);
cell.row = New_Reuse(short, cell.row, cell.size);
cell.rowspan = New_Reuse(short, cell.rowspan,
cell.size);
cell.indexarray = New_Reuse(short, cell.indexarray,
cell.size);
cell.height = New_Reuse(short, cell.height, cell.size);
}
}
if (c > cell.maxcell) {
cell.maxcell++;
cell.row[cell.maxcell] = j;
cell.rowspan[cell.maxcell] = rowspan;
cell.height[cell.maxcell] = 0;
if (cell.maxcell > k) {
int ii;
for (ii = cell.maxcell; ii > k; ii--)
cell.indexarray[ii] = cell.indexarray[ii - 1];
}
cell.indexarray[k] = cell.maxcell;
}
if (cell.height[c] < t_dep)
cell.height[c] = t_dep;
continue;
}
if (t->tabheight[j] < t_dep)
t->tabheight[j] = t_dep;
}
}
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
case BORDER_NOWIN:
space = 1;
break;
case BORDER_NONE:
space = 0;
}
check_cell_width(t->tabheight, cell.height, cell.row, cell.rowspan,
cell.maxcell, cell.indexarray, space, 1);
}
Commit Message: Prevent negative indent value in feed_table_block_tag()
Bug-Debian: https://github.com/tats/w3m/issues/88
CWE ID: CWE-835
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void cdateFunc(
sqlite3_context *context,
int NotUsed,
sqlite3_value **NotUsed2
){
UNUSED_PARAMETER2(NotUsed, NotUsed2);
dateFunc(context, 0, 0);
}
Commit Message: sqlite: safely move pointer values through SQL.
This lands https://www.sqlite.org/src/timeline?c=d6a44b35 in
third_party/sqlite/src/ and
third_party/sqlite/patches/0013-Add-new-interfaces-sqlite3_bind_pointer-sqlite3_resu.patch
and re-generates third_party/sqlite/amalgamation/* using the script at
third_party/sqlite/google_generate_amalgamation.sh.
The CL also adds a layout test that verifies the patch works as intended.
BUG=742407
Change-Id: I2e1a457459cd2e975e6241b630e7b79c82545981
Reviewed-on: https://chromium-review.googlesource.com/572976
Reviewed-by: Chris Mumford <[email protected]>
Commit-Queue: Victor Costan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#487275}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
const unsigned char
*pixels;
Image
*image;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
MagickBooleanType
status;
size_t
length;
ssize_t
count,
y;
/*
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)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=1;
image->endian=MSBEndian;
(void) ReadBlobLSBShort(image);
image->columns=(size_t) ReadBlobLSBShort(image);
(void) ReadBlobLSBShort(image);
image->rows=(size_t) ReadBlobLSBShort(image);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Convert bi-level image to pixel packets.
*/
SetImageColorspace(image,GRAYColorspace);
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
pixels=(const unsigned char *) ReadBlobStream(image,length,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) ReadBlobStream(image,(size_t) (-(ssize_t) length) & 0x01,
GetQuantumPixels(quantum_info),&count);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: Fixed memory leak reported in #456.
CWE ID: CWE-772
Target: 1
Example 2:
Code: bool GLES2DecoderImpl::GenQueriesEXTHelper(
GLsizei n, const GLuint* client_ids) {
for (GLsizei ii = 0; ii < n; ++ii) {
if (query_manager_->GetQuery(client_ids[ii])) {
return false;
}
}
query_manager_->GenQueries(n, client_ids);
return true;
}
Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled.
This is when we expose DrawBuffers extension.
BUG=376951
TEST=the attached test case, webgl conformance
[email protected],[email protected]
Review URL: https://codereview.chromium.org/315283002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: long Track::GetNext(const BlockEntry* pCurrEntry,
const BlockEntry*& pNextEntry) const {
assert(pCurrEntry);
assert(!pCurrEntry->EOS()); //?
const Block* const pCurrBlock = pCurrEntry->GetBlock();
assert(pCurrBlock && pCurrBlock->GetTrackNumber() == m_info.number);
if (!pCurrBlock || pCurrBlock->GetTrackNumber() != m_info.number)
return -1;
const Cluster* pCluster = pCurrEntry->GetCluster();
assert(pCluster);
assert(!pCluster->EOS());
long status = pCluster->GetNext(pCurrEntry, pNextEntry);
if (status < 0) // error
return status;
for (int i = 0;;) {
while (pNextEntry) {
const Block* const pNextBlock = pNextEntry->GetBlock();
assert(pNextBlock);
if (pNextBlock->GetTrackNumber() == m_info.number)
return 0;
pCurrEntry = pNextEntry;
status = pCluster->GetNext(pCurrEntry, pNextEntry);
if (status < 0) // error
return status;
}
pCluster = m_pSegment->GetNext(pCluster);
if (pCluster == NULL) {
pNextEntry = GetEOS();
return 1;
}
if (pCluster->EOS()) {
#if 0
if (m_pSegment->Unparsed() <= 0) //all clusters have been loaded
{
pNextEntry = GetEOS();
return 1;
}
#else
if (m_pSegment->DoneParsing()) {
pNextEntry = GetEOS();
return 1;
}
#endif
pNextEntry = NULL;
return E_BUFFER_NOT_FULL;
}
status = pCluster->GetFirst(pNextEntry);
if (status < 0) // error
return status;
if (pNextEntry == NULL) // empty cluster
continue;
++i;
if (i >= 100)
break;
}
pNextEntry = GetEOS(); // so we can return a non-NULL value
return 1;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int load_state_from_tss16(struct x86_emulate_ctxt *ctxt,
struct tss_segment_16 *tss)
{
int ret;
u8 cpl;
ctxt->_eip = tss->ip;
ctxt->eflags = tss->flag | 2;
*reg_write(ctxt, VCPU_REGS_RAX) = tss->ax;
*reg_write(ctxt, VCPU_REGS_RCX) = tss->cx;
*reg_write(ctxt, VCPU_REGS_RDX) = tss->dx;
*reg_write(ctxt, VCPU_REGS_RBX) = tss->bx;
*reg_write(ctxt, VCPU_REGS_RSP) = tss->sp;
*reg_write(ctxt, VCPU_REGS_RBP) = tss->bp;
*reg_write(ctxt, VCPU_REGS_RSI) = tss->si;
*reg_write(ctxt, VCPU_REGS_RDI) = tss->di;
/*
* SDM says that segment selectors are loaded before segment
* descriptors
*/
set_segment_selector(ctxt, tss->ldt, VCPU_SREG_LDTR);
set_segment_selector(ctxt, tss->es, VCPU_SREG_ES);
set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS);
set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS);
set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS);
cpl = tss->cs & 3;
/*
* Now load segment descriptors. If fault happens at this stage
* it is handled in a context of new task
*/
ret = __load_segment_descriptor(ctxt, tss->ldt, VCPU_SREG_LDTR, cpl, true);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl, true);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl, true);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl, true);
if (ret != X86EMUL_CONTINUE)
return ret;
ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl, true);
if (ret != X86EMUL_CONTINUE)
return ret;
return X86EMUL_CONTINUE;
}
Commit Message: KVM: x86: Handle errors when RIP is set during far jumps
Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not
handle this case, and may result in failed vm-entry once the assignment is
done. The tricky part of doing so is that loading the new CS affects the
VMCS/VMCB state, so if we fail during loading the new RIP, we are left in
unconsistent state. Therefore, this patch saves on 64-bit the old CS
descriptor and restores it if loading RIP failed.
This fixes CVE-2014-3647.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: void release_open_intent(struct nameidata *nd)
{
if (nd->intent.open.file->f_path.dentry == NULL)
put_filp(nd->intent.open.file);
else
fput(nd->intent.open.file);
}
Commit Message: fix autofs/afs/etc. magic mountpoint breakage
We end up trying to kfree() nd.last.name on open("/mnt/tmp", O_CREAT)
if /mnt/tmp is an autofs direct mount. The reason is that nd.last_type
is bogus here; we want LAST_BIND for everything of that kind and we
get LAST_NORM left over from finding parent directory.
So make sure that it *is* set properly; set to LAST_BIND before
doing ->follow_link() - for normal symlinks it will be changed
by __vfs_follow_link() and everything else needs it set that way.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void rollback_registered_many(struct list_head *head)
{
struct net_device *dev, *tmp;
BUG_ON(dev_boot_phase);
ASSERT_RTNL();
list_for_each_entry_safe(dev, tmp, head, unreg_list) {
/* Some devices call without registering
* for initialization unwind. Remove those
* devices and proceed with the remaining.
*/
if (dev->reg_state == NETREG_UNINITIALIZED) {
pr_debug("unregister_netdevice: device %s/%p never "
"was registered\n", dev->name, dev);
WARN_ON(1);
list_del(&dev->unreg_list);
continue;
}
BUG_ON(dev->reg_state != NETREG_REGISTERED);
}
/* If device is running, close it first. */
dev_close_many(head);
list_for_each_entry(dev, head, unreg_list) {
/* And unlink it from device chain. */
unlist_netdevice(dev);
dev->reg_state = NETREG_UNREGISTERING;
}
synchronize_net();
list_for_each_entry(dev, head, unreg_list) {
/* Shutdown queueing discipline. */
dev_shutdown(dev);
/* Notify protocols, that we are about to destroy
this device. They should clean all the things.
*/
call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
if (!dev->rtnl_link_ops ||
dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
rtmsg_ifinfo(RTM_DELLINK, dev, ~0U);
/*
* Flush the unicast and multicast chains
*/
dev_uc_flush(dev);
dev_mc_flush(dev);
if (dev->netdev_ops->ndo_uninit)
dev->netdev_ops->ndo_uninit(dev);
/* Notifier chain MUST detach us from master device. */
WARN_ON(dev->master);
/* Remove entries from kobject tree */
netdev_unregister_kobject(dev);
}
/* Process any work delayed until the end of the batch */
dev = list_first_entry(head, struct net_device, unreg_list);
call_netdevice_notifiers(NETDEV_UNREGISTER_BATCH, dev);
rcu_barrier();
list_for_each_entry(dev, head, unreg_list)
dev_put(dev);
}
Commit Message: net: don't allow CAP_NET_ADMIN to load non-netdev kernel modules
Since a8f80e8ff94ecba629542d9b4b5f5a8ee3eb565c any process with
CAP_NET_ADMIN may load any module from /lib/modules/. This doesn't mean
that CAP_NET_ADMIN is a superset of CAP_SYS_MODULE as modules are
limited to /lib/modules/**. However, CAP_NET_ADMIN capability shouldn't
allow anybody load any module not related to networking.
This patch restricts an ability of autoloading modules to netdev modules
with explicit aliases. This fixes CVE-2011-1019.
Arnd Bergmann suggested to leave untouched the old pre-v2.6.32 behavior
of loading netdev modules by name (without any prefix) for processes
with CAP_SYS_MODULE to maintain the compatibility with network scripts
that use autoloading netdev modules by aliases like "eth0", "wlan0".
Currently there are only three users of the feature in the upstream
kernel: ipip, ip_gre and sit.
root@albatros:~# capsh --drop=$(seq -s, 0 11),$(seq -s, 13 34) --
root@albatros:~# grep Cap /proc/$$/status
CapInh: 0000000000000000
CapPrm: fffffff800001000
CapEff: fffffff800001000
CapBnd: fffffff800001000
root@albatros:~# modprobe xfs
FATAL: Error inserting xfs
(/lib/modules/2.6.38-rc6-00001-g2bf4ca3/kernel/fs/xfs/xfs.ko): Operation not permitted
root@albatros:~# lsmod | grep xfs
root@albatros:~# ifconfig xfs
xfs: error fetching interface information: Device not found
root@albatros:~# lsmod | grep xfs
root@albatros:~# lsmod | grep sit
root@albatros:~# ifconfig sit
sit: error fetching interface information: Device not found
root@albatros:~# lsmod | grep sit
root@albatros:~# ifconfig sit0
sit0 Link encap:IPv6-in-IPv4
NOARP MTU:1480 Metric:1
root@albatros:~# lsmod | grep sit
sit 10457 0
tunnel4 2957 1 sit
For CAP_SYS_MODULE module loading is still relaxed:
root@albatros:~# grep Cap /proc/$$/status
CapInh: 0000000000000000
CapPrm: ffffffffffffffff
CapEff: ffffffffffffffff
CapBnd: ffffffffffffffff
root@albatros:~# ifconfig xfs
xfs: error fetching interface information: Device not found
root@albatros:~# lsmod | grep xfs
xfs 745319 0
Reference: https://lkml.org/lkml/2011/2/24/203
Signed-off-by: Vasiliy Kulikov <[email protected]>
Signed-off-by: Michael Tokarev <[email protected]>
Acked-by: David S. Miller <[email protected]>
Acked-by: Kees Cook <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
const struct net_device_ops *slave_ops = slave_dev->netdev_ops;
struct slave *new_slave = NULL;
struct netdev_hw_addr *ha;
struct sockaddr addr;
int link_reporting;
int res = 0;
if (!bond->params.use_carrier && slave_dev->ethtool_ops == NULL &&
slave_ops->ndo_do_ioctl == NULL) {
pr_warning("%s: Warning: no link monitoring support for %s\n",
bond_dev->name, slave_dev->name);
}
/* already enslaved */
if (slave_dev->flags & IFF_SLAVE) {
pr_debug("Error, Device was already enslaved\n");
return -EBUSY;
}
/* vlan challenged mutual exclusion */
/* no need to lock since we're protected by rtnl_lock */
if (slave_dev->features & NETIF_F_VLAN_CHALLENGED) {
pr_debug("%s: NETIF_F_VLAN_CHALLENGED\n", slave_dev->name);
if (bond_vlan_used(bond)) {
pr_err("%s: Error: cannot enslave VLAN challenged slave %s on VLAN enabled bond %s\n",
bond_dev->name, slave_dev->name, bond_dev->name);
return -EPERM;
} else {
pr_warning("%s: Warning: enslaved VLAN challenged slave %s. Adding VLANs will be blocked as long as %s is part of bond %s\n",
bond_dev->name, slave_dev->name,
slave_dev->name, bond_dev->name);
}
} else {
pr_debug("%s: ! NETIF_F_VLAN_CHALLENGED\n", slave_dev->name);
}
/*
* Old ifenslave binaries are no longer supported. These can
* be identified with moderate accuracy by the state of the slave:
* the current ifenslave will set the interface down prior to
* enslaving it; the old ifenslave will not.
*/
if ((slave_dev->flags & IFF_UP)) {
pr_err("%s is up. This may be due to an out of date ifenslave.\n",
slave_dev->name);
res = -EPERM;
goto err_undo_flags;
}
/* set bonding device ether type by slave - bonding netdevices are
* created with ether_setup, so when the slave type is not ARPHRD_ETHER
* there is a need to override some of the type dependent attribs/funcs.
*
* bond ether type mutual exclusion - don't allow slaves of dissimilar
* ether type (eg ARPHRD_ETHER and ARPHRD_INFINIBAND) share the same bond
*/
if (bond->slave_cnt == 0) {
if (bond_dev->type != slave_dev->type) {
pr_debug("%s: change device type from %d to %d\n",
bond_dev->name,
bond_dev->type, slave_dev->type);
res = netdev_bonding_change(bond_dev,
NETDEV_PRE_TYPE_CHANGE);
res = notifier_to_errno(res);
if (res) {
pr_err("%s: refused to change device type\n",
bond_dev->name);
res = -EBUSY;
goto err_undo_flags;
}
/* Flush unicast and multicast addresses */
dev_uc_flush(bond_dev);
dev_mc_flush(bond_dev);
if (slave_dev->type != ARPHRD_ETHER)
bond_setup_by_slave(bond_dev, slave_dev);
else
ether_setup(bond_dev);
netdev_bonding_change(bond_dev,
NETDEV_POST_TYPE_CHANGE);
}
} else if (bond_dev->type != slave_dev->type) {
pr_err("%s ether type (%d) is different from other slaves (%d), can not enslave it.\n",
slave_dev->name,
slave_dev->type, bond_dev->type);
res = -EINVAL;
goto err_undo_flags;
}
if (slave_ops->ndo_set_mac_address == NULL) {
if (bond->slave_cnt == 0) {
pr_warning("%s: Warning: The first slave device specified does not support setting the MAC address. Setting fail_over_mac to active.",
bond_dev->name);
bond->params.fail_over_mac = BOND_FOM_ACTIVE;
} else if (bond->params.fail_over_mac != BOND_FOM_ACTIVE) {
pr_err("%s: Error: The slave device specified does not support setting the MAC address, but fail_over_mac is not set to active.\n",
bond_dev->name);
res = -EOPNOTSUPP;
goto err_undo_flags;
}
}
call_netdevice_notifiers(NETDEV_JOIN, slave_dev);
/* If this is the first slave, then we need to set the master's hardware
* address to be the same as the slave's. */
if (is_zero_ether_addr(bond->dev->dev_addr))
memcpy(bond->dev->dev_addr, slave_dev->dev_addr,
slave_dev->addr_len);
new_slave = kzalloc(sizeof(struct slave), GFP_KERNEL);
if (!new_slave) {
res = -ENOMEM;
goto err_undo_flags;
}
/*
* Set the new_slave's queue_id to be zero. Queue ID mapping
* is set via sysfs or module option if desired.
*/
new_slave->queue_id = 0;
/* Save slave's original mtu and then set it to match the bond */
new_slave->original_mtu = slave_dev->mtu;
res = dev_set_mtu(slave_dev, bond->dev->mtu);
if (res) {
pr_debug("Error %d calling dev_set_mtu\n", res);
goto err_free;
}
/*
* Save slave's original ("permanent") mac address for modes
* that need it, and for restoring it upon release, and then
* set it to the master's address
*/
memcpy(new_slave->perm_hwaddr, slave_dev->dev_addr, ETH_ALEN);
if (!bond->params.fail_over_mac) {
/*
* Set slave to master's mac address. The application already
* set the master's mac address to that of the first slave
*/
memcpy(addr.sa_data, bond_dev->dev_addr, bond_dev->addr_len);
addr.sa_family = slave_dev->type;
res = dev_set_mac_address(slave_dev, &addr);
if (res) {
pr_debug("Error %d calling set_mac_address\n", res);
goto err_restore_mtu;
}
}
res = netdev_set_bond_master(slave_dev, bond_dev);
if (res) {
pr_debug("Error %d calling netdev_set_bond_master\n", res);
goto err_restore_mac;
}
/* open the slave since the application closed it */
res = dev_open(slave_dev);
if (res) {
pr_debug("Opening slave %s failed\n", slave_dev->name);
goto err_unset_master;
}
new_slave->bond = bond;
new_slave->dev = slave_dev;
slave_dev->priv_flags |= IFF_BONDING;
if (bond_is_lb(bond)) {
/* bond_alb_init_slave() must be called before all other stages since
* it might fail and we do not want to have to undo everything
*/
res = bond_alb_init_slave(bond, new_slave);
if (res)
goto err_close;
}
/* If the mode USES_PRIMARY, then the new slave gets the
* master's promisc (and mc) settings only if it becomes the
* curr_active_slave, and that is taken care of later when calling
* bond_change_active()
*/
if (!USES_PRIMARY(bond->params.mode)) {
/* set promiscuity level to new slave */
if (bond_dev->flags & IFF_PROMISC) {
res = dev_set_promiscuity(slave_dev, 1);
if (res)
goto err_close;
}
/* set allmulti level to new slave */
if (bond_dev->flags & IFF_ALLMULTI) {
res = dev_set_allmulti(slave_dev, 1);
if (res)
goto err_close;
}
netif_addr_lock_bh(bond_dev);
/* upload master's mc_list to new slave */
netdev_for_each_mc_addr(ha, bond_dev)
dev_mc_add(slave_dev, ha->addr);
netif_addr_unlock_bh(bond_dev);
}
if (bond->params.mode == BOND_MODE_8023AD) {
/* add lacpdu mc addr to mc list */
u8 lacpdu_multicast[ETH_ALEN] = MULTICAST_LACPDU_ADDR;
dev_mc_add(slave_dev, lacpdu_multicast);
}
bond_add_vlans_on_slave(bond, slave_dev);
write_lock_bh(&bond->lock);
bond_attach_slave(bond, new_slave);
new_slave->delay = 0;
new_slave->link_failure_count = 0;
write_unlock_bh(&bond->lock);
bond_compute_features(bond);
read_lock(&bond->lock);
new_slave->last_arp_rx = jiffies;
if (bond->params.miimon && !bond->params.use_carrier) {
link_reporting = bond_check_dev_link(bond, slave_dev, 1);
if ((link_reporting == -1) && !bond->params.arp_interval) {
/*
* miimon is set but a bonded network driver
* does not support ETHTOOL/MII and
* arp_interval is not set. Note: if
* use_carrier is enabled, we will never go
* here (because netif_carrier is always
* supported); thus, we don't need to change
* the messages for netif_carrier.
*/
pr_warning("%s: Warning: MII and ETHTOOL support not available for interface %s, and arp_interval/arp_ip_target module parameters not specified, thus bonding will not detect link failures! see bonding.txt for details.\n",
bond_dev->name, slave_dev->name);
} else if (link_reporting == -1) {
/* unable get link status using mii/ethtool */
pr_warning("%s: Warning: can't get link status from interface %s; the network driver associated with this interface does not support MII or ETHTOOL link status reporting, thus miimon has no effect on this interface.\n",
bond_dev->name, slave_dev->name);
}
}
/* check for initial state */
if (!bond->params.miimon ||
(bond_check_dev_link(bond, slave_dev, 0) == BMSR_LSTATUS)) {
if (bond->params.updelay) {
pr_debug("Initial state of slave_dev is BOND_LINK_BACK\n");
new_slave->link = BOND_LINK_BACK;
new_slave->delay = bond->params.updelay;
} else {
pr_debug("Initial state of slave_dev is BOND_LINK_UP\n");
new_slave->link = BOND_LINK_UP;
}
new_slave->jiffies = jiffies;
} else {
pr_debug("Initial state of slave_dev is BOND_LINK_DOWN\n");
new_slave->link = BOND_LINK_DOWN;
}
if (bond_update_speed_duplex(new_slave) &&
(new_slave->link != BOND_LINK_DOWN)) {
pr_warning("%s: Warning: failed to get speed and duplex from %s, assumed to be 100Mb/sec and Full.\n",
bond_dev->name, new_slave->dev->name);
if (bond->params.mode == BOND_MODE_8023AD) {
pr_warning("%s: Warning: Operation of 802.3ad mode requires ETHTOOL support in base driver for proper aggregator selection.\n",
bond_dev->name);
}
}
if (USES_PRIMARY(bond->params.mode) && bond->params.primary[0]) {
/* if there is a primary slave, remember it */
if (strcmp(bond->params.primary, new_slave->dev->name) == 0) {
bond->primary_slave = new_slave;
bond->force_primary = true;
}
}
write_lock_bh(&bond->curr_slave_lock);
switch (bond->params.mode) {
case BOND_MODE_ACTIVEBACKUP:
bond_set_slave_inactive_flags(new_slave);
bond_select_active_slave(bond);
break;
case BOND_MODE_8023AD:
/* in 802.3ad mode, the internal mechanism
* will activate the slaves in the selected
* aggregator
*/
bond_set_slave_inactive_flags(new_slave);
/* if this is the first slave */
if (bond->slave_cnt == 1) {
SLAVE_AD_INFO(new_slave).id = 1;
/* Initialize AD with the number of times that the AD timer is called in 1 second
* can be called only after the mac address of the bond is set
*/
bond_3ad_initialize(bond, 1000/AD_TIMER_INTERVAL);
} else {
SLAVE_AD_INFO(new_slave).id =
SLAVE_AD_INFO(new_slave->prev).id + 1;
}
bond_3ad_bind_slave(new_slave);
break;
case BOND_MODE_TLB:
case BOND_MODE_ALB:
bond_set_active_slave(new_slave);
bond_set_slave_inactive_flags(new_slave);
bond_select_active_slave(bond);
break;
default:
pr_debug("This slave is always active in trunk mode\n");
/* always active in trunk mode */
bond_set_active_slave(new_slave);
/* In trunking mode there is little meaning to curr_active_slave
* anyway (it holds no special properties of the bond device),
* so we can change it without calling change_active_interface()
*/
if (!bond->curr_active_slave)
bond->curr_active_slave = new_slave;
break;
} /* switch(bond_mode) */
write_unlock_bh(&bond->curr_slave_lock);
bond_set_carrier(bond);
#ifdef CONFIG_NET_POLL_CONTROLLER
slave_dev->npinfo = bond_netpoll_info(bond);
if (slave_dev->npinfo) {
if (slave_enable_netpoll(new_slave)) {
read_unlock(&bond->lock);
pr_info("Error, %s: master_dev is using netpoll, "
"but new slave device does not support netpoll.\n",
bond_dev->name);
res = -EBUSY;
goto err_close;
}
}
#endif
read_unlock(&bond->lock);
res = bond_create_slave_symlinks(bond_dev, slave_dev);
if (res)
goto err_close;
res = netdev_rx_handler_register(slave_dev, bond_handle_frame,
new_slave);
if (res) {
pr_debug("Error %d calling netdev_rx_handler_register\n", res);
goto err_dest_symlinks;
}
pr_info("%s: enslaving %s as a%s interface with a%s link.\n",
bond_dev->name, slave_dev->name,
bond_is_active_slave(new_slave) ? "n active" : " backup",
new_slave->link != BOND_LINK_DOWN ? "n up" : " down");
/* enslave is successful */
return 0;
/* Undo stages on error */
err_dest_symlinks:
bond_destroy_slave_symlinks(bond_dev, slave_dev);
err_close:
dev_close(slave_dev);
err_unset_master:
netdev_set_bond_master(slave_dev, NULL);
err_restore_mac:
if (!bond->params.fail_over_mac) {
/* XXX TODO - fom follow mode needs to change master's
* MAC if this slave's MAC is in use by the bond, or at
* least print a warning.
*/
memcpy(addr.sa_data, new_slave->perm_hwaddr, ETH_ALEN);
addr.sa_family = slave_dev->type;
dev_set_mac_address(slave_dev, &addr);
}
err_restore_mtu:
dev_set_mtu(slave_dev, new_slave->original_mtu);
err_free:
kfree(new_slave);
err_undo_flags:
bond_compute_features(bond);
return res;
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int midi_setup_copyright(struct _mdi *mdi, char * text) {
MIDI_EVENT_SDEBUG(__FUNCTION__,0, text);
strip_text(text);
_WM_CheckEventMemoryPool(mdi);
mdi->events[mdi->event_count].do_event = *_WM_do_meta_copyright;
mdi->events[mdi->event_count].event_data.channel = 0;
mdi->events[mdi->event_count].event_data.data.string = text;
mdi->events[mdi->event_count].samples_to_next = 0;
mdi->event_count++;
return (0);
}
Commit Message: Add a new size parameter to _WM_SetupMidiEvent() so that it knows
where to stop reading, and adjust its users properly. Fixes bug #175
(CVE-2017-11661, CVE-2017-11662, CVE-2017-11663, CVE-2017-11664.)
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PassRefPtr<DocumentFragment> Range::createContextualFragment(const String& markup, ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return 0;
}
Node* element = m_start.container()->isElementNode() ? m_start.container() : m_start.container()->parentNode();
if (!element || !element->isHTMLElement()) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
RefPtr<DocumentFragment> fragment = createDocumentFragmentForElement(markup, toElement(element), AllowScriptingContentAndDoNotMarkAlreadyStarted);
if (!fragment) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
return fragment.release();
}
Commit Message: There are too many poorly named functions to create a fragment from markup
https://bugs.webkit.org/show_bug.cgi?id=87339
Reviewed by Eric Seidel.
Source/WebCore:
Moved all functions that create a fragment from markup to markup.h/cpp.
There should be no behavioral change.
* dom/Range.cpp:
(WebCore::Range::createContextualFragment):
* dom/Range.h: Removed createDocumentFragmentForElement.
* dom/ShadowRoot.cpp:
(WebCore::ShadowRoot::setInnerHTML):
* editing/markup.cpp:
(WebCore::createFragmentFromMarkup):
(WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource.
(WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor.
(WebCore::removeElementPreservingChildren): Moved from Range.
(WebCore::createContextualFragment): Ditto.
* editing/markup.h:
* html/HTMLElement.cpp:
(WebCore::HTMLElement::setInnerHTML):
(WebCore::HTMLElement::setOuterHTML):
(WebCore::HTMLElement::insertAdjacentHTML):
* inspector/DOMPatchSupport.cpp:
(WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using
one of the functions listed in markup.h
* xml/XSLTProcessor.cpp:
(WebCore::XSLTProcessor::transformToFragment):
Source/WebKit/qt:
Replace calls to Range::createDocumentFragmentForElement by calls to
createContextualDocumentFragment.
* Api/qwebelement.cpp:
(QWebElement::appendInside):
(QWebElement::prependInside):
(QWebElement::prependOutside):
(QWebElement::appendOutside):
(QWebElement::encloseContentsWith):
(QWebElement::encloseWith):
git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void LockScreenMediaControlsView::OnMouseExited(const ui::MouseEvent& event) {
if (is_in_drag_ || contents_view_->layer()->GetAnimator()->is_animating())
return;
close_button_->SetVisible(false);
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200
Target: 1
Example 2:
Code: offline_pages::RequestStats* GetRequestStats() {
return offliner_->GetRequestStatsForTest();
}
Commit Message: Remove unused histograms from the background loader offliner.
Bug: 975512
Change-Id: I87b0a91bed60e3a9e8a1fd9ae9b18cac27a0859f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1683361
Reviewed-by: Cathy Li <[email protected]>
Reviewed-by: Steven Holte <[email protected]>
Commit-Queue: Peter Williamson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#675332}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void utee_param_to_param(struct tee_ta_param *p, struct utee_params *up)
{
size_t n;
uint32_t types = up->types;
p->types = types;
for (n = 0; n < TEE_NUM_PARAMS; n++) {
uintptr_t a = up->vals[n * 2];
size_t b = up->vals[n * 2 + 1];
switch (TEE_PARAM_TYPE_GET(types, n)) {
case TEE_PARAM_TYPE_MEMREF_INPUT:
case TEE_PARAM_TYPE_MEMREF_OUTPUT:
case TEE_PARAM_TYPE_MEMREF_INOUT:
p->u[n].mem.mobj = &mobj_virt;
p->u[n].mem.offs = a;
p->u[n].mem.size = b;
break;
case TEE_PARAM_TYPE_VALUE_INPUT:
case TEE_PARAM_TYPE_VALUE_INOUT:
p->u[n].val.a = a;
p->u[n].val.b = b;
break;
default:
memset(&p->u[n], 0, sizeof(p->u[n]));
break;
}
}
}
Commit Message: core: svc: always check ta parameters
Always check TA parameters from a user TA. This prevents a user TA from
passing invalid pointers to a pseudo TA.
Fixes: OP-TEE-2018-0007: "Buffer checks missing when calling pseudo
TAs".
Signed-off-by: Jens Wiklander <[email protected]>
Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8)
Reviewed-by: Joakim Bech <[email protected]>
Reported-by: Riscure <[email protected]>
Reported-by: Alyssa Milburn <[email protected]>
Acked-by: Etienne Carriere <[email protected]>
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int snd_seq_ioctl_create_port(struct snd_seq_client *client, void *arg)
{
struct snd_seq_port_info *info = arg;
struct snd_seq_client_port *port;
struct snd_seq_port_callback *callback;
/* it is not allowed to create the port for an another client */
if (info->addr.client != client->number)
return -EPERM;
port = snd_seq_create_port(client, (info->flags & SNDRV_SEQ_PORT_FLG_GIVEN_PORT) ? info->addr.port : -1);
if (port == NULL)
return -ENOMEM;
if (client->type == USER_CLIENT && info->kernel) {
snd_seq_delete_port(client, port->addr.port);
return -EINVAL;
}
if (client->type == KERNEL_CLIENT) {
if ((callback = info->kernel) != NULL) {
if (callback->owner)
port->owner = callback->owner;
port->private_data = callback->private_data;
port->private_free = callback->private_free;
port->event_input = callback->event_input;
port->c_src.open = callback->subscribe;
port->c_src.close = callback->unsubscribe;
port->c_dest.open = callback->use;
port->c_dest.close = callback->unuse;
}
}
info->addr = port->addr;
snd_seq_set_port_info(port, info);
snd_seq_system_client_ev_port_start(port->addr.client, port->addr.port);
return 0;
}
Commit Message: ALSA: seq: Fix use-after-free at creating a port
There is a potential race window opened at creating and deleting a
port via ioctl, as spotted by fuzzing. snd_seq_create_port() creates
a port object and returns its pointer, but it doesn't take the
refcount, thus it can be deleted immediately by another thread.
Meanwhile, snd_seq_ioctl_create_port() still calls the function
snd_seq_system_client_ev_port_start() with the created port object
that is being deleted, and this triggers use-after-free like:
BUG: KASAN: use-after-free in snd_seq_ioctl_create_port+0x504/0x630 [snd_seq] at addr ffff8801f2241cb1
=============================================================================
BUG kmalloc-512 (Tainted: G B ): kasan: bad access detected
-----------------------------------------------------------------------------
INFO: Allocated in snd_seq_create_port+0x94/0x9b0 [snd_seq] age=1 cpu=3 pid=4511
___slab_alloc+0x425/0x460
__slab_alloc+0x20/0x40
kmem_cache_alloc_trace+0x150/0x190
snd_seq_create_port+0x94/0x9b0 [snd_seq]
snd_seq_ioctl_create_port+0xd1/0x630 [snd_seq]
snd_seq_do_ioctl+0x11c/0x190 [snd_seq]
snd_seq_ioctl+0x40/0x80 [snd_seq]
do_vfs_ioctl+0x54b/0xda0
SyS_ioctl+0x79/0x90
entry_SYSCALL_64_fastpath+0x16/0x75
INFO: Freed in port_delete+0x136/0x1a0 [snd_seq] age=1 cpu=2 pid=4717
__slab_free+0x204/0x310
kfree+0x15f/0x180
port_delete+0x136/0x1a0 [snd_seq]
snd_seq_delete_port+0x235/0x350 [snd_seq]
snd_seq_ioctl_delete_port+0xc8/0x180 [snd_seq]
snd_seq_do_ioctl+0x11c/0x190 [snd_seq]
snd_seq_ioctl+0x40/0x80 [snd_seq]
do_vfs_ioctl+0x54b/0xda0
SyS_ioctl+0x79/0x90
entry_SYSCALL_64_fastpath+0x16/0x75
Call Trace:
[<ffffffff81b03781>] dump_stack+0x63/0x82
[<ffffffff81531b3b>] print_trailer+0xfb/0x160
[<ffffffff81536db4>] object_err+0x34/0x40
[<ffffffff815392d3>] kasan_report.part.2+0x223/0x520
[<ffffffffa07aadf4>] ? snd_seq_ioctl_create_port+0x504/0x630 [snd_seq]
[<ffffffff815395fe>] __asan_report_load1_noabort+0x2e/0x30
[<ffffffffa07aadf4>] snd_seq_ioctl_create_port+0x504/0x630 [snd_seq]
[<ffffffffa07aa8f0>] ? snd_seq_ioctl_delete_port+0x180/0x180 [snd_seq]
[<ffffffff8136be50>] ? taskstats_exit+0xbc0/0xbc0
[<ffffffffa07abc5c>] snd_seq_do_ioctl+0x11c/0x190 [snd_seq]
[<ffffffffa07abd10>] snd_seq_ioctl+0x40/0x80 [snd_seq]
[<ffffffff8136d433>] ? acct_account_cputime+0x63/0x80
[<ffffffff815b515b>] do_vfs_ioctl+0x54b/0xda0
.....
We may fix this in a few different ways, and in this patch, it's fixed
simply by taking the refcount properly at snd_seq_create_port() and
letting the caller unref the object after use. Also, there is another
potential use-after-free by sprintf() call in snd_seq_create_port(),
and this is moved inside the lock.
This fix covers CVE-2017-15265.
Reported-and-tested-by: Michael23 Yu <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: void fuse_request_send(struct fuse_conn *fc, struct fuse_req *req)
{
req->isreply = 1;
spin_lock(&fc->lock);
if (!fc->connected)
req->out.h.error = -ENOTCONN;
else if (fc->conn_error)
req->out.h.error = -ECONNREFUSED;
else {
req->in.h.unique = fuse_get_unique(fc);
queue_request(fc, req);
/* acquire extra reference, since request is still needed
after request_end() */
__fuse_get_request(req);
request_wait_answer(fc, req);
}
spin_unlock(&fc->lock);
}
Commit Message: fuse: check size of FUSE_NOTIFY_INVAL_ENTRY message
FUSE_NOTIFY_INVAL_ENTRY didn't check the length of the write so the
message processing could overrun and result in a "kernel BUG at
fs/fuse/dev.c:629!"
Reported-by: Han-Wen Nienhuys <[email protected]>
Signed-off-by: Miklos Szeredi <[email protected]>
CC: [email protected]
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: MagickExport MagickBooleanType SetImageProperty(Image *image,
const char *property,const char *value,ExceptionInfo *exception)
{
MagickBooleanType
status;
MagickStatusType
flags;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->properties == (void *) NULL)
image->properties=NewSplayTree(CompareSplayTreeString,
RelinquishMagickMemory,RelinquishMagickMemory); /* create splay-tree */
if (value == (const char *) NULL)
return(DeleteImageProperty(image,property)); /* delete if NULL */
status=MagickTrue;
if (strlen(property) <= 1)
{
/*
Do not 'set' single letter properties - read only shorthand.
*/
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
/* FUTURE: binary chars or quotes in key should produce a error */
/* Set attributes with known names or special prefixes
return result is found, or break to set a free form properity
*/
switch (*property)
{
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
case '8':
{
if (LocaleNCompare("8bim:",property,5) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break;
}
#endif
case 'B':
case 'b':
{
if (LocaleCompare("background",property) == 0)
{
(void) QueryColorCompliance(value,AllCompliance,
&image->background_color,exception);
/* check for FUTURE: value exception?? */
/* also add user input to splay tree */
}
break; /* not an attribute, add as a property */
}
case 'C':
case 'c':
{
if (LocaleCompare("channels",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
if (LocaleCompare("colorspace",property) == 0)
{
ssize_t
colorspace;
colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse,
value);
if (colorspace < 0)
return(MagickFalse); /* FUTURE: value exception?? */
return(SetImageColorspace(image,(ColorspaceType) colorspace,exception));
}
if (LocaleCompare("compose",property) == 0)
{
ssize_t
compose;
compose=ParseCommandOption(MagickComposeOptions,MagickFalse,value);
if (compose < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->compose=(CompositeOperator) compose;
return(MagickTrue);
}
if (LocaleCompare("compress",property) == 0)
{
ssize_t
compression;
compression=ParseCommandOption(MagickCompressOptions,MagickFalse,
value);
if (compression < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->compression=(CompressionType) compression;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'D':
case 'd':
{
if (LocaleCompare("delay",property) == 0)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(value,&geometry_info);
if ((flags & GreaterValue) != 0)
{
if (image->delay > (size_t) floor(geometry_info.rho+0.5))
image->delay=(size_t) floor(geometry_info.rho+0.5);
}
else
if ((flags & LessValue) != 0)
{
if (image->delay < (size_t) floor(geometry_info.rho+0.5))
image->delay=(ssize_t)
floor(geometry_info.sigma+0.5);
}
else
image->delay=(size_t) floor(geometry_info.rho+0.5);
if ((flags & SigmaValue) != 0)
image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);
return(MagickTrue);
}
if (LocaleCompare("delay_units",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
if (LocaleCompare("density",property) == 0)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(value,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
return(MagickTrue);
}
if (LocaleCompare("depth",property) == 0)
{
image->depth=StringToUnsignedLong(value);
return(MagickTrue);
}
if (LocaleCompare("dispose",property) == 0)
{
ssize_t
dispose;
dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,value);
if (dispose < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->dispose=(DisposeType) dispose;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
case 'E':
case 'e':
{
if (LocaleNCompare("exif:",property,5) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
case 'F':
case 'f':
{
if (LocaleNCompare("fx:",property,3) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
#endif
case 'G':
case 'g':
{
if (LocaleCompare("gamma",property) == 0)
{
image->gamma=StringToDouble(value,(char **) NULL);
return(MagickTrue);
}
if (LocaleCompare("gravity",property) == 0)
{
ssize_t
gravity;
gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,value);
if (gravity < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->gravity=(GravityType) gravity;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'H':
case 'h':
{
if (LocaleCompare("height",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
case 'I':
case 'i':
{
if (LocaleCompare("intensity",property) == 0)
{
ssize_t
intensity;
intensity=ParseCommandOption(MagickIntentOptions,MagickFalse,value);
if (intensity < 0)
return(MagickFalse);
image->intensity=(PixelIntensityMethod) intensity;
return(MagickTrue);
}
if (LocaleCompare("intent",property) == 0)
{
ssize_t
rendering_intent;
rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse,
value);
if (rendering_intent < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->rendering_intent=(RenderingIntent) rendering_intent;
return(MagickTrue);
}
if (LocaleCompare("interpolate",property) == 0)
{
ssize_t
interpolate;
interpolate=ParseCommandOption(MagickInterpolateOptions,MagickFalse,
value);
if (interpolate < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->interpolate=(PixelInterpolateMethod) interpolate;
return(MagickTrue);
}
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
if (LocaleNCompare("iptc:",property,5) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
#endif
break; /* not an attribute, add as a property */
}
case 'K':
case 'k':
if (LocaleCompare("kurtosis",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
case 'L':
case 'l':
{
if (LocaleCompare("loop",property) == 0)
{
image->iterations=StringToUnsignedLong(value);
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'M':
case 'm':
if ((LocaleCompare("magick",property) == 0) ||
(LocaleCompare("max",property) == 0) ||
(LocaleCompare("mean",property) == 0) ||
(LocaleCompare("min",property) == 0) ||
(LocaleCompare("min",property) == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
case 'O':
case 'o':
if (LocaleCompare("opaque",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
case 'P':
case 'p':
{
if (LocaleCompare("page",property) == 0)
{
char
*geometry;
geometry=GetPageGeometry(value);
flags=ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
return(MagickTrue);
}
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
if (LocaleNCompare("pixel:",property,6) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
#endif
if (LocaleCompare("profile",property) == 0)
{
ImageInfo
*image_info;
StringInfo
*profile;
image_info=AcquireImageInfo();
(void) CopyMagickString(image_info->filename,value,MagickPathExtent);
(void) SetImageInfo(image_info,1,exception);
profile=FileToStringInfo(image_info->filename,~0UL,exception);
if (profile != (StringInfo *) NULL)
status=SetImageProfile(image,image_info->magick,profile,exception);
image_info=DestroyImageInfo(image_info);
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'R':
case 'r':
{
if (LocaleCompare("rendering-intent",property) == 0)
{
ssize_t
rendering_intent;
rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse,
value);
if (rendering_intent < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->rendering_intent=(RenderingIntent) rendering_intent;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'S':
case 's':
if ((LocaleCompare("size",property) == 0) ||
(LocaleCompare("skewness",property) == 0) ||
(LocaleCompare("scenes",property) == 0) ||
(LocaleCompare("standard-deviation",property) == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
case 'T':
case 't':
{
if (LocaleCompare("tile-offset",property) == 0)
{
char
*geometry;
geometry=GetPageGeometry(value);
flags=ParseAbsoluteGeometry(geometry,&image->tile_offset);
geometry=DestroyString(geometry);
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'U':
case 'u':
{
if (LocaleCompare("units",property) == 0)
{
ssize_t
units;
units=ParseCommandOption(MagickResolutionOptions,MagickFalse,value);
if (units < 0)
return(MagickFalse); /* FUTURE: value exception?? */
image->units=(ResolutionType) units;
return(MagickTrue);
}
break; /* not an attribute, add as a property */
}
case 'V':
case 'v':
{
if (LocaleCompare("version",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
case 'W':
case 'w':
{
if (LocaleCompare("width",property) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
#if 0 /* Percent escape's sets values with this prefix: for later use
Throwing an exception causes this setting to fail */
case 'X':
case 'x':
{
if (LocaleNCompare("xmp:",property,4) == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"SetReadOnlyProperty","`%s'",property);
return(MagickFalse);
}
break; /* not an attribute, add as a property */
}
#endif
}
/* Default: not an attribute, add as a property */
status=AddValueToSplayTree((SplayTreeInfo *) image->properties,
ConstantString(property),ConstantString(value));
/* FUTURE: error if status is bad? */
return(status);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/298
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: pimv1_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
register const u_char *ep;
register u_char type;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
ND_TCHECK(bp[1]);
type = bp[1];
ND_PRINT((ndo, " %s", tok2str(pimv1_type_str, "[type %u]", type)));
switch (type) {
case PIMV1_TYPE_QUERY:
if (ND_TTEST(bp[8])) {
switch (bp[8] >> 4) {
case 0:
ND_PRINT((ndo, " Dense-mode"));
break;
case 1:
ND_PRINT((ndo, " Sparse-mode"));
break;
case 2:
ND_PRINT((ndo, " Sparse-Dense-mode"));
break;
default:
ND_PRINT((ndo, " mode-%d", bp[8] >> 4));
break;
}
}
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[10],2);
ND_PRINT((ndo, " (Hold-time "));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[10]));
ND_PRINT((ndo, ")"));
}
break;
case PIMV1_TYPE_REGISTER:
ND_TCHECK2(bp[8], 20); /* ip header */
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[20]),
ipaddr_string(ndo, &bp[24])));
break;
case PIMV1_TYPE_REGISTER_STOP:
ND_TCHECK2(bp[12], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[8]),
ipaddr_string(ndo, &bp[12])));
break;
case PIMV1_TYPE_RP_REACHABILITY:
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[22], 2);
ND_PRINT((ndo, " group %s", ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_PRINT((ndo, " RP %s hold ", ipaddr_string(ndo, &bp[16])));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[22]));
}
break;
case PIMV1_TYPE_ASSERT:
ND_TCHECK2(bp[16], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[16]),
ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_TCHECK2(bp[24], 4);
ND_PRINT((ndo, " %s pref %d metric %d",
(bp[20] & 0x80) ? "RP-tree" : "SPT",
EXTRACT_32BITS(&bp[20]) & 0x7fffffff,
EXTRACT_32BITS(&bp[24])));
break;
case PIMV1_TYPE_JOIN_PRUNE:
case PIMV1_TYPE_GRAFT:
case PIMV1_TYPE_GRAFT_ACK:
if (ndo->ndo_vflag)
pimv1_join_prune_print(ndo, &bp[8], len - 8);
break;
}
ND_TCHECK(bp[4]);
if ((bp[4] >> 4) != 1)
ND_PRINT((ndo, " [v%d]", bp[4] >> 4));
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks.
Use ND_TCHECK macros to do bounds checking, and add length checks before
the bounds checks.
Add a bounds check that the review process found was missing.
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), modified
so the capture file won't be rejected as an invalid capture.
Update one test output file to reflect the changes.
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int cxusb_d680_dmb_power_ctrl(struct dvb_usb_device *d, int onoff)
{
int ret;
u8 b;
ret = cxusb_power_ctrl(d, onoff);
if (!onoff)
return ret;
msleep(128);
cxusb_ctrl_msg(d, CMD_DIGITAL, NULL, 0, &b, 1);
msleep(100);
return ret;
}
Commit Message: [media] cxusb: Use a dma capable buffer also for reading
Commit 17ce039b4e54 ("[media] cxusb: don't do DMA on stack")
added a kmalloc'ed bounce buffer for writes, but missed to do the same
for reads. As the read only happens after the write is finished, we can
reuse the same buffer.
As dvb_usb_generic_rw handles a read length of 0 by itself, avoid calling
it using the dvb_usb_generic_read wrapper function.
Signed-off-by: Stefan Brüns <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void kvm_free_physmem(struct kvm *kvm)
{
struct kvm_memslots *slots = kvm->memslots;
struct kvm_memory_slot *memslot;
kvm_for_each_memslot(memslot, slots)
kvm_free_physmem_slot(memslot, NULL);
kfree(kvm->memslots);
}
Commit Message: KVM: unmap pages from the iommu when slots are removed
commit 32f6daad4651a748a58a3ab6da0611862175722f upstream.
We've been adding new mappings, but not destroying old mappings.
This can lead to a page leak as pages are pinned using
get_user_pages, but only unpinned with put_page if they still
exist in the memslots list on vm shutdown. A memslot that is
destroyed while an iommu domain is enabled for the guest will
therefore result in an elevated page reference count that is
never cleared.
Additionally, without this fix, the iommu is only programmed
with the first translation for a gpa. This can result in
peer-to-peer errors if a mapping is destroyed and replaced by a
new mapping at the same gpa as the iommu will still be pointing
to the original, pinned memory address.
Signed-off-by: Alex Williamson <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SoftAACEncoder2::~SoftAACEncoder2() {
aacEncClose(&mAACEncoder);
delete[] mInputFrame;
mInputFrame = NULL;
}
Commit Message: codecs: handle onReset() for a few encoders
Test: Run PoC binaries
Bug: 34749392
Bug: 34705519
Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd
CWE ID:
Target: 1
Example 2:
Code: WebLocalFrame* CreateChildCounterFrameClient::CreateChildFrame(
WebLocalFrame* parent,
WebTreeScopeType scope,
const WebString& name,
const WebString& fallback_name,
WebSandboxFlags sandbox_flags,
const ParsedFeaturePolicy& container_policy,
const WebFrameOwnerProperties& frame_owner_properties) {
++count_;
return TestWebFrameClient::CreateChildFrame(
parent, scope, name, fallback_name, sandbox_flags, container_policy,
frame_owner_properties);
}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Philip Jägenstedt <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static bool new_idmap_permitted(const struct file *file,
struct user_namespace *ns, int cap_setid,
struct uid_gid_map *new_map)
{
/* Allow mapping to your own filesystem ids */
if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) {
u32 id = new_map->extent[0].lower_first;
if (cap_setid == CAP_SETUID) {
kuid_t uid = make_kuid(ns->parent, id);
if (uid_eq(uid, current_fsuid()))
return true;
}
else if (cap_setid == CAP_SETGID) {
kgid_t gid = make_kgid(ns->parent, id);
if (gid_eq(gid, current_fsgid()))
return true;
}
}
/* Allow anyone to set a mapping that doesn't require privilege */
if (!cap_valid(cap_setid))
return true;
/* Allow the specified ids if we have the appropriate capability
* (CAP_SETUID or CAP_SETGID) over the parent user namespace.
* And the opener of the id file also had the approprpiate capability.
*/
if (ns_capable(ns->parent, cap_setid) &&
file_ns_capable(file, ns->parent, cap_setid))
return true;
return false;
}
Commit Message: userns: Check uid_map's opener's fsuid, not the current fsuid
Signed-off-by: Andy Lutomirski <[email protected]>
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool dstBufferSizeHasOverflow(ParsedOptions options) {
CheckedNumeric<size_t> totalBytes = options.cropRect.width();
totalBytes *= options.cropRect.height();
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
if (!options.shouldScaleInput)
return false;
totalBytes = options.resizeWidth;
totalBytes *= options.resizeHeight;
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
return false;
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static void t1_subset_charstrings(PDF pdf)
{
cs_entry *ptr;
t1_check_unusual_charstring();
cs_size_pos = (int) (strstr(t1_line_array, charstringname) + strlen(charstringname) - t1_line_array + 1);
/*tex |cs_size_pos| points to the number indicating dict size after |/CharStrings|. */
cs_size = (int) t1_scan_num(t1_line_array + cs_size_pos, 0);
cs_ptr = cs_tab = xtalloc((unsigned) cs_size, cs_entry);
for (ptr = cs_tab; ptr - cs_tab < cs_size; ptr++)
init_cs_entry(ptr);
cs_notdef = NULL;
cs_dict_start = xstrdup(t1_line_array);
t1_getline();
while (t1_cslen) {
store_cs();
t1_getline();
}
cs_dict_end = xstrdup(t1_line_array);
t1_mark_glyphs();
if (subr_tab != NULL) {
if (cs_token_pair == NULL)
formatted_error("type 1","mismatched subroutine begin/end token pairs");
t1_subr_flush();
}
for (cs_counter = 0, ptr = cs_tab; ptr < cs_ptr; ptr++)
if (ptr->used)
cs_counter++;
t1_cs_flush();
}
Commit Message: writet1 protection against buffer overflow
git-svn-id: svn://tug.org/texlive/trunk/Build/source@48697 c570f23f-e606-0410-a88d-b1316a301751
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WorkerProcessLauncherTest::KillProcess(DWORD exit_code) {
exit_code_ = exit_code;
BOOL result = SetEvent(process_exit_event_);
EXPECT_TRUE(result);
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_FUNCTION(xml_parser_create)
{
php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void CopyObjectToDoubleElements(FixedArrayBase* from_base,
uint32_t from_start,
FixedArrayBase* to_base,
uint32_t to_start, int raw_copy_size) {
DisallowHeapAllocation no_allocation;
int copy_size = raw_copy_size;
if (raw_copy_size < 0) {
DCHECK(raw_copy_size == ElementsAccessor::kCopyToEnd ||
raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole);
copy_size = from_base->length() - from_start;
if (raw_copy_size == ElementsAccessor::kCopyToEndAndInitializeToHole) {
for (int i = to_start + copy_size; i < to_base->length(); ++i) {
FixedDoubleArray::cast(to_base)->set_the_hole(i);
}
}
}
DCHECK((copy_size + static_cast<int>(to_start)) <= to_base->length() &&
(copy_size + static_cast<int>(from_start)) <= from_base->length());
if (copy_size == 0) return;
FixedArray* from = FixedArray::cast(from_base);
FixedDoubleArray* to = FixedDoubleArray::cast(to_base);
Object* the_hole = from->GetHeap()->the_hole_value();
for (uint32_t from_end = from_start + copy_size;
from_start < from_end; from_start++, to_start++) {
Object* hole_or_object = from->get(from_start);
if (hole_or_object == the_hole) {
to->set_the_hole(to_start);
} else {
to->set(to_start, hole_or_object->Number());
}
}
}
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static bool rds_tcp_is_unloading(struct rds_connection *conn)
{
return atomic_read(&rds_tcp_unloading) != 0;
}
Commit Message: net: rds: force to destroy connection if t_sock is NULL in rds_tcp_kill_sock().
When it is to cleanup net namespace, rds_tcp_exit_net() will call
rds_tcp_kill_sock(), if t_sock is NULL, it will not call
rds_conn_destroy(), rds_conn_path_destroy() and rds_tcp_conn_free() to free
connection, and the worker cp_conn_w is not stopped, afterwards the net is freed in
net_drop_ns(); While cp_conn_w rds_connect_worker() will call rds_tcp_conn_path_connect()
and reference 'net' which has already been freed.
In rds_tcp_conn_path_connect(), rds_tcp_set_callbacks() will set t_sock = sock before
sock->ops->connect, but if connect() is failed, it will call
rds_tcp_restore_callbacks() and set t_sock = NULL, if connect is always
failed, rds_connect_worker() will try to reconnect all the time, so
rds_tcp_kill_sock() will never to cancel worker cp_conn_w and free the
connections.
Therefore, the condition !tc->t_sock is not needed if it is going to do
cleanup_net->rds_tcp_exit_net->rds_tcp_kill_sock, because tc->t_sock is always
NULL, and there is on other path to cancel cp_conn_w and free
connection. So this patch is to fix this.
rds_tcp_kill_sock():
...
if (net != c_net || !tc->t_sock)
...
Acked-by: Santosh Shilimkar <[email protected]>
==================================================================
BUG: KASAN: use-after-free in inet_create+0xbcc/0xd28
net/ipv4/af_inet.c:340
Read of size 4 at addr ffff8003496a4684 by task kworker/u8:4/3721
CPU: 3 PID: 3721 Comm: kworker/u8:4 Not tainted 5.1.0 #11
Hardware name: linux,dummy-virt (DT)
Workqueue: krdsd rds_connect_worker
Call trace:
dump_backtrace+0x0/0x3c0 arch/arm64/kernel/time.c:53
show_stack+0x28/0x38 arch/arm64/kernel/traps.c:152
__dump_stack lib/dump_stack.c:77 [inline]
dump_stack+0x120/0x188 lib/dump_stack.c:113
print_address_description+0x68/0x278 mm/kasan/report.c:253
kasan_report_error mm/kasan/report.c:351 [inline]
kasan_report+0x21c/0x348 mm/kasan/report.c:409
__asan_report_load4_noabort+0x30/0x40 mm/kasan/report.c:429
inet_create+0xbcc/0xd28 net/ipv4/af_inet.c:340
__sock_create+0x4f8/0x770 net/socket.c:1276
sock_create_kern+0x50/0x68 net/socket.c:1322
rds_tcp_conn_path_connect+0x2b4/0x690 net/rds/tcp_connect.c:114
rds_connect_worker+0x108/0x1d0 net/rds/threads.c:175
process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153
worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296
kthread+0x2f0/0x378 kernel/kthread.c:255
ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117
Allocated by task 687:
save_stack mm/kasan/kasan.c:448 [inline]
set_track mm/kasan/kasan.c:460 [inline]
kasan_kmalloc+0xd4/0x180 mm/kasan/kasan.c:553
kasan_slab_alloc+0x14/0x20 mm/kasan/kasan.c:490
slab_post_alloc_hook mm/slab.h:444 [inline]
slab_alloc_node mm/slub.c:2705 [inline]
slab_alloc mm/slub.c:2713 [inline]
kmem_cache_alloc+0x14c/0x388 mm/slub.c:2718
kmem_cache_zalloc include/linux/slab.h:697 [inline]
net_alloc net/core/net_namespace.c:384 [inline]
copy_net_ns+0xc4/0x2d0 net/core/net_namespace.c:424
create_new_namespaces+0x300/0x658 kernel/nsproxy.c:107
unshare_nsproxy_namespaces+0xa0/0x198 kernel/nsproxy.c:206
ksys_unshare+0x340/0x628 kernel/fork.c:2577
__do_sys_unshare kernel/fork.c:2645 [inline]
__se_sys_unshare kernel/fork.c:2643 [inline]
__arm64_sys_unshare+0x38/0x58 kernel/fork.c:2643
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall arch/arm64/kernel/syscall.c:47 [inline]
el0_svc_common+0x168/0x390 arch/arm64/kernel/syscall.c:83
el0_svc_handler+0x60/0xd0 arch/arm64/kernel/syscall.c:129
el0_svc+0x8/0xc arch/arm64/kernel/entry.S:960
Freed by task 264:
save_stack mm/kasan/kasan.c:448 [inline]
set_track mm/kasan/kasan.c:460 [inline]
__kasan_slab_free+0x114/0x220 mm/kasan/kasan.c:521
kasan_slab_free+0x10/0x18 mm/kasan/kasan.c:528
slab_free_hook mm/slub.c:1370 [inline]
slab_free_freelist_hook mm/slub.c:1397 [inline]
slab_free mm/slub.c:2952 [inline]
kmem_cache_free+0xb8/0x3a8 mm/slub.c:2968
net_free net/core/net_namespace.c:400 [inline]
net_drop_ns.part.6+0x78/0x90 net/core/net_namespace.c:407
net_drop_ns net/core/net_namespace.c:406 [inline]
cleanup_net+0x53c/0x6d8 net/core/net_namespace.c:569
process_one_work+0x6e8/0x1700 kernel/workqueue.c:2153
worker_thread+0x3b0/0xdd0 kernel/workqueue.c:2296
kthread+0x2f0/0x378 kernel/kthread.c:255
ret_from_fork+0x10/0x18 arch/arm64/kernel/entry.S:1117
The buggy address belongs to the object at ffff8003496a3f80
which belongs to the cache net_namespace of size 7872
The buggy address is located 1796 bytes inside of
7872-byte region [ffff8003496a3f80, ffff8003496a5e40)
The buggy address belongs to the page:
page:ffff7e000d25a800 count:1 mapcount:0 mapping:ffff80036ce4b000
index:0x0 compound_mapcount: 0
flags: 0xffffe0000008100(slab|head)
raw: 0ffffe0000008100 dead000000000100 dead000000000200 ffff80036ce4b000
raw: 0000000000000000 0000000080040004 00000001ffffffff 0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff8003496a4580: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff8003496a4600: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
>ffff8003496a4680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff8003496a4700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff8003496a4780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
Fixes: 467fa15356ac("RDS-TCP: Support multiple RDS-TCP listen endpoints, one per netns.")
Reported-by: Hulk Robot <[email protected]>
Signed-off-by: Mao Wenan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: Segment::Segment(IMkvReader* pReader, long long elem_start,
long long start, long long size)
: m_pReader(pReader),
m_element_start(elem_start),
m_start(start),
m_size(size),
m_pos(start),
m_pUnknownSize(0),
m_pSeekHead(NULL),
m_pInfo(NULL),
m_pTracks(NULL),
m_pCues(NULL),
m_pChapters(NULL),
m_clusters(NULL),
m_clusterCount(0),
m_clusterPreloadCount(0),
m_clusterSize(0) {}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
Target: 1
Example 2:
Code: ScriptPromise BluetoothRemoteGATTCharacteristic::getDescriptors(
ScriptState* scriptState,
ExceptionState&) {
return getDescriptorsImpl(
scriptState, mojom::blink::WebBluetoothGATTQueryQuantity::MULTIPLE);
}
Commit Message: Allow serialization of empty bluetooth uuids.
This change allows the passing WTF::Optional<String> types as
bluetooth.mojom.UUID optional parameter without needing to ensure the passed
object isn't empty.
BUG=None
R=juncai, dcheng
Review-Url: https://codereview.chromium.org/2646613003
Cr-Commit-Position: refs/heads/master@{#445809}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderWidgetHostViewAura::ProcessMouseWheelEvent(
const blink::WebMouseWheelEvent& event,
const ui::LatencyInfo& latency) {
host_->ForwardWheelEventWithLatencyInfo(event, latency);
}
Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash
RenderWidgetHostViewChildFrame expects its parent to have a valid
FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even
if DelegatedFrameHost is not used (in mus+ash).
BUG=706553
[email protected]
Review-Url: https://codereview.chromium.org/2847253003
Cr-Commit-Position: refs/heads/master@{#468179}
CWE ID: CWE-254
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void bpf_map_inc(struct bpf_map *map, bool uref)
{
atomic_inc(&map->refcnt);
if (uref)
atomic_inc(&map->usercnt);
}
Commit Message: bpf: fix refcnt overflow
On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK,
the malicious application may overflow 32-bit bpf program refcnt.
It's also possible to overflow map refcnt on 1Tb system.
Impose 32k hard limit which means that the same bpf program or
map cannot be shared by more than 32k processes.
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: static void v9fs_readlink(void *opaque)
{
V9fsPDU *pdu = opaque;
size_t offset = 7;
V9fsString target;
int32_t fid;
int err = 0;
V9fsFidState *fidp;
err = pdu_unmarshal(pdu, offset, "d", &fid);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_readlink(pdu->tag, pdu->id, fid);
fidp = get_fid(pdu, fid);
if (fidp == NULL) {
err = -ENOENT;
goto out_nofid;
}
v9fs_string_init(&target);
err = v9fs_co_readlink(pdu, &fidp->path, &target);
if (err < 0) {
goto out;
}
err = pdu_marshal(pdu, offset, "s", &target);
if (err < 0) {
v9fs_string_free(&target);
goto out;
}
err += offset;
trace_v9fs_readlink_return(pdu->tag, pdu->id, target.data);
v9fs_string_free(&target);
out:
put_fid(pdu, fidp);
out_nofid:
pdu_complete(pdu, err);
}
Commit Message:
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int vp78_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
AVPacket *avpkt, int is_vp7)
{
VP8Context *s = avctx->priv_data;
int ret, i, referenced, num_jobs;
enum AVDiscard skip_thresh;
VP8Frame *av_uninit(curframe), *prev_frame;
if (is_vp7)
ret = vp7_decode_frame_header(s, avpkt->data, avpkt->size);
else
ret = vp8_decode_frame_header(s, avpkt->data, avpkt->size);
if (ret < 0)
goto err;
prev_frame = s->framep[VP56_FRAME_CURRENT];
referenced = s->update_last || s->update_golden == VP56_FRAME_CURRENT ||
s->update_altref == VP56_FRAME_CURRENT;
skip_thresh = !referenced ? AVDISCARD_NONREF
: !s->keyframe ? AVDISCARD_NONKEY
: AVDISCARD_ALL;
if (avctx->skip_frame >= skip_thresh) {
s->invisible = 1;
memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);
goto skip_decode;
}
s->deblock_filter = s->filter.level && avctx->skip_loop_filter < skip_thresh;
for (i = 0; i < 5; i++)
if (s->frames[i].tf.f->data[0] &&
&s->frames[i] != prev_frame &&
&s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&
&s->frames[i] != s->framep[VP56_FRAME_GOLDEN] &&
&s->frames[i] != s->framep[VP56_FRAME_GOLDEN2])
vp8_release_frame(s, &s->frames[i]);
curframe = s->framep[VP56_FRAME_CURRENT] = vp8_find_free_buffer(s);
if (!s->colorspace)
avctx->colorspace = AVCOL_SPC_BT470BG;
if (s->fullrange)
avctx->color_range = AVCOL_RANGE_JPEG;
else
avctx->color_range = AVCOL_RANGE_MPEG;
/* Given that arithmetic probabilities are updated every frame, it's quite
* likely that the values we have on a random interframe are complete
* junk if we didn't start decode on a keyframe. So just don't display
* anything rather than junk. */
if (!s->keyframe && (!s->framep[VP56_FRAME_PREVIOUS] ||
!s->framep[VP56_FRAME_GOLDEN] ||
!s->framep[VP56_FRAME_GOLDEN2])) {
av_log(avctx, AV_LOG_WARNING,
"Discarding interframe without a prior keyframe!\n");
ret = AVERROR_INVALIDDATA;
goto err;
}
curframe->tf.f->key_frame = s->keyframe;
curframe->tf.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
: AV_PICTURE_TYPE_P;
if ((ret = vp8_alloc_frame(s, curframe, referenced)) < 0)
goto err;
if (s->update_altref != VP56_FRAME_NONE)
s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[s->update_altref];
else
s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[VP56_FRAME_GOLDEN2];
if (s->update_golden != VP56_FRAME_NONE)
s->next_framep[VP56_FRAME_GOLDEN] = s->framep[s->update_golden];
else
s->next_framep[VP56_FRAME_GOLDEN] = s->framep[VP56_FRAME_GOLDEN];
if (s->update_last)
s->next_framep[VP56_FRAME_PREVIOUS] = curframe;
else
s->next_framep[VP56_FRAME_PREVIOUS] = s->framep[VP56_FRAME_PREVIOUS];
s->next_framep[VP56_FRAME_CURRENT] = curframe;
if (avctx->codec->update_thread_context)
ff_thread_finish_setup(avctx);
s->linesize = curframe->tf.f->linesize[0];
s->uvlinesize = curframe->tf.f->linesize[1];
memset(s->top_nnz, 0, s->mb_width * sizeof(*s->top_nnz));
/* Zero macroblock structures for top/top-left prediction
* from outside the frame. */
if (!s->mb_layout)
memset(s->macroblocks + s->mb_height * 2 - 1, 0,
(s->mb_width + 1) * sizeof(*s->macroblocks));
if (!s->mb_layout && s->keyframe)
memset(s->intra4x4_pred_mode_top, DC_PRED, s->mb_width * 4);
memset(s->ref_count, 0, sizeof(s->ref_count));
if (s->mb_layout == 1) {
if (prev_frame && s->segmentation.enabled &&
!s->segmentation.update_map)
ff_thread_await_progress(&prev_frame->tf, 1, 0);
if (is_vp7)
vp7_decode_mv_mb_modes(avctx, curframe, prev_frame);
else
vp8_decode_mv_mb_modes(avctx, curframe, prev_frame);
}
if (avctx->active_thread_type == FF_THREAD_FRAME)
num_jobs = 1;
else
num_jobs = FFMIN(s->num_coeff_partitions, avctx->thread_count);
s->num_jobs = num_jobs;
s->curframe = curframe;
s->prev_frame = prev_frame;
s->mv_bounds.mv_min.y = -MARGIN;
s->mv_bounds.mv_max.y = ((s->mb_height - 1) << 6) + MARGIN;
for (i = 0; i < MAX_THREADS; i++) {
VP8ThreadData *td = &s->thread_data[i];
atomic_init(&td->thread_mb_pos, 0);
atomic_init(&td->wait_mb_pos, INT_MAX);
}
if (is_vp7)
avctx->execute2(avctx, vp7_decode_mb_row_sliced, s->thread_data, NULL,
num_jobs);
else
avctx->execute2(avctx, vp8_decode_mb_row_sliced, s->thread_data, NULL,
num_jobs);
ff_thread_report_progress(&curframe->tf, INT_MAX, 0);
memcpy(&s->framep[0], &s->next_framep[0], sizeof(s->framep[0]) * 4);
skip_decode:
if (!s->update_probabilities)
s->prob[0] = s->prob[1];
if (!s->invisible) {
if ((ret = av_frame_ref(data, curframe->tf.f)) < 0)
return ret;
*got_frame = 1;
}
return avpkt->size;
err:
memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);
return ret;
}
Commit Message: avcodec/webp: Always set pix_fmt
Fixes: out of array access
Fixes: 1434/clusterfuzz-testcase-minimized-6314998085189632
Fixes: 1435/clusterfuzz-testcase-minimized-6483783723253760
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Reviewed-by: "Ronald S. Bultje" <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static unsigned int stack_maxrandom_size(void)
{
unsigned int max = 0;
if ((current->flags & PF_RANDOMIZE) &&
!(current->personality & ADDR_NO_RANDOMIZE)) {
max = ((-1U) & STACK_RND_MASK) << PAGE_SHIFT;
}
return max;
}
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
Target: 1
Example 2:
Code: unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image,
unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth)
{
unsigned error;
LodePNGState state;
lodepng_state_init(&state);
state.info_raw.colortype = colortype;
state.info_raw.bitdepth = bitdepth;
state.info_png.color.colortype = colortype;
state.info_png.color.bitdepth = bitdepth;
lodepng_encode(out, outsize, image, w, h, &state);
error = state.error;
lodepng_state_cleanup(&state);
return error;
}
Commit Message: Fixed #5645: realloc return handling
CWE ID: CWE-772
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void FragmentPaintPropertyTreeBuilder::UpdateTransformForNonRootSVG() {
DCHECK(properties_);
DCHECK(object_.IsSVGChild());
DCHECK(object_.IsSVGForeignObject() ||
context_.current.paint_offset == LayoutPoint());
if (NeedsPaintPropertyUpdate()) {
AffineTransform transform = object_.LocalToSVGParentTransform();
if (NeedsTransformForNonRootSVG(object_)) {
OnUpdate(properties_->UpdateTransform(
context_.current.transform,
TransformPaintPropertyNode::State{transform}));
} else {
OnClear(properties_->ClearTransform());
}
}
if (properties_->Transform()) {
context_.current.transform = properties_->Transform();
context_.current.should_flatten_inherited_transform = false;
context_.current.rendering_context_id = 0;
}
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: polkit_backend_interactive_authority_check_authorization (PolkitBackendAuthority *authority,
PolkitSubject *caller,
PolkitSubject *subject,
const gchar *action_id,
PolkitDetails *details,
PolkitCheckAuthorizationFlags flags,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
PolkitBackendInteractiveAuthority *interactive_authority;
PolkitBackendInteractiveAuthorityPrivate *priv;
gchar *caller_str;
gchar *subject_str;
PolkitIdentity *user_of_caller;
PolkitIdentity *user_of_subject;
gchar *user_of_caller_str;
gchar *user_of_subject_str;
PolkitAuthorizationResult *result;
GError *error;
GSimpleAsyncResult *simple;
gboolean has_details;
gchar **detail_keys;
interactive_authority = POLKIT_BACKEND_INTERACTIVE_AUTHORITY (authority);
priv = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_GET_PRIVATE (interactive_authority);
error = NULL;
caller_str = NULL;
subject_str = NULL;
user_of_caller = NULL;
user_of_subject = NULL;
user_of_caller_str = NULL;
user_of_subject_str = NULL;
result = NULL;
simple = g_simple_async_result_new (G_OBJECT (authority),
callback,
user_data,
polkit_backend_interactive_authority_check_authorization);
/* handle being called from ourselves */
if (caller == NULL)
{
/* TODO: this is kind of a hack */
GDBusConnection *system_bus;
system_bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, NULL);
caller = polkit_system_bus_name_new (g_dbus_connection_get_unique_name (system_bus));
g_object_unref (system_bus);
}
caller_str = polkit_subject_to_string (caller);
subject_str = polkit_subject_to_string (subject);
g_debug ("%s is inquiring whether %s is authorized for %s",
caller_str,
subject_str,
action_id);
action_id);
user_of_caller = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor,
caller,
&error);
if (error != NULL)
{
g_simple_async_result_complete (simple);
g_object_unref (simple);
g_error_free (error);
goto out;
}
user_of_caller_str = polkit_identity_to_string (user_of_caller);
g_debug (" user of caller is %s", user_of_caller_str);
g_debug (" user of caller is %s", user_of_caller_str);
user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor,
subject,
&error);
if (error != NULL)
{
g_simple_async_result_complete (simple);
g_object_unref (simple);
g_error_free (error);
goto out;
}
user_of_subject_str = polkit_identity_to_string (user_of_subject);
g_debug (" user of subject is %s", user_of_subject_str);
has_details = FALSE;
if (details != NULL)
{
detail_keys = polkit_details_get_keys (details);
if (detail_keys != NULL)
{
if (g_strv_length (detail_keys) > 0)
has_details = TRUE;
g_strfreev (detail_keys);
}
}
/* Not anyone is allowed to check that process XYZ is allowed to do ABC.
* We only allow this if, and only if,
* We only allow this if, and only if,
*
* - processes may check for another process owned by the *same* user but not
* if details are passed (otherwise you'd be able to spoof the dialog)
*
* - processes running as uid 0 may check anything and pass any details
*
if (!polkit_identity_equal (user_of_caller, user_of_subject) || has_details)
* then any uid referenced by that annotation is also allowed to check
* to check anything and pass any details
*/
if (!polkit_identity_equal (user_of_caller, user_of_subject) || has_details)
{
if (!may_identity_check_authorization (interactive_authority, action_id, user_of_caller))
{
"pass details");
}
else
{
g_simple_async_result_set_error (simple,
POLKIT_ERROR,
POLKIT_ERROR_NOT_AUTHORIZED,
"Only trusted callers (e.g. uid 0 or an action owner) can use CheckAuthorization() for "
"subjects belonging to other identities");
}
g_simple_async_result_complete (simple);
g_object_unref (simple);
goto out;
}
}
Commit Message:
CWE ID: CWE-200
Target: 1
Example 2:
Code: _XcursorReadComment (XcursorFile *file,
XcursorFileHeader *fileHeader,
int toc)
{
XcursorChunkHeader chunkHeader;
XcursorUInt length;
XcursorComment *comment;
if (!file || !fileHeader)
return NULL;
/* read chunk header */
if (!_XcursorFileReadChunkHeader (file, fileHeader, toc, &chunkHeader))
return NULL;
/* read extra comment header fields */
if (!_XcursorReadUInt (file, &length))
return NULL;
comment = XcursorCommentCreate (chunkHeader.subtype, length);
if (!comment)
return NULL;
if (!_XcursorReadBytes (file, comment->comment, length))
{
XcursorCommentDestroy (comment);
return NULL;
}
comment->comment[length] = '\0';
return comment;
}
Commit Message:
CWE ID: CWE-190
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void __exit iwch_cm_term(void)
{
flush_workqueue(workq);
destroy_workqueue(workq);
}
Commit Message: iw_cxgb3: Fix incorrectly returning error on success
The cxgb3_*_send() functions return NET_XMIT_ values, which are
positive integers values. So don't treat positive return values
as an error.
Signed-off-by: Steve Wise <[email protected]>
Signed-off-by: Hariprasad Shenai <[email protected]>
Signed-off-by: Doug Ledford <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BrowserProcessMainImpl::Shutdown() {
if (state_ != STATE_STARTED) {
CHECK_NE(state_, STATE_SHUTTING_DOWN);
return;
MessagePump::Get()->Stop();
WebContentsUnloader::GetInstance()->Shutdown();
if (process_model_ != PROCESS_MODEL_SINGLE_PROCESS) {
BrowserContext::AssertNoContextsExist();
}
browser_main_runner_->Shutdown();
browser_main_runner_.reset();
if (process_model_ != PROCESS_MODEL_SINGLE_PROCESS) {
BrowserContext::AssertNoContextsExist();
}
browser_main_runner_->Shutdown();
browser_main_runner_.reset();
exit_manager_.reset();
main_delegate_.reset();
platform_delegate_.reset();
state_ = STATE_SHUTDOWN;
}
BrowserProcessMain::BrowserProcessMain() {}
BrowserProcessMain::~BrowserProcessMain() {}
ProcessModel BrowserProcessMain::GetProcessModelOverrideFromEnv() {
static bool g_initialized = false;
static ProcessModel g_process_model = PROCESS_MODEL_UNDEFINED;
if (g_initialized) {
return g_process_model;
}
g_initialized = true;
std::unique_ptr<base::Environment> env = base::Environment::Create();
if (IsEnvironmentOptionEnabled("SINGLE_PROCESS", env.get())) {
g_process_model = PROCESS_MODEL_SINGLE_PROCESS;
} else {
std::string model = GetEnvironmentOption("PROCESS_MODEL", env.get());
if (!model.empty()) {
if (model == "multi-process") {
g_process_model = PROCESS_MODEL_MULTI_PROCESS;
} else if (model == "single-process") {
g_process_model = PROCESS_MODEL_SINGLE_PROCESS;
} else if (model == "process-per-site-instance") {
g_process_model = PROCESS_MODEL_PROCESS_PER_SITE_INSTANCE;
} else if (model == "process-per-view") {
g_process_model = PROCESS_MODEL_PROCESS_PER_VIEW;
} else if (model == "process-per-site") {
g_process_model = PROCESS_MODEL_PROCESS_PER_SITE;
} else if (model == "site-per-process") {
g_process_model = PROCESS_MODEL_SITE_PER_PROCESS;
} else {
LOG(WARNING) << "Invalid process mode: " << model;
}
}
}
return g_process_model;
}
BrowserProcessMain* BrowserProcessMain::GetInstance() {
static BrowserProcessMainImpl g_instance;
return &g_instance;
}
} // namespace oxide
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void rpc_lookup_req(int prog, int ver)
{
uint32_t data[16];
data[0] = 0; data[1] = 0; /* auth credential */
data[2] = 0; data[3] = 0; /* auth verifier */
data[4] = htonl(prog);
data[5] = htonl(ver);
data[6] = htonl(17); /* IP_UDP */
data[7] = 0;
rpc_req(PROG_PORTMAP, PORTMAP_GETPORT, data, 8);
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void cJSON_AddItemToArray( cJSON *array, cJSON *item )
{
cJSON *c = array->child;
if ( ! item )
return;
if ( ! c ) {
array->child = item;
} else {
while ( c && c->next )
c = c->next;
suffix_object( c, item );
}
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int usb_console_setup(struct console *co, char *options)
{
struct usbcons_info *info = &usbcons_info;
int baud = 9600;
int bits = 8;
int parity = 'n';
int doflow = 0;
int cflag = CREAD | HUPCL | CLOCAL;
char *s;
struct usb_serial *serial;
struct usb_serial_port *port;
int retval;
struct tty_struct *tty = NULL;
struct ktermios dummy;
if (options) {
baud = simple_strtoul(options, NULL, 10);
s = options;
while (*s >= '0' && *s <= '9')
s++;
if (*s)
parity = *s++;
if (*s)
bits = *s++ - '0';
if (*s)
doflow = (*s++ == 'r');
}
/* Sane default */
if (baud == 0)
baud = 9600;
switch (bits) {
case 7:
cflag |= CS7;
break;
default:
case 8:
cflag |= CS8;
break;
}
switch (parity) {
case 'o': case 'O':
cflag |= PARODD;
break;
case 'e': case 'E':
cflag |= PARENB;
break;
}
co->cflag = cflag;
/*
* no need to check the index here: if the index is wrong, console
* code won't call us
*/
port = usb_serial_port_get_by_minor(co->index);
if (port == NULL) {
/* no device is connected yet, sorry :( */
pr_err("No USB device connected to ttyUSB%i\n", co->index);
return -ENODEV;
}
serial = port->serial;
retval = usb_autopm_get_interface(serial->interface);
if (retval)
goto error_get_interface;
tty_port_tty_set(&port->port, NULL);
info->port = port;
++port->port.count;
if (!tty_port_initialized(&port->port)) {
if (serial->type->set_termios) {
/*
* allocate a fake tty so the driver can initialize
* the termios structure, then later call set_termios to
* configure according to command line arguments
*/
tty = kzalloc(sizeof(*tty), GFP_KERNEL);
if (!tty) {
retval = -ENOMEM;
goto reset_open_count;
}
kref_init(&tty->kref);
tty->driver = usb_serial_tty_driver;
tty->index = co->index;
init_ldsem(&tty->ldisc_sem);
spin_lock_init(&tty->files_lock);
INIT_LIST_HEAD(&tty->tty_files);
kref_get(&tty->driver->kref);
__module_get(tty->driver->owner);
tty->ops = &usb_console_fake_tty_ops;
tty_init_termios(tty);
tty_port_tty_set(&port->port, tty);
}
/* only call the device specific open if this
* is the first time the port is opened */
retval = serial->type->open(NULL, port);
if (retval) {
dev_err(&port->dev, "could not open USB console port\n");
goto fail;
}
if (serial->type->set_termios) {
tty->termios.c_cflag = cflag;
tty_termios_encode_baud_rate(&tty->termios, baud, baud);
memset(&dummy, 0, sizeof(struct ktermios));
serial->type->set_termios(tty, port, &dummy);
tty_port_tty_set(&port->port, NULL);
tty_kref_put(tty);
}
tty_port_set_initialized(&port->port, 1);
}
/* Now that any required fake tty operations are completed restore
* the tty port count */
--port->port.count;
/* The console is special in terms of closing the device so
* indicate this port is now acting as a system console. */
port->port.console = 1;
mutex_unlock(&serial->disc_mutex);
return retval;
fail:
tty_port_tty_set(&port->port, NULL);
tty_kref_put(tty);
reset_open_count:
port->port.count = 0;
usb_autopm_put_interface(serial->interface);
error_get_interface:
usb_serial_put(serial);
mutex_unlock(&serial->disc_mutex);
return retval;
}
Commit Message: USB: serial: console: fix use-after-free after failed setup
Make sure to reset the USB-console port pointer when console setup fails
in order to avoid having the struct usb_serial be prematurely freed by
the console code when the device is later disconnected.
Fixes: 73e487fdb75f ("[PATCH] USB console: fix disconnection issues")
Cc: stable <[email protected]> # 2.6.18
Acked-by: Greg Kroah-Hartman <[email protected]>
Signed-off-by: Johan Hovold <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: MagickExport unsigned int ReadBlobMSBLong(Image *image)
{
register const unsigned char
*p;
register unsigned int
value;
ssize_t
count;
unsigned char
buffer[4];
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
*buffer='\0';
p=(const unsigned char *) ReadBlobStream(image,4,buffer,&count);
if (count != 4)
return(0UL);
value=(unsigned int) (*p++) << 24;
value|=(unsigned int) (*p++) << 16;
value|=(unsigned int) (*p++) << 8;
value|=(unsigned int) (*p++);
return(value);
}
Commit Message: https://github.com/ImageMagick/ImageMagick6/issues/43
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: archive_acl_add_entry_len_l(struct archive_acl *acl,
int type, int permset, int tag, int id, const char *name, size_t len,
struct archive_string_conv *sc)
{
struct archive_acl_entry *ap;
int r;
if (acl_special(acl, type, permset, tag) == 0)
return ARCHIVE_OK;
ap = acl_new_entry(acl, type, permset, tag, id);
if (ap == NULL) {
/* XXX Error XXX */
return ARCHIVE_FAILED;
}
if (name != NULL && *name != '\0' && len > 0) {
r = archive_mstring_copy_mbs_len_l(&ap->name, name, len, sc);
} else {
r = 0;
archive_mstring_clean(&ap->name);
}
if (r == 0)
return (ARCHIVE_OK);
else if (errno == ENOMEM)
return (ARCHIVE_FATAL);
else
return (ARCHIVE_WARN);
}
Commit Message: Skip 0-length ACL fields
Currently, it is possible to create an archive that crashes bsdtar
with a malformed ACL:
Program received signal SIGSEGV, Segmentation fault.
archive_acl_from_text_l (acl=<optimised out>, text=0x7e2e92 "", want_type=<optimised out>, sc=<optimised out>) at libarchive/archive_acl.c:1726
1726 switch (*s) {
(gdb) p n
$1 = 1
(gdb) p field[n]
$2 = {start = 0x0, end = 0x0}
Stop this by checking that the length is not zero before beginning
the switch statement.
I am pretty sure this is the bug mentioned in the qsym paper [1],
and I was able to replicate it with a qsym + AFL + afl-rb setup.
[1] https://www.usenix.org/conference/usenixsecurity18/presentation/yun
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb)
{
struct skb_shared_info *shinfo = skb_shinfo(skb);
int nr_frags = shinfo->nr_frags;
int i;
for (i = 0; i < nr_frags; i++) {
skb_frag_t *frag = shinfo->frags + i;
struct xen_netif_tx_request *txp;
struct page *page;
u16 pending_idx;
pending_idx = frag_get_pending_idx(frag);
txp = &netbk->pending_tx_info[pending_idx].req;
page = virt_to_page(idx_to_kaddr(netbk, pending_idx));
__skb_fill_page_desc(skb, i, page, txp->offset, txp->size);
skb->len += txp->size;
skb->data_len += txp->size;
skb->truesize += txp->size;
/* Take an extra reference to offset xen_netbk_idx_release */
get_page(netbk->mmap_pages[pending_idx]);
xen_netbk_idx_release(netbk, pending_idx);
}
}
Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop.
Signed-off-by: Matthew Daley <[email protected]>
Reviewed-by: Konrad Rzeszutek Wilk <[email protected]>
Acked-by: Ian Campbell <[email protected]>
Acked-by: Jan Beulich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: static inline void __sock_kfree_s(struct sock *sk, void *mem, int size,
const bool nullify)
{
if (WARN_ON_ONCE(!mem))
return;
if (nullify)
kzfree(mem);
else
kfree(mem);
atomic_sub(size, &sk->sk_omem_alloc);
}
Commit Message: net: avoid signed overflows for SO_{SND|RCV}BUFFORCE
CAP_NET_ADMIN users should not be allowed to set negative
sk_sndbuf or sk_rcvbuf values, as it can lead to various memory
corruptions, crashes, OOM...
Note that before commit 82981930125a ("net: cleanups in
sock_setsockopt()"), the bug was even more serious, since SO_SNDBUF
and SO_RCVBUF were vulnerable.
This needs to be backported to all known linux kernels.
Again, many thanks to syzkaller team for discovering this gem.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void jp2_pclr_destroy(jp2_box_t *box)
{
jp2_pclr_t *pclr = &box->data.pclr;
if (pclr->lutdata) {
jas_free(pclr->lutdata);
}
if (pclr->bpc)
jas_free(pclr->bpc);
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: cJSON *cJSON_CreateTrue( void )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = cJSON_True;
return item;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: void AXLayoutObject::setSelection(const AXRange& selection) {
if (!getLayoutObject() || !selection.isValid())
return;
AXObject* anchorObject =
selection.anchorObject ? selection.anchorObject.get() : this;
AXObject* focusObject =
selection.focusObject ? selection.focusObject.get() : this;
if (!isValidSelectionBound(anchorObject) ||
!isValidSelectionBound(focusObject)) {
return;
}
if (anchorObject == focusObject &&
anchorObject->getLayoutObject()->isTextControl()) {
TextControlElement* textControl =
toLayoutTextControl(anchorObject->getLayoutObject())
->textControlElement();
if (selection.anchorOffset <= selection.focusOffset) {
textControl->setSelectionRange(selection.anchorOffset,
selection.focusOffset,
SelectionHasForwardDirection);
} else {
textControl->setSelectionRange(selection.focusOffset,
selection.anchorOffset,
SelectionHasBackwardDirection);
}
return;
}
LocalFrame* frame = getLayoutObject()->frame();
if (!frame)
return;
frame->document()->updateStyleAndLayoutIgnorePendingStylesheets();
VisiblePosition anchorVisiblePosition =
toVisiblePosition(anchorObject, selection.anchorOffset);
VisiblePosition focusVisiblePosition =
toVisiblePosition(focusObject, selection.focusOffset);
if (anchorVisiblePosition.isNull() || focusVisiblePosition.isNull())
return;
frame->selection().setSelection(
SelectionInDOMTree::Builder()
.collapse(anchorVisiblePosition.toPositionWithAffinity())
.extend(focusVisiblePosition.deepEquivalent())
.build());
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: gboolean OmniboxPopupViewGtk::HandleButtonRelease(GtkWidget* widget,
GdkEventButton* event) {
if (ignore_mouse_drag_) {
ignore_mouse_drag_ = false;
return TRUE;
}
size_t line = LineFromY(static_cast<int>(event->y));
switch (event->button) {
case 1: // Left click.
AcceptLine(line, CURRENT_TAB);
break;
case 2: // Middle click.
AcceptLine(line, NEW_BACKGROUND_TAB);
break;
default:
break;
}
return TRUE;
}
Commit Message: GTK: Stop listening to gtk signals in the omnibox before destroying the model.
BUG=123530
TEST=none
Review URL: http://codereview.chromium.org/10103012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132498 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool HTMLMediaElement::IsMediaDataCORSSameOrigin(
const SecurityOrigin* origin) const {
if (GetWebMediaPlayer() &&
GetWebMediaPlayer()->DidGetOpaqueResponseFromServiceWorker()) {
return false;
}
if (!HasSingleSecurityOrigin())
return false;
return (GetWebMediaPlayer() &&
GetWebMediaPlayer()->DidPassCORSAccessCheck()) ||
origin->CanReadContent(currentSrc());
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732
Target: 1
Example 2:
Code: ResourcePtr<RawResource> ResourceFetcher::fetchMedia(FetchRequest& request)
{
return toRawResource(requestResource(Resource::Media, request));
}
Commit Message: Enforce SVG image security rules
SVG images have unique security rules that prevent them from loading
any external resources. This patch enforces these rules in
ResourceFetcher::canRequest for all non-data-uri resources. This locks
down our SVG resource handling and fixes two security bugs.
In the case of SVG images that reference other images, we had a bug
where a cached subresource would be used directly from the cache.
This has been fixed because the canRequest check occurs before we use
cached resources.
In the case of SVG images that use CSS imports, we had a bug where
imports were blindly requested. This has been fixed by stopping all
non-data-uri requests in SVG images.
With this patch we now match Gecko's behavior on both testcases.
BUG=380885, 382296
Review URL: https://codereview.chromium.org/320763002
git-svn-id: svn://svn.chromium.org/blink/trunk@176084 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void MakeUsernameForAccount(const base::DictionaryValue* result,
base::string16* gaia_id,
wchar_t* username,
DWORD username_length,
wchar_t* domain,
DWORD domain_length,
wchar_t* sid,
DWORD sid_length) {
DCHECK(gaia_id);
DCHECK(username);
DCHECK(domain);
DCHECK(sid);
*gaia_id = GetDictString(result, kKeyId);
HRESULT hr = GetSidFromId(*gaia_id, sid, sid_length);
if (SUCCEEDED(hr)) {
hr = OSUserManager::Get()->FindUserBySID(sid, username, username_length,
domain, domain_length);
if (SUCCEEDED(hr))
return;
}
LOGFN(INFO) << "No existing user found associated to gaia id:" << *gaia_id;
wcscpy_s(domain, domain_length, OSUserManager::GetLocalDomain().c_str());
username[0] = 0;
sid[0] = 0;
base::string16 os_username = GetDictString(result, kKeyEmail);
std::transform(os_username.begin(), os_username.end(), os_username.begin(),
::tolower);
base::string16::size_type at = os_username.find(L"@gmail.com");
if (at == base::string16::npos)
at = os_username.find(L"@googlemail.com");
if (at != base::string16::npos) {
os_username.resize(at);
} else {
std::string username_utf8 =
gaia::SanitizeEmail(base::UTF16ToUTF8(os_username));
size_t tld_length =
net::registry_controlled_domains::GetCanonicalHostRegistryLength(
gaia::ExtractDomainName(username_utf8),
net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
if (tld_length > 0) {
username_utf8.resize(username_utf8.length() - tld_length - 1);
os_username = base::UTF8ToUTF16(username_utf8);
}
}
if (os_username.size() > kWindowsUsernameBufferLength - 1)
os_username.resize(kWindowsUsernameBufferLength - 1);
for (auto& c : os_username) {
if (wcschr(L"@\\[]:|<>+=;?*", c) != nullptr || c < 32)
c = L'_';
}
wcscpy_s(username, username_length, os_username.c_str());
}
Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled.
Unless the registry key "mdm_aca" is explicitly set to 1, always
fail sign in of consumer accounts when mdm enrollment is enabled.
Consumer accounts are defined as accounts with gmail.com or
googlemail.com domain.
Bug: 944049
Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903
Commit-Queue: Tien Mai <[email protected]>
Reviewed-by: Roger Tawa <[email protected]>
Cr-Commit-Position: refs/heads/master@{#646278}
CWE ID: CWE-284
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void NavigationControllerImpl::DiscardNonCommittedEntriesInternal() {
if (pending_entry_index_ == -1)
delete pending_entry_;
pending_entry_ = NULL;
pending_entry_index_ = -1;
DiscardTransientEntry();
}
Commit Message: Delete unneeded pending entries in DidFailProvisionalLoad to prevent a spoof.
BUG=280512
BUG=278899
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/23978003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@222146 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: void RenderFrameHostImpl::OnDidStopLoading() {
if (!is_loading_) {
LOG(WARNING) << "OnDidStopLoading was called twice.";
return;
}
is_loading_ = false;
navigation_handle_.reset();
if (is_active())
frame_tree_node_->DidStopLoading();
}
Commit Message: Correctly reset FP in RFHI whenever origin changes
Bug: 713364
Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f
Reviewed-on: https://chromium-review.googlesource.com/482380
Commit-Queue: Ian Clelland <[email protected]>
Reviewed-by: Charles Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#466778}
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: MagickExport unsigned char *ImageToBlob(const ImageInfo *image_info,
Image *image,size_t *length,ExceptionInfo *exception)
{
const MagickInfo
*magick_info;
ImageInfo
*blob_info;
MagickBooleanType
status;
unsigned char
*blob;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
*length=0;
blob=(unsigned char *) NULL;
blob_info=CloneImageInfo(image_info);
blob_info->adjoin=MagickFalse;
(void) SetImageInfo(blob_info,1,exception);
if (*blob_info->magick != '\0')
(void) CopyMagickString(image->magick,blob_info->magick,MaxTextExtent);
magick_info=GetMagickInfo(image->magick,exception);
if (magick_info == (const MagickInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateError,"NoDecodeDelegateForThisImageFormat","`%s'",
image->magick);
blob_info=DestroyImageInfo(blob_info);
return(blob);
}
(void) CopyMagickString(blob_info->magick,image->magick,MaxTextExtent);
if (GetMagickBlobSupport(magick_info) != MagickFalse)
{
/*
Native blob support for this image format.
*/
blob_info->length=0;
blob_info->blob=AcquireQuantumMemory(MagickMaxBlobExtent,
sizeof(unsigned char));
if (blob_info->blob == (void *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
else
{
(void) CloseBlob(image);
image->blob->exempt=MagickTrue;
*image->filename='\0';
status=WriteImage(blob_info,image);
InheritException(exception,&image->exception);
*length=image->blob->length;
blob=DetachBlob(image->blob);
if (blob == (unsigned char *) NULL)
blob_info->blob=RelinquishMagickMemory(blob_info->blob);
else if (status == MagickFalse)
blob=(unsigned char *) RelinquishMagickMemory(blob);
else
blob=(unsigned char *) ResizeQuantumMemory(blob,*length+1,
sizeof(*blob));
}
}
else
{
char
unique[MaxTextExtent];
int
file;
/*
Write file to disk in blob image format.
*/
file=AcquireUniqueFileResource(unique);
if (file == -1)
{
ThrowFileException(exception,BlobError,"UnableToWriteBlob",
image_info->filename);
}
else
{
blob_info->file=fdopen(file,"wb");
if (blob_info->file != (FILE *) NULL)
{
(void) FormatLocaleString(image->filename,MaxTextExtent,"%s:%s",
image->magick,unique);
status=WriteImage(blob_info,image);
(void) CloseBlob(image);
(void) fclose(blob_info->file);
if (status == MagickFalse)
InheritException(exception,&image->exception);
else
blob=FileToBlob(unique,~0UL,length,exception);
}
(void) RelinquishUniqueFileResource(unique);
}
}
blob_info=DestroyImageInfo(blob_info);
return(blob);
}
Commit Message: https://github.com/ImageMagick/ImageMagick6/issues/43
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) {
while (begin && isspace ((ut8)str[*begin])) {
++(*begin);
}
if (!str[*begin]) { // null byte
*end = *begin;
return TT_EOF;
} else if (isalpha ((ut8)str[*begin])) { // word token
*end = *begin;
while (end && isalnum ((ut8)str[*end])) {
++(*end);
}
return TT_WORD;
} else if (isdigit ((ut8)str[*begin])) { // number token
*end = *begin;
while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex.
++(*end);
}
return TT_NUMBER;
} else { // special character: [, ], +, *, ...
*end = *begin + 1;
return TT_SPECIAL;
}
}
Commit Message: Fix #12239 - crash in the x86.nz assembler ##asm (#12252)
CWE ID: CWE-125
Target: 1
Example 2:
Code: void Browser::LoadingStateChanged(WebContents* source) {
window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading());
window_->UpdateTitleBar();
WebContents* selected_contents = chrome::GetActiveWebContents(this);
if (source == selected_contents) {
bool is_loading = source->IsLoading();
command_controller_->LoadingStateChanged(is_loading, false);
if (GetStatusBubble()) {
GetStatusBubble()->SetStatus(
CoreTabHelper::FromWebContents(chrome::GetActiveWebContents(this))->
GetStatusText());
}
}
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static ENUM_PTRS_BEGIN(pattern2_instance_enum_ptrs) {
if (index < st_pattern2_template_max_ptrs) {
gs_ptr_type_t ptype =
ENUM_SUPER_ELT(gs_pattern2_instance_t, st_pattern2_template,
templat, 0);
if (ptype)
return ptype;
return ENUM_OBJ(NULL); /* don't stop early */
}
ENUM_PREFIX(st_pattern_instance, st_pattern2_template_max_ptrs);
}
Commit Message:
CWE ID: CWE-704
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CreatePersistentHistogramAllocator() {
GlobalHistogramAllocator::GetCreateHistogramResultHistogram();
GlobalHistogramAllocator::CreateWithLocalMemory(
kAllocatorMemorySize, 0, "HistogramAllocatorTest");
allocator_ = GlobalHistogramAllocator::Get()->memory_allocator();
}
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <[email protected]>
Reviewed-by: Alexei Svitkine <[email protected]>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void Document::SetContentLanguage(const AtomicString& language) {
if (content_language_ == language)
return;
content_language_ = language;
SetNeedsStyleRecalc(kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
StyleChangeReason::kLanguage));
}
Commit Message: Inherit CSP when we inherit the security origin
This prevents attacks that use main window navigation to get out of the
existing csp constraints such as the related bug
Bug: 747847
Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8
Reviewed-on: https://chromium-review.googlesource.com/592027
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static v8::Handle<v8::Value> supplementalMethod2Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestInterface.supplementalMethod2");
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError();
TestInterface* imp = V8TestInterface::toNative(args.Holder());
ExceptionCode ec = 0;
{
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))) : 0);
ScriptExecutionContext* scriptContext = getScriptExecutionContext();
if (!scriptContext)
return v8::Undefined();
RefPtr<TestObj> result = TestSupplemental::supplementalMethod2(imp, scriptContext, strArg, objArg, ec);
if (UNLIKELY(ec))
goto fail;
return toV8(result.release(), args.GetIsolate());
}
fail:
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int32_t FASTCALL get_word (WavpackStream *wps, int chan, int32_t *correction)
{
register struct entropy_data *c = wps->w.c + chan;
uint32_t ones_count, low, mid, high;
int32_t value;
int sign;
if (!wps->wvbits.ptr)
return WORD_EOF;
if (correction)
*correction = 0;
if (!(wps->w.c [0].median [0] & ~1) && !wps->w.holding_zero && !wps->w.holding_one && !(wps->w.c [1].median [0] & ~1)) {
uint32_t mask;
int cbits;
if (wps->w.zeros_acc) {
if (--wps->w.zeros_acc) {
c->slow_level -= (c->slow_level + SLO) >> SLS;
return 0;
}
}
else {
for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits);
if (cbits == 33)
return WORD_EOF;
if (cbits < 2)
wps->w.zeros_acc = cbits;
else {
for (mask = 1, wps->w.zeros_acc = 0; --cbits; mask <<= 1)
if (getbit (&wps->wvbits))
wps->w.zeros_acc |= mask;
wps->w.zeros_acc |= mask;
}
if (wps->w.zeros_acc) {
c->slow_level -= (c->slow_level + SLO) >> SLS;
CLEAR (wps->w.c [0].median);
CLEAR (wps->w.c [1].median);
return 0;
}
}
}
if (wps->w.holding_zero)
ones_count = wps->w.holding_zero = 0;
else {
#ifdef USE_CTZ_OPTIMIZATION
while (wps->wvbits.bc < LIMIT_ONES) {
if (++(wps->wvbits.ptr) == wps->wvbits.end)
wps->wvbits.wrap (&wps->wvbits);
wps->wvbits.sr |= *(wps->wvbits.ptr) << wps->wvbits.bc;
wps->wvbits.bc += sizeof (*(wps->wvbits.ptr)) * 8;
}
#ifdef _WIN32
_BitScanForward (&ones_count, ~wps->wvbits.sr);
#else
ones_count = __builtin_ctz (~wps->wvbits.sr);
#endif
if (ones_count >= LIMIT_ONES) {
wps->wvbits.bc -= ones_count;
wps->wvbits.sr >>= ones_count;
for (; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count);
if (ones_count == (LIMIT_ONES + 1))
return WORD_EOF;
if (ones_count == LIMIT_ONES) {
uint32_t mask;
int cbits;
for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits);
if (cbits == 33)
return WORD_EOF;
if (cbits < 2)
ones_count = cbits;
else {
for (mask = 1, ones_count = 0; --cbits; mask <<= 1)
if (getbit (&wps->wvbits))
ones_count |= mask;
ones_count |= mask;
}
ones_count += LIMIT_ONES;
}
}
else {
wps->wvbits.bc -= ones_count + 1;
wps->wvbits.sr >>= ones_count + 1;
}
#elif defined (USE_NEXT8_OPTIMIZATION)
int next8;
if (wps->wvbits.bc < 8) {
if (++(wps->wvbits.ptr) == wps->wvbits.end)
wps->wvbits.wrap (&wps->wvbits);
next8 = (wps->wvbits.sr |= *(wps->wvbits.ptr) << wps->wvbits.bc) & 0xff;
wps->wvbits.bc += sizeof (*(wps->wvbits.ptr)) * 8;
}
else
next8 = wps->wvbits.sr & 0xff;
if (next8 == 0xff) {
wps->wvbits.bc -= 8;
wps->wvbits.sr >>= 8;
for (ones_count = 8; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count);
if (ones_count == (LIMIT_ONES + 1))
return WORD_EOF;
if (ones_count == LIMIT_ONES) {
uint32_t mask;
int cbits;
for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits);
if (cbits == 33)
return WORD_EOF;
if (cbits < 2)
ones_count = cbits;
else {
for (mask = 1, ones_count = 0; --cbits; mask <<= 1)
if (getbit (&wps->wvbits))
ones_count |= mask;
ones_count |= mask;
}
ones_count += LIMIT_ONES;
}
}
else {
wps->wvbits.bc -= (ones_count = ones_count_table [next8]) + 1;
wps->wvbits.sr >>= ones_count + 1;
}
#else
for (ones_count = 0; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count);
if (ones_count >= LIMIT_ONES) {
uint32_t mask;
int cbits;
if (ones_count == (LIMIT_ONES + 1))
return WORD_EOF;
for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits);
if (cbits == 33)
return WORD_EOF;
if (cbits < 2)
ones_count = cbits;
else {
for (mask = 1, ones_count = 0; --cbits; mask <<= 1)
if (getbit (&wps->wvbits))
ones_count |= mask;
ones_count |= mask;
}
ones_count += LIMIT_ONES;
}
#endif
if (wps->w.holding_one) {
wps->w.holding_one = ones_count & 1;
ones_count = (ones_count >> 1) + 1;
}
else {
wps->w.holding_one = ones_count & 1;
ones_count >>= 1;
}
wps->w.holding_zero = ~wps->w.holding_one & 1;
}
if ((wps->wphdr.flags & HYBRID_FLAG) && !chan)
update_error_limit (wps);
if (ones_count == 0) {
low = 0;
high = GET_MED (0) - 1;
DEC_MED0 ();
}
else {
low = GET_MED (0);
INC_MED0 ();
if (ones_count == 1) {
high = low + GET_MED (1) - 1;
DEC_MED1 ();
}
else {
low += GET_MED (1);
INC_MED1 ();
if (ones_count == 2) {
high = low + GET_MED (2) - 1;
DEC_MED2 ();
}
else {
low += (ones_count - 2) * GET_MED (2);
high = low + GET_MED (2) - 1;
INC_MED2 ();
}
}
}
low &= 0x7fffffff;
high &= 0x7fffffff;
mid = (high + low + 1) >> 1;
if (!c->error_limit)
mid = read_code (&wps->wvbits, high - low) + low;
else while (high - low > c->error_limit) {
if (getbit (&wps->wvbits))
mid = (high + (low = mid) + 1) >> 1;
else
mid = ((high = mid - 1) + low + 1) >> 1;
}
sign = getbit (&wps->wvbits);
if (bs_is_open (&wps->wvcbits) && c->error_limit) {
value = read_code (&wps->wvcbits, high - low) + low;
if (correction)
*correction = sign ? (mid - value) : (value - mid);
}
if (wps->wphdr.flags & HYBRID_BITRATE) {
c->slow_level -= (c->slow_level + SLO) >> SLS;
c->slow_level += wp_log2 (mid);
}
return sign ? ~mid : mid;
}
Commit Message: fixes for 4 fuzz failures posted to SourceForge mailing list
CWE ID: CWE-125
Target: 1
Example 2:
Code: LayoutUnit RenderFlexibleBox::flowAwareBorderStart() const
{
if (isHorizontalFlow())
return isLeftToRightFlow() ? borderLeft() : borderRight();
return isLeftToRightFlow() ? borderTop() : borderBottom();
}
Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1)
Previously StyleDifference was an enum that proximately bigger values
imply smaller values (e.g. StyleDifferenceLayout implies
StyleDifferenceRepaint). This causes unnecessary repaints in some cases
on layout change.
Convert StyleDifference to a structure containing relatively independent
flags.
This change doesn't directly improve the result, but can make further
repaint optimizations possible.
Step 1 doesn't change any functionality. RenderStyle still generate the
legacy StyleDifference enum when comparing styles and convert the result
to the new StyleDifference. Implicit requirements are not handled during
the conversion.
Converted call sites to use the new StyleDifference according to the
following conversion rules:
- diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange()
- diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly()
- diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout()
- diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout()
- diff > StyleDifferenceRepaintLayer => diff.needsLayout()
- diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly()
- diff == StyleDifferenceLayout => diff.needsFullLayout()
BUG=358460
TEST=All existing layout tests.
[email protected], [email protected], [email protected]
Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983
Review URL: https://codereview.chromium.org/236203020
git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int iwch_l2t_send(struct t3cdev *tdev, struct sk_buff *skb, struct l2t_entry *l2e)
{
int error = 0;
struct cxio_rdev *rdev;
rdev = (struct cxio_rdev *)tdev->ulp;
if (cxio_fatal_error(rdev)) {
kfree_skb(skb);
return -EIO;
}
error = l2t_send(tdev, skb, l2e);
if (error < 0)
kfree_skb(skb);
return error;
}
Commit Message: iw_cxgb3: Fix incorrectly returning error on success
The cxgb3_*_send() functions return NET_XMIT_ values, which are
positive integers values. So don't treat positive return values
as an error.
Signed-off-by: Steve Wise <[email protected]>
Signed-off-by: Hariprasad Shenai <[email protected]>
Signed-off-by: Doug Ledford <[email protected]>
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SendTabToSelfInfoBar::ShowInfoBar(content::WebContents* web_contents,
SendTabToSelfInfoBarDelegate* delegate) {
NOTIMPLEMENTED();
}
Commit Message: [SendTabToSelf] Added logic to display an infobar for the feature.
This CL is one of many to come. It covers:
* Creation of the infobar from the SendTabToSelfInfoBarController
* Plumbed the call to create the infobar to the native code.
* Open the link when user taps on the link
In follow-up CLs, the following will be done:
* Instantiate the InfobarController in the ChromeActivity
* Listen for Model changes in the Controller
Bug: 949233,963193
Change-Id: I5df1359debb5f0f35c32c2df3b691bf9129cdeb8
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1604406
Reviewed-by: Tommy Nyquist <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Mikel Astiz <[email protected]>
Reviewed-by: sebsg <[email protected]>
Reviewed-by: Jeffrey Cohen <[email protected]>
Reviewed-by: Matthew Jones <[email protected]>
Commit-Queue: Tanya Gupta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660854}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int nfs4_call_sync_sequence(struct rpc_clnt *clnt,
struct nfs_server *server,
struct rpc_message *msg,
struct nfs4_sequence_args *args,
struct nfs4_sequence_res *res,
int privileged)
{
int ret;
struct rpc_task *task;
struct nfs41_call_sync_data data = {
.seq_server = server,
.seq_args = args,
.seq_res = res,
};
struct rpc_task_setup task_setup = {
.rpc_client = clnt,
.rpc_message = msg,
.callback_ops = &nfs41_call_sync_ops,
.callback_data = &data
};
if (privileged)
task_setup.callback_ops = &nfs41_call_priv_sync_ops;
task = rpc_run_task(&task_setup);
if (IS_ERR(task))
ret = PTR_ERR(task);
else {
ret = task->tk_status;
rpc_put_task(task);
}
return ret;
}
Commit Message: Fix length of buffer copied in __nfs4_get_acl_uncached
_copy_from_pages() used to copy data from the temporary buffer to the
user passed buffer is passed the wrong size parameter when copying
data. res.acl_len contains both the bitmap and acl lenghts while
acl_len contains the acl length after adjusting for the bitmap size.
Signed-off-by: Sachin Prabhu <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void PermissionsRequestFunction::InstallUIAbort(bool user_initiated) {
results_ = Request::Results::Create(false);
SendResponse(true);
Release(); // Balanced in RunImpl().
}
Commit Message: Check prefs before allowing extension file access in the permissions API.
[email protected]
BUG=169632
Review URL: https://chromiumcodereview.appspot.com/11884008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DocumentLoader::DidInstallNewDocument(Document* document) {
document->SetReadyState(Document::kLoading);
document->InitContentSecurityPolicy(content_security_policy_.Release());
if (history_item_ && IsBackForwardLoadType(load_type_))
document->SetStateForNewFormElements(history_item_->GetDocumentState());
String suborigin_header = response_.HttpHeaderField(HTTPNames::Suborigin);
if (!suborigin_header.IsNull()) {
Vector<String> messages;
Suborigin suborigin;
if (ParseSuboriginHeader(suborigin_header, &suborigin, messages))
document->EnforceSuborigin(suborigin);
for (auto& message : messages) {
document->AddConsoleMessage(
ConsoleMessage::Create(kSecurityMessageSource, kErrorMessageLevel,
"Error with Suborigin header: " + message));
}
}
document->GetClientHintsPreferences().UpdateFrom(client_hints_preferences_);
Settings* settings = document->GetSettings();
fetcher_->SetImagesEnabled(settings->GetImagesEnabled());
fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically());
const AtomicString& dns_prefetch_control =
response_.HttpHeaderField(HTTPNames::X_DNS_Prefetch_Control);
if (!dns_prefetch_control.IsEmpty())
document->ParseDNSPrefetchControlHeader(dns_prefetch_control);
String header_content_language =
response_.HttpHeaderField(HTTPNames::Content_Language);
if (!header_content_language.IsEmpty()) {
size_t comma_index = header_content_language.find(',');
header_content_language.Truncate(comma_index);
header_content_language =
header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>);
if (!header_content_language.IsEmpty())
document->SetContentLanguage(AtomicString(header_content_language));
}
OriginTrialContext::AddTokensFromHeader(
document, response_.HttpHeaderField(HTTPNames::Origin_Trial));
String referrer_policy_header =
response_.HttpHeaderField(HTTPNames::Referrer_Policy);
if (!referrer_policy_header.IsNull()) {
UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader);
document->ParseAndSetReferrerPolicy(referrer_policy_header);
}
GetLocalFrameClient().DidCreateNewDocument();
}
Commit Message: Inherit CSP when we inherit the security origin
This prevents attacks that use main window navigation to get out of the
existing csp constraints such as the related bug
Bug: 747847
Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8
Reviewed-on: https://chromium-review.googlesource.com/592027
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732
Target: 1
Example 2:
Code: void HTMLTextAreaElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
{
if (name == wrapAttr) {
if (shouldWrapText()) {
addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePreWrap);
addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
} else {
addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePre);
addPropertyToPresentationAttributeStyle(style, CSSPropertyWordWrap, CSSValueNormal);
}
} else
HTMLTextFormControlElement::collectStyleForPresentationAttribute(name, value, style);
}
Commit Message: Add HTMLFormControlElement::supportsAutofocus to fix a FIXME comment.
This virtual function should return true if the form control can hanlde
'autofocucs' attribute if it is specified.
Note: HTMLInputElement::supportsAutofocus reuses InputType::isInteractiveContent
because interactiveness is required for autofocus capability.
BUG=none
TEST=none; no behavior changes.
Review URL: https://codereview.chromium.org/143343003
git-svn-id: svn://svn.chromium.org/blink/trunk@165432 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static MagickBooleanType SetGrayscaleImage(Image *image)
{
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
PixelPacket
*colormap;
register ssize_t
i;
ssize_t
*colormap_index,
j,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->type != GrayscaleType)
(void) TransformImageColorspace(image,GRAYColorspace);
colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize,
sizeof(*colormap_index));
if (colormap_index == (ssize_t *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
if (image->storage_class != PseudoClass)
{
ExceptionInfo
*exception;
(void) ResetMagickMemory(colormap_index,(-1),MaxColormapSize*
sizeof(*colormap_index));
if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
image->colors=0;
status=MagickTrue;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
register size_t
intensity;
intensity=ScaleQuantumToMap(GetPixelRed(q));
if (colormap_index[intensity] < 0)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SetGrayscaleImage)
#endif
if (colormap_index[intensity] < 0)
{
colormap_index[intensity]=(ssize_t) image->colors;
image->colormap[image->colors].red=GetPixelRed(q);
image->colormap[image->colors].green=GetPixelGreen(q);
image->colormap[image->colors].blue=GetPixelBlue(q);
image->colors++;
}
}
SetPixelIndex(indexes+x,colormap_index[intensity]);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
}
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].opacity=(unsigned short) i;
qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
IntensityCompare);
colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
sizeof(*colormap));
if (colormap == (PixelPacket *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
j=0;
colormap[j]=image->colormap[0];
for (i=0; i < (ssize_t) image->colors; i++)
{
if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
{
j++;
colormap[j]=image->colormap[i];
}
colormap_index[(ssize_t) image->colormap[i].opacity]=j;
}
image->colors=(size_t) (j+1);
image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
image->colormap=colormap;
status=MagickTrue;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,colormap_index[ScaleQuantumToMap(GetPixelIndex(
indexes+x))]);
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
image->type=GrayscaleType;
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
image->type=BilevelType;
return(status);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/574
CWE ID: CWE-772
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool DebugOnStart::FindArgument(wchar_t* command_line, const char* argument_c) {
wchar_t argument[50];
for (int i = 0; argument_c[i]; ++i)
argument[i] = argument_c[i];
int argument_len = lstrlen(argument);
int command_line_len = lstrlen(command_line);
while (command_line_len > argument_len) {
wchar_t first_char = command_line[0];
wchar_t last_char = command_line[argument_len+1];
if ((first_char == L'-' || first_char == L'/') &&
(last_char == L' ' || last_char == 0 || last_char == L'=')) {
command_line[argument_len+1] = 0;
if (lstrcmpi(command_line+1, argument) == 0) {
command_line[argument_len+1] = last_char;
return true;
}
command_line[argument_len+1] = last_char;
}
++command_line;
--command_line_len;
}
return false;
}
Commit Message: Fix null-termination on string copy in debug-on-start code.
BUG=73740
Review URL: http://codereview.chromium.org/6549019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75629 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: void virtio_del_queue(VirtIODevice *vdev, int n)
{
if (n < 0 || n >= VIRTIO_PCI_QUEUE_MAX) {
abort();
}
vdev->vq[n].vring.num = 0;
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int usbip_recv_xbuff(struct usbip_device *ud, struct urb *urb)
{
int ret;
int size;
if (ud->side == USBIP_STUB) {
/* the direction of urb must be OUT. */
if (usb_pipein(urb->pipe))
return 0;
size = urb->transfer_buffer_length;
} else {
/* the direction of urb must be IN. */
if (usb_pipeout(urb->pipe))
return 0;
size = urb->actual_length;
}
/* no need to recv xbuff */
if (!(size > 0))
return 0;
ret = usbip_recv(ud->tcp_socket, urb->transfer_buffer, size);
if (ret != size) {
dev_err(&urb->dev->dev, "recv xbuf, %d\n", ret);
if (ud->side == USBIP_STUB) {
usbip_event_add(ud, SDEV_EVENT_ERROR_TCP);
} else {
usbip_event_add(ud, VDEV_EVENT_ERROR_TCP);
return -EPIPE;
}
}
return ret;
}
Commit Message: USB: usbip: fix potential out-of-bounds write
Fix potential out-of-bounds write to urb->transfer_buffer
usbip handles network communication directly in the kernel. When receiving a
packet from its peer, usbip code parses headers according to protocol. As
part of this parsing urb->actual_length is filled. Since the input for
urb->actual_length comes from the network, it should be treated as untrusted.
Any entity controlling the network may put any value in the input and the
preallocated urb->transfer_buffer may not be large enough to hold the data.
Thus, the malicious entity is able to write arbitrary data to kernel memory.
Signed-off-by: Ignat Korchagin <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int vfio_msi_enable(struct vfio_pci_device *vdev, int nvec, bool msix)
{
struct pci_dev *pdev = vdev->pdev;
unsigned int flag = msix ? PCI_IRQ_MSIX : PCI_IRQ_MSI;
int ret;
if (!is_irq_none(vdev))
return -EINVAL;
vdev->ctx = kzalloc(nvec * sizeof(struct vfio_pci_irq_ctx), GFP_KERNEL);
if (!vdev->ctx)
return -ENOMEM;
/* return the number of supported vectors if we can't get all: */
ret = pci_alloc_irq_vectors(pdev, 1, nvec, flag);
if (ret < nvec) {
if (ret > 0)
pci_free_irq_vectors(pdev);
kfree(vdev->ctx);
return ret;
}
vdev->num_ctx = nvec;
vdev->irq_type = msix ? VFIO_PCI_MSIX_IRQ_INDEX :
VFIO_PCI_MSI_IRQ_INDEX;
if (!msix) {
/*
* Compute the virtual hardware field for max msi vectors -
* it is the log base 2 of the number of vectors.
*/
vdev->msi_qmax = fls(nvec * 2 - 1) - 1;
}
return 0;
}
Commit Message: vfio/pci: Fix integer overflows, bitmask check
The VFIO_DEVICE_SET_IRQS ioctl did not sufficiently sanitize
user-supplied integers, potentially allowing memory corruption. This
patch adds appropriate integer overflow checks, checks the range bounds
for VFIO_IRQ_SET_DATA_NONE, and also verifies that only single element
in the VFIO_IRQ_SET_DATA_TYPE_MASK bitmask is set.
VFIO_IRQ_SET_ACTION_TYPE_MASK is already correctly checked later in
vfio_pci_set_irqs_ioctl().
Furthermore, a kzalloc is changed to a kcalloc because the use of a
kzalloc with an integer multiplication allowed an integer overflow
condition to be reached without this patch. kcalloc checks for overflow
and should prevent a similar occurrence.
Signed-off-by: Vlad Tsyrklevich <[email protected]>
Signed-off-by: Alex Williamson <[email protected]>
CWE ID: CWE-190
Target: 1
Example 2:
Code: std::string CreateServerRedirect(const std::string& dest_url) {
const char* const kServerRedirectBase = "server-redirect?";
return kServerRedirectBase + dest_url;
}
Commit Message: Update PrerenderBrowserTests to work with new
PrerenderContents.
Also update PrerenderContents to pass plugin
and HTML5 prerender tests.
BUG=81229
TEST=PrerenderBrowserTests (Once the new code is enabled)
Review URL: http://codereview.chromium.org/6905169
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83841 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: acpi_cpu_flags acpi_os_acquire_lock(acpi_spinlock lockp)
{
acpi_cpu_flags flags;
spin_lock_irqsave(lockp, flags);
return flags;
}
Commit Message: acpi: Disable ACPI table override if securelevel is set
From the kernel documentation (initrd_table_override.txt):
If the ACPI_INITRD_TABLE_OVERRIDE compile option is true, it is possible
to override nearly any ACPI table provided by the BIOS with an
instrumented, modified one.
When securelevel is set, the kernel should disallow any unauthenticated
changes to kernel space. ACPI tables contain code invoked by the kernel, so
do not allow ACPI tables to be overridden if securelevel is set.
Signed-off-by: Linn Crosetto <[email protected]>
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct posix_acl *jffs2_get_acl(struct inode *inode, int type)
{
struct jffs2_inode_info *f = JFFS2_INODE_INFO(inode);
struct posix_acl *acl;
char *value = NULL;
int rc, xprefix;
switch (type) {
case ACL_TYPE_ACCESS:
acl = jffs2_iget_acl(inode, &f->i_acl_access);
if (acl != JFFS2_ACL_NOT_CACHED)
return acl;
xprefix = JFFS2_XPREFIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
acl = jffs2_iget_acl(inode, &f->i_acl_default);
if (acl != JFFS2_ACL_NOT_CACHED)
return acl;
xprefix = JFFS2_XPREFIX_ACL_DEFAULT;
break;
default:
return ERR_PTR(-EINVAL);
}
rc = do_jffs2_getxattr(inode, xprefix, "", NULL, 0);
if (rc > 0) {
value = kmalloc(rc, GFP_KERNEL);
if (!value)
return ERR_PTR(-ENOMEM);
rc = do_jffs2_getxattr(inode, xprefix, "", value, rc);
}
if (rc > 0) {
acl = jffs2_acl_from_medium(value, rc);
} else if (rc == -ENODATA || rc == -ENOSYS) {
acl = NULL;
} else {
acl = ERR_PTR(rc);
}
if (value)
kfree(value);
if (!IS_ERR(acl)) {
switch (type) {
case ACL_TYPE_ACCESS:
jffs2_iset_acl(inode, &f->i_acl_access, acl);
break;
case ACL_TYPE_DEFAULT:
jffs2_iset_acl(inode, &f->i_acl_default, acl);
break;
}
}
return acl;
}
Commit Message:
CWE ID: CWE-264
Target: 1
Example 2:
Code: void WebBluetoothServiceImpl::RemoteCharacteristicReadValue(
const std::string& characteristic_instance_id,
RemoteCharacteristicReadValueCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
const CacheQueryResult query_result =
QueryCacheForCharacteristic(characteristic_instance_id);
if (query_result.outcome == CacheQueryOutcome::BAD_RENDERER) {
return;
}
if (query_result.outcome != CacheQueryOutcome::SUCCESS) {
RecordCharacteristicReadValueOutcome(query_result.outcome);
std::move(callback).Run(query_result.GetWebResult(),
base::nullopt /* value */);
return;
}
if (BluetoothBlocklist::Get().IsExcludedFromReads(
query_result.characteristic->GetUUID())) {
RecordCharacteristicReadValueOutcome(UMAGATTOperationOutcome::BLOCKLISTED);
std::move(callback).Run(blink::mojom::WebBluetoothResult::BLOCKLISTED_READ,
base::nullopt /* value */);
return;
}
auto copyable_callback = AdaptCallbackForRepeating(std::move(callback));
query_result.characteristic->ReadRemoteCharacteristic(
base::Bind(&WebBluetoothServiceImpl::OnCharacteristicReadValueSuccess,
weak_ptr_factory_.GetWeakPtr(), copyable_callback),
base::Bind(&WebBluetoothServiceImpl::OnCharacteristicReadValueFailed,
weak_ptr_factory_.GetWeakPtr(), copyable_callback));
}
Commit Message: bluetooth: Implement getAvailability()
This change implements the getAvailability() method for
navigator.bluetooth as defined in the specification.
Bug: 707640
Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516
Reviewed-by: Chris Harrelson <[email protected]>
Reviewed-by: Giovanni Ortuño Urquidi <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]>
Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]>
Cr-Commit-Position: refs/heads/master@{#688987}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static long kvm_dev_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
long r = -EINVAL;
switch (ioctl) {
case KVM_GET_API_VERSION:
r = -EINVAL;
if (arg)
goto out;
r = KVM_API_VERSION;
break;
case KVM_CREATE_VM:
r = kvm_dev_ioctl_create_vm(arg);
break;
case KVM_CHECK_EXTENSION:
r = kvm_dev_ioctl_check_extension_generic(arg);
break;
case KVM_GET_VCPU_MMAP_SIZE:
r = -EINVAL;
if (arg)
goto out;
r = PAGE_SIZE; /* struct kvm_run */
#ifdef CONFIG_X86
r += PAGE_SIZE; /* pio data page */
#endif
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
r += PAGE_SIZE; /* coalesced mmio ring page */
#endif
break;
case KVM_TRACE_ENABLE:
case KVM_TRACE_PAUSE:
case KVM_TRACE_DISABLE:
r = -EOPNOTSUPP;
break;
default:
return kvm_arch_dev_ioctl(filp, ioctl, arg);
}
out:
return r;
}
Commit Message: KVM: perform an invalid memslot step for gpa base change
PPC must flush all translations before the new memory slot
is visible.
Signed-off-by: Marcelo Tosatti <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: hfs_cat_traverse(HFS_INFO * hfs,
TSK_HFS_BTREE_CB a_cb, void *ptr)
{
TSK_FS_INFO *fs = &(hfs->fs_info);
uint32_t cur_node; /* node id of the current node */
char *node;
uint16_t nodesize;
uint8_t is_done = 0;
tsk_error_reset();
nodesize = tsk_getu16(fs->endian, hfs->catalog_header.nodesize);
if ((node = (char *) tsk_malloc(nodesize)) == NULL)
return 1;
/* start at root node */
cur_node = tsk_getu32(fs->endian, hfs->catalog_header.rootNode);
/* if the root node is zero, then the extents btree is empty */
/* if no files have overflow extents, the Extents B-tree still
exists on disk, but is an empty B-tree containing only
the header node */
if (cur_node == 0) {
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_cat_traverse: "
"empty extents btree\n");
free(node);
return 1;
}
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_cat_traverse: starting at "
"root node %" PRIu32 "; nodesize = %"
PRIu16 "\n", cur_node, nodesize);
/* Recurse down to the needed leaf nodes and then go forward */
is_done = 0;
while (is_done == 0) {
TSK_OFF_T cur_off; /* start address of cur_node */
uint16_t num_rec; /* number of records in this node */
ssize_t cnt;
hfs_btree_node *node_desc;
if (cur_node > tsk_getu32(fs->endian,
hfs->catalog_header.totalNodes)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: Node %d too large for file", cur_node);
free(node);
return 1;
}
cur_off = cur_node * nodesize;
cnt = tsk_fs_attr_read(hfs->catalog_attr, cur_off,
node, nodesize, 0);
if (cnt != nodesize) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_cat_traverse: Error reading node %d at offset %"
PRIuOFF, cur_node, cur_off);
free(node);
return 1;
}
if (nodesize < sizeof(hfs_btree_node)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: Node size %d is too small to be valid", nodesize);
free(node);
return 1;
}
node_desc = (hfs_btree_node *) node;
num_rec = tsk_getu16(fs->endian, node_desc->num_rec);
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_cat_traverse: node %" PRIu32
" @ %" PRIu64 " has %" PRIu16 " records\n",
cur_node, cur_off, num_rec);
if (num_rec == 0) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr("hfs_cat_traverse: zero records in node %"
PRIu32, cur_node);
free(node);
return 1;
}
/* With an index node, find the record with the largest key that is smaller
* to or equal to cnid */
if (node_desc->type == HFS_BT_NODE_TYPE_IDX) {
uint32_t next_node = 0;
int rec;
for (rec = 0; rec < num_rec; ++rec) {
size_t rec_off;
hfs_btree_key_cat *key;
uint8_t retval;
int keylen;
rec_off =
tsk_getu16(fs->endian,
&node[nodesize - (rec + 1) * 2]);
if (rec_off > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: offset of record %d in index node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, (int) rec_off,
nodesize);
free(node);
return 1;
}
key = (hfs_btree_key_cat *) & node[rec_off];
keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len);
if ((keylen) > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: length of key %d in index node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, keylen, nodesize);
free(node);
return 1;
}
/*
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_traverse: record %" PRIu16
" ; keylen %" PRIu16 " (%" PRIu32 ")\n", rec,
tsk_getu16(fs->endian, key->key_len),
tsk_getu32(fs->endian, key->parent_cnid));
*/
/* save the info from this record unless it is too big */
retval =
a_cb(hfs, HFS_BT_NODE_TYPE_IDX, key,
cur_off + rec_off, ptr);
if (retval == HFS_BTREE_CB_ERR) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr2
("hfs_cat_traverse: Callback returned error");
free(node);
return 1;
}
else if ((retval == HFS_BTREE_CB_IDX_LT)
|| (next_node == 0)) {
hfs_btree_index_record *idx_rec;
int keylen =
2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian,
key->key_len), &(hfs->catalog_header));
if (rec_off + keylen > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: offset of record and keylength %d in index node %d too large (%d vs %"
PRIu16 ")", rec, cur_node,
(int) rec_off + keylen, nodesize);
free(node);
return 1;
}
idx_rec =
(hfs_btree_index_record *) & node[rec_off +
keylen];
next_node = tsk_getu32(fs->endian, idx_rec->childNode);
}
if (retval == HFS_BTREE_CB_IDX_EQGT) {
break;
}
}
if (next_node == 0) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: did not find any keys in index node %d",
cur_node);
is_done = 1;
break;
}
if (next_node == cur_node) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: node %d references itself as next node",
cur_node);
is_done = 1;
break;
}
cur_node = next_node;
}
/* With a leaf, we look for the specific record. */
else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) {
int rec;
for (rec = 0; rec < num_rec; ++rec) {
size_t rec_off;
hfs_btree_key_cat *key;
uint8_t retval;
int keylen;
rec_off =
tsk_getu16(fs->endian,
&node[nodesize - (rec + 1) * 2]);
if (rec_off > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: offset of record %d in leaf node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, (int) rec_off,
nodesize);
free(node);
return 1;
}
key = (hfs_btree_key_cat *) & node[rec_off];
keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len);
if ((keylen) > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: length of key %d in leaf node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, keylen, nodesize);
free(node);
return 1;
}
/*
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_traverse: record %" PRIu16
"; keylen %" PRIu16 " (%" PRIu32 ")\n", rec,
tsk_getu16(fs->endian, key->key_len),
tsk_getu32(fs->endian, key->parent_cnid));
*/
retval =
a_cb(hfs, HFS_BT_NODE_TYPE_LEAF, key,
cur_off + rec_off, ptr);
if (retval == HFS_BTREE_CB_LEAF_STOP) {
is_done = 1;
break;
}
else if (retval == HFS_BTREE_CB_ERR) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr2
("hfs_cat_traverse: Callback returned error");
free(node);
return 1;
}
}
if (is_done == 0) {
cur_node = tsk_getu32(fs->endian, node_desc->flink);
if (cur_node == 0) {
is_done = 1;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_traverse: moving forward to next leaf");
}
}
else {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr("hfs_cat_traverse: btree node %" PRIu32
" (%" PRIu64 ") is neither index nor leaf (%" PRIu8 ")",
cur_node, cur_off, node_desc->type);
free(node);
return 1;
}
}
free(node);
return 0;
}
Commit Message: Merge pull request #1374 from JordyZomer/develop
Fix CVE-2018-19497.
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int tiff_mapproc(thandle_t h, tdata_t *d, toff_t *o)
{
(void)h;
(void)d;
(void)o;
return 0;
}
Commit Message: Fix invalid read in gdImageCreateFromTiffPtr()
tiff_invalid_read.tiff is corrupt, and causes an invalid read in
gdImageCreateFromTiffPtr(), but not in gdImageCreateFromTiff(). The culprit
is dynamicGetbuf(), which doesn't check for out-of-bound reads. In this case,
dynamicGetbuf() is called with a negative dp->pos, but also positive buffer
overflows have to be handled, in which case 0 has to be returned (cf. commit
75e29a9).
Fixing dynamicGetbuf() exhibits that the corrupt TIFF would still create
the image, because the return value of TIFFReadRGBAImage() is not checked.
We do that, and let createFromTiffRgba() fail if TIFFReadRGBAImage() fails.
This issue had been reported by Ibrahim El-Sayed to [email protected].
CVE-2016-6911
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: DownloadItemImplDelegate::~DownloadItemImplDelegate() {
DCHECK_EQ(0, count_);
}
Commit Message: Downloads : Fixed an issue of opening incorrect download file
When one download overwrites another completed download, calling download.open in the old download causes the new download to open, which could be dangerous and undesirable. In this CL, we are trying to avoid this by blocking the opening of the old download.
Bug: 793620
Change-Id: Ic948175756700ad7c08489c3cc347330daedb6f8
Reviewed-on: https://chromium-review.googlesource.com/826477
Reviewed-by: David Trainor <[email protected]>
Reviewed-by: Xing Liu <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Commit-Queue: Shakti Sahu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#525810}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void P2PSocketDispatcherHost::OnAcceptIncomingTcpConnection(
const IPC::Message& msg, int listen_socket_id,
net::IPEndPoint remote_address, int connected_socket_id) {
P2PSocketHost* socket = LookupSocket(msg.routing_id(), listen_socket_id);
if (!socket) {
LOG(ERROR) << "Received P2PHostMsg_AcceptIncomingTcpConnection "
"for invalid socket_id.";
return;
}
P2PSocketHost* accepted_connection =
socket->AcceptIncomingTcpConnection(remote_address, connected_socket_id);
if (accepted_connection) {
sockets_.insert(std::pair<ExtendedSocketId, P2PSocketHost*>(
ExtendedSocketId(msg.routing_id(), connected_socket_id),
accepted_connection));
}
}
Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE)
CIDs 16230, 16439, 16610, 16635
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/7215029
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: ContextState::ContextState(FeatureInfo* feature_info,
ErrorStateClient* error_state_client,
Logger* logger)
: active_texture_unit(0),
bound_renderbuffer_valid(false),
pack_reverse_row_order(false),
ignore_cached_state(false),
fbo_binding_for_scissor_workaround_dirty(false),
feature_info_(feature_info),
error_state_(ErrorState::Create(error_state_client, logger)) {
Initialize();
}
Commit Message: Fix tabs sharing TEXTURE_2D_ARRAY/TEXTURE_3D data.
In linux and android, we are seeing an issue where texture data from one
tab overwrites the texture data of another tab. This is happening for apps
which are using webgl2 texture of type TEXTURE_2D_ARRAY/TEXTURE_3D.
Due to a bug in virtual context save/restore code for above texture formats,
the texture data is not properly restored while switching tabs. Hence
texture data from one tab overwrites other.
This CL has fix for that issue, an update for existing test expectations
and a new unit test for this bug.
Bug: 788448
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: Ie933984cdd2d1381f42eb4638f730c8245207a28
Reviewed-on: https://chromium-review.googlesource.com/930327
Reviewed-by: Zhenyao Mo <[email protected]>
Commit-Queue: vikas soni <[email protected]>
Cr-Commit-Position: refs/heads/master@{#539111}
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: AcpiNsEvaluate (
ACPI_EVALUATE_INFO *Info)
{
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE (NsEvaluate);
if (!Info)
{
return_ACPI_STATUS (AE_BAD_PARAMETER);
}
if (!Info->Node)
{
/*
* Get the actual namespace node for the target object if we
* need to. Handles these cases:
*
* 1) Null node, valid pathname from root (absolute path)
* 2) Node and valid pathname (path relative to Node)
* 3) Node, Null pathname
*/
Status = AcpiNsGetNode (Info->PrefixNode, Info->RelativePathname,
ACPI_NS_NO_UPSEARCH, &Info->Node);
if (ACPI_FAILURE (Status))
{
return_ACPI_STATUS (Status);
}
}
/*
* For a method alias, we must grab the actual method node so that
* proper scoping context will be established before execution.
*/
if (AcpiNsGetType (Info->Node) == ACPI_TYPE_LOCAL_METHOD_ALIAS)
{
Info->Node = ACPI_CAST_PTR (
ACPI_NAMESPACE_NODE, Info->Node->Object);
}
/* Complete the info block initialization */
Info->ReturnObject = NULL;
Info->NodeFlags = Info->Node->Flags;
Info->ObjDesc = AcpiNsGetAttachedObject (Info->Node);
ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "%s [%p] Value %p\n",
Info->RelativePathname, Info->Node,
AcpiNsGetAttachedObject (Info->Node)));
/* Get info if we have a predefined name (_HID, etc.) */
Info->Predefined = AcpiUtMatchPredefinedMethod (Info->Node->Name.Ascii);
/* Get the full pathname to the object, for use in warning messages */
Info->FullPathname = AcpiNsGetNormalizedPathname (Info->Node, TRUE);
if (!Info->FullPathname)
{
return_ACPI_STATUS (AE_NO_MEMORY);
}
/* Count the number of arguments being passed in */
Info->ParamCount = 0;
if (Info->Parameters)
{
while (Info->Parameters[Info->ParamCount])
{
Info->ParamCount++;
}
/* Warn on impossible argument count */
if (Info->ParamCount > ACPI_METHOD_NUM_ARGS)
{
ACPI_WARN_PREDEFINED ((AE_INFO, Info->FullPathname, ACPI_WARN_ALWAYS,
"Excess arguments (%u) - using only %u",
Info->ParamCount, ACPI_METHOD_NUM_ARGS));
Info->ParamCount = ACPI_METHOD_NUM_ARGS;
}
}
/*
* For predefined names: Check that the declared argument count
* matches the ACPI spec -- otherwise this is a BIOS error.
*/
AcpiNsCheckAcpiCompliance (Info->FullPathname, Info->Node,
Info->Predefined);
/*
* For all names: Check that the incoming argument count for
* this method/object matches the actual ASL/AML definition.
*/
AcpiNsCheckArgumentCount (Info->FullPathname, Info->Node,
Info->ParamCount, Info->Predefined);
/* For predefined names: Typecheck all incoming arguments */
AcpiNsCheckArgumentTypes (Info);
/*
* Three major evaluation cases:
*
* 1) Object types that cannot be evaluated by definition
* 2) The object is a control method -- execute it
* 3) The object is not a method -- just return it's current value
*/
switch (AcpiNsGetType (Info->Node))
{
case ACPI_TYPE_DEVICE:
case ACPI_TYPE_EVENT:
case ACPI_TYPE_MUTEX:
case ACPI_TYPE_REGION:
case ACPI_TYPE_THERMAL:
case ACPI_TYPE_LOCAL_SCOPE:
/*
* 1) Disallow evaluation of certain object types. For these,
* object evaluation is undefined and not supported.
*/
ACPI_ERROR ((AE_INFO,
"%s: Evaluation of object type [%s] is not supported",
Info->FullPathname,
AcpiUtGetTypeName (Info->Node->Type)));
Status = AE_TYPE;
goto Cleanup;
case ACPI_TYPE_METHOD:
/*
* 2) Object is a control method - execute it
*/
/* Verify that there is a method object associated with this node */
if (!Info->ObjDesc)
{
ACPI_ERROR ((AE_INFO, "%s: Method has no attached sub-object",
Info->FullPathname));
Status = AE_NULL_OBJECT;
goto Cleanup;
}
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC,
"**** Execute method [%s] at AML address %p length %X\n",
Info->FullPathname,
Info->ObjDesc->Method.AmlStart + 1,
Info->ObjDesc->Method.AmlLength - 1));
/*
* Any namespace deletion must acquire both the namespace and
* interpreter locks to ensure that no thread is using the portion of
* the namespace that is being deleted.
*
* Execute the method via the interpreter. The interpreter is locked
* here before calling into the AML parser
*/
AcpiExEnterInterpreter ();
Status = AcpiPsExecuteMethod (Info);
AcpiExExitInterpreter ();
break;
default:
/*
* 3) All other non-method objects -- get the current object value
*/
/*
* Some objects require additional resolution steps (e.g., the Node
* may be a field that must be read, etc.) -- we can't just grab
* the object out of the node.
*
* Use ResolveNodeToValue() to get the associated value.
*
* NOTE: we can get away with passing in NULL for a walk state because
* the Node is guaranteed to not be a reference to either a method
* local or a method argument (because this interface is never called
* from a running method.)
*
* Even though we do not directly invoke the interpreter for object
* resolution, we must lock it because we could access an OpRegion.
* The OpRegion access code assumes that the interpreter is locked.
*/
AcpiExEnterInterpreter ();
/* TBD: ResolveNodeToValue has a strange interface, fix */
Info->ReturnObject = ACPI_CAST_PTR (ACPI_OPERAND_OBJECT, Info->Node);
Status = AcpiExResolveNodeToValue (ACPI_CAST_INDIRECT_PTR (
ACPI_NAMESPACE_NODE, &Info->ReturnObject), NULL);
AcpiExExitInterpreter ();
if (ACPI_FAILURE (Status))
{
Info->ReturnObject = NULL;
goto Cleanup;
}
ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Returned object %p [%s]\n",
Info->ReturnObject,
AcpiUtGetObjectTypeName (Info->ReturnObject)));
Status = AE_CTRL_RETURN_VALUE; /* Always has a "return value" */
break;
}
/*
* For predefined names, check the return value against the ACPI
* specification. Some incorrect return value types are repaired.
*/
(void) AcpiNsCheckReturnValue (Info->Node, Info, Info->ParamCount,
Status, &Info->ReturnObject);
/* Check if there is a return value that must be dealt with */
if (Status == AE_CTRL_RETURN_VALUE)
{
/* If caller does not want the return value, delete it */
if (Info->Flags & ACPI_IGNORE_RETURN_VALUE)
{
AcpiUtRemoveReference (Info->ReturnObject);
Info->ReturnObject = NULL;
}
/* Map AE_CTRL_RETURN_VALUE to AE_OK, we are done with it */
Status = AE_OK;
}
ACPI_DEBUG_PRINT ((ACPI_DB_NAMES,
"*** Completed evaluation of object %s ***\n",
Info->RelativePathname));
Cleanup:
/*
* Namespace was unlocked by the handling AcpiNs* function, so we
* just free the pathname and return
*/
ACPI_FREE (Info->FullPathname);
Info->FullPathname = NULL;
return_ACPI_STATUS (Status);
}
Commit Message: acpi: acpica: fix acpi operand cache leak in nseval.c
I found an ACPI cache leak in ACPI early termination and boot continuing case.
When early termination occurs due to malicious ACPI table, Linux kernel
terminates ACPI function and continues to boot process. While kernel terminates
ACPI function, kmem_cache_destroy() reports Acpi-Operand cache leak.
Boot log of ACPI operand cache leak is as follows:
>[ 0.464168] ACPI: Added _OSI(Module Device)
>[ 0.467022] ACPI: Added _OSI(Processor Device)
>[ 0.469376] ACPI: Added _OSI(3.0 _SCP Extensions)
>[ 0.471647] ACPI: Added _OSI(Processor Aggregator Device)
>[ 0.477997] ACPI Error: Null stack entry at ffff880215c0aad8 (20170303/exresop-174)
>[ 0.482706] ACPI Exception: AE_AML_INTERNAL, While resolving operands for [OpcodeName unavailable] (20170303/dswexec-461)
>[ 0.487503] ACPI Error: Method parse/execution failed [\DBG] (Node ffff88021710ab40), AE_AML_INTERNAL (20170303/psparse-543)
>[ 0.492136] ACPI Error: Method parse/execution failed [\_SB._INI] (Node ffff88021710a618), AE_AML_INTERNAL (20170303/psparse-543)
>[ 0.497683] ACPI: Interpreter enabled
>[ 0.499385] ACPI: (supports S0)
>[ 0.501151] ACPI: Using IOAPIC for interrupt routing
>[ 0.503342] ACPI Error: Null stack entry at ffff880215c0aad8 (20170303/exresop-174)
>[ 0.506522] ACPI Exception: AE_AML_INTERNAL, While resolving operands for [OpcodeName unavailable] (20170303/dswexec-461)
>[ 0.510463] ACPI Error: Method parse/execution failed [\DBG] (Node ffff88021710ab40), AE_AML_INTERNAL (20170303/psparse-543)
>[ 0.514477] ACPI Error: Method parse/execution failed [\_PIC] (Node ffff88021710ab18), AE_AML_INTERNAL (20170303/psparse-543)
>[ 0.518867] ACPI Exception: AE_AML_INTERNAL, Evaluating _PIC (20170303/bus-991)
>[ 0.522384] kmem_cache_destroy Acpi-Operand: Slab cache still has objects
>[ 0.524597] CPU: 1 PID: 1 Comm: swapper/0 Not tainted 4.12.0-rc5 #26
>[ 0.526795] Hardware name: innotek GmbH VirtualBox/VirtualBox, BIOS VirtualBox 12/01/2006
>[ 0.529668] Call Trace:
>[ 0.530811] ? dump_stack+0x5c/0x81
>[ 0.532240] ? kmem_cache_destroy+0x1aa/0x1c0
>[ 0.533905] ? acpi_os_delete_cache+0xa/0x10
>[ 0.535497] ? acpi_ut_delete_caches+0x3f/0x7b
>[ 0.537237] ? acpi_terminate+0xa/0x14
>[ 0.538701] ? acpi_init+0x2af/0x34f
>[ 0.540008] ? acpi_sleep_proc_init+0x27/0x27
>[ 0.541593] ? do_one_initcall+0x4e/0x1a0
>[ 0.543008] ? kernel_init_freeable+0x19e/0x21f
>[ 0.546202] ? rest_init+0x80/0x80
>[ 0.547513] ? kernel_init+0xa/0x100
>[ 0.548817] ? ret_from_fork+0x25/0x30
>[ 0.550587] vgaarb: loaded
>[ 0.551716] EDAC MC: Ver: 3.0.0
>[ 0.553744] PCI: Probing PCI hardware
>[ 0.555038] PCI host bridge to bus 0000:00
> ... Continue to boot and log is omitted ...
I analyzed this memory leak in detail and found AcpiNsEvaluate() function
only removes Info->ReturnObject in AE_CTRL_RETURN_VALUE case. But, when errors
occur, the status value is not AE_CTRL_RETURN_VALUE, and Info->ReturnObject is
also not null. Therefore, this causes acpi operand memory leak.
This cache leak causes a security threat because an old kernel (<= 4.9) shows
memory locations of kernel functions in stack dump. Some malicious users
could use this information to neutralize kernel ASLR.
I made a patch to fix ACPI operand cache leak.
Signed-off-by: Seunghun Han <[email protected]>
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadPICTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define ThrowPICTException(exception,message) \
{ \
if (tile_image != (Image *) NULL) \
tile_image=DestroyImage(tile_image); \
if (read_info != (ImageInfo *) NULL) \
read_info=DestroyImageInfo(read_info); \
ThrowReaderException((exception),(message)); \
}
char
geometry[MagickPathExtent],
header_ole[4];
Image
*image,
*tile_image;
ImageInfo
*read_info;
int
c,
code;
MagickBooleanType
jpeg,
status;
PICTRectangle
frame;
PICTPixmap
pixmap;
Quantum
index;
register Quantum
*q;
register ssize_t
i,
x;
size_t
extent,
length;
ssize_t
count,
flags,
j,
version,
y;
StringInfo
*profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PICT header.
*/
read_info=(ImageInfo *) NULL;
tile_image=(Image *) NULL;
pixmap.bits_per_pixel=0;
pixmap.component_count=0;
/*
Skip header : 512 for standard PICT and 4, ie "PICT" for OLE2.
*/
header_ole[0]=ReadBlobByte(image);
header_ole[1]=ReadBlobByte(image);
header_ole[2]=ReadBlobByte(image);
header_ole[3]=ReadBlobByte(image);
if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) &&
(header_ole[2] == 0x43) && (header_ole[3] == 0x54 )))
for (i=0; i < 508; i++)
if (ReadBlobByte(image) == EOF)
break;
(void) ReadBlobMSBShort(image); /* skip picture size */
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
while ((c=ReadBlobByte(image)) == 0) ;
if (c != 0x11)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
version=(ssize_t) ReadBlobByte(image);
if (version == 2)
{
c=ReadBlobByte(image);
if (c != 0xff)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
}
else
if (version != 1)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) ||
(frame.bottom < 0) || (frame.left >= frame.right) ||
(frame.top >= frame.bottom))
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
/*
Create black canvas.
*/
flags=0;
image->depth=8;
image->columns=(size_t) (frame.right-frame.left);
image->rows=(size_t) (frame.bottom-frame.top);
image->resolution.x=DefaultResolution;
image->resolution.y=DefaultResolution;
image->units=UndefinedResolution;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status != MagickFalse)
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Interpret PICT opcodes.
*/
jpeg=MagickFalse;
for (code=0; EOFBlob(image) == MagickFalse; )
{
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((version == 1) || ((TellBlob(image) % 2) != 0))
code=ReadBlobByte(image);
if (version == 2)
code=ReadBlobMSBSignedShort(image);
if (code < 0)
break;
if (code == 0)
continue;
if (code > 0xa1)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"%04X:",code);
}
else
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %04X %s: %s",code,codes[code].name,codes[code].description);
switch (code)
{
case 0x01:
{
/*
Clipping rectangle.
*/
length=ReadBlobMSBShort(image);
if (length != 0x000a)
{
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0))
break;
image->columns=(size_t) (frame.right-frame.left);
image->rows=(size_t) (frame.bottom-frame.top);
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status != MagickFalse)
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
break;
}
case 0x12:
case 0x13:
case 0x14:
{
ssize_t
pattern;
size_t
height,
width;
/*
Skip pattern definition.
*/
pattern=(ssize_t) ReadBlobMSBShort(image);
for (i=0; i < 8; i++)
if (ReadBlobByte(image) == EOF)
break;
if (pattern == 2)
{
for (i=0; i < 5; i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
if (pattern != 1)
ThrowPICTException(CorruptImageError,"UnknownPatternType");
length=ReadBlobMSBShort(image);
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (ReadPixmap(image,&pixmap) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
image->depth=(size_t) pixmap.component_size;
image->resolution.x=1.0*pixmap.horizontal_resolution;
image->resolution.y=1.0*pixmap.vertical_resolution;
image->units=PixelsPerInchResolution;
(void) ReadBlobMSBLong(image);
flags=(ssize_t) ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
for (i=0; i <= (ssize_t) length; i++)
(void) ReadBlobMSBLong(image);
width=(size_t) (frame.bottom-frame.top);
height=(size_t) (frame.right-frame.left);
if (pixmap.bits_per_pixel <= 8)
length&=0x7fff;
if (pixmap.bits_per_pixel == 16)
width<<=1;
if (length == 0)
length=width;
if (length < 8)
{
for (i=0; i < (ssize_t) (length*height); i++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (i=0; i < (ssize_t) height; i++)
{
if (EOFBlob(image) != MagickFalse)
break;
if (length > 200)
{
for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++)
if (ReadBlobByte(image) == EOF)
break;
}
else
for (j=0; j < (ssize_t) ReadBlobByte(image); j++)
if (ReadBlobByte(image) == EOF)
break;
}
break;
}
case 0x1b:
{
/*
Initialize image background color.
*/
image->background_color.red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
image->background_color.blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
break;
}
case 0x70:
case 0x71:
case 0x72:
case 0x73:
case 0x74:
case 0x75:
case 0x76:
case 0x77:
{
/*
Skip polygon or region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
break;
}
case 0x90:
case 0x91:
case 0x98:
case 0x99:
case 0x9a:
case 0x9b:
{
PICTRectangle
source,
destination;
register unsigned char
*p;
size_t
j;
ssize_t
bytes_per_line;
unsigned char
*pixels;
/*
Pixmap clipped by a rectangle.
*/
bytes_per_line=0;
if ((code != 0x9a) && (code != 0x9b))
bytes_per_line=(ssize_t) ReadBlobMSBShort(image);
else
{
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
}
if (ReadRectangle(image,&frame) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
/*
Initialize tile image.
*/
tile_image=CloneImage(image,(size_t) (frame.right-frame.left),
(size_t) (frame.bottom-frame.top),MagickTrue,exception);
if (tile_image == (Image *) NULL)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
{
if (ReadPixmap(image,&pixmap) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
tile_image->depth=(size_t) pixmap.component_size;
tile_image->alpha_trait=pixmap.component_count == 4 ?
BlendPixelTrait : UndefinedPixelTrait;
tile_image->resolution.x=(double) pixmap.horizontal_resolution;
tile_image->resolution.y=(double) pixmap.vertical_resolution;
tile_image->units=PixelsPerInchResolution;
if (tile_image->alpha_trait != UndefinedPixelTrait)
(void) SetImageAlpha(tile_image,OpaqueAlpha,exception);
}
if ((code != 0x9a) && (code != 0x9b))
{
/*
Initialize colormap.
*/
tile_image->colors=2;
if ((bytes_per_line & 0x8000) != 0)
{
(void) ReadBlobMSBLong(image);
flags=(ssize_t) ReadBlobMSBShort(image);
tile_image->colors=1UL*ReadBlobMSBShort(image)+1;
}
status=AcquireImageColormap(tile_image,tile_image->colors,
exception);
if (status == MagickFalse)
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
if ((bytes_per_line & 0x8000) != 0)
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
j=ReadBlobMSBShort(image) % tile_image->colors;
if ((flags & 0x8000) != 0)
j=(size_t) i;
tile_image->colormap[j].red=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].green=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
tile_image->colormap[j].blue=(Quantum)
ScaleShortToQuantum(ReadBlobMSBShort(image));
}
}
else
{
for (i=0; i < (ssize_t) tile_image->colors; i++)
{
tile_image->colormap[i].red=(Quantum) (QuantumRange-
tile_image->colormap[i].red);
tile_image->colormap[i].green=(Quantum) (QuantumRange-
tile_image->colormap[i].green);
tile_image->colormap[i].blue=(Quantum) (QuantumRange-
tile_image->colormap[i].blue);
}
}
}
if (EOFBlob(image) != MagickFalse)
ThrowPICTException(CorruptImageError,
"InsufficientImageDataInFile");
if (ReadRectangle(image,&source) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
if (ReadRectangle(image,&destination) == MagickFalse)
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlobMSBShort(image);
if ((code == 0x91) || (code == 0x99) || (code == 0x9b))
{
/*
Skip region.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) (length-2); i++)
if (ReadBlobByte(image) == EOF)
break;
}
if ((code != 0x9a) && (code != 0x9b) &&
(bytes_per_line & 0x8000) == 0)
pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,1,
&extent);
else
pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,
(unsigned int) pixmap.bits_per_pixel,&extent);
if (pixels == (unsigned char *) NULL)
ThrowPICTException(CorruptImageError,"UnableToUncompressImage");
/*
Convert PICT tile image to pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
if (p > (pixels+extent+image->columns))
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowPICTException(CorruptImageError,"NotEnoughPixelData");
}
q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
if (tile_image->storage_class == PseudoClass)
{
index=(Quantum) ConstrainColormapIndex(tile_image,(ssize_t)
*p,exception);
SetPixelIndex(tile_image,index,q);
SetPixelRed(tile_image,
tile_image->colormap[(ssize_t) index].red,q);
SetPixelGreen(tile_image,
tile_image->colormap[(ssize_t) index].green,q);
SetPixelBlue(tile_image,
tile_image->colormap[(ssize_t) index].blue,q);
}
else
{
if (pixmap.bits_per_pixel == 16)
{
i=(ssize_t) (*p++);
j=(size_t) (*p);
SetPixelRed(tile_image,ScaleCharToQuantum(
(unsigned char) ((i & 0x7c) << 1)),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
(unsigned char) (((i & 0x03) << 6) |
((j & 0xe0) >> 2))),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
(unsigned char) ((j & 0x1f) << 3)),q);
}
else
if (tile_image->alpha_trait == UndefinedPixelTrait)
{
if (p > (pixels+extent+2*image->columns))
ThrowPICTException(CorruptImageError,
"NotEnoughPixelData");
SetPixelRed(tile_image,ScaleCharToQuantum(*p),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
*(p+tile_image->columns)),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
*(p+2*tile_image->columns)),q);
}
else
{
if (p > (pixels+extent+3*image->columns))
ThrowPICTException(CorruptImageError,
"NotEnoughPixelData");
SetPixelAlpha(tile_image,ScaleCharToQuantum(*p),q);
SetPixelRed(tile_image,ScaleCharToQuantum(
*(p+tile_image->columns)),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(
*(p+2*tile_image->columns)),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(
*(p+3*tile_image->columns)),q);
}
}
p++;
q+=GetPixelChannels(tile_image);
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
if ((tile_image->storage_class == DirectClass) &&
(pixmap.bits_per_pixel != 16))
{
p+=(pixmap.component_count-1)*tile_image->columns;
if (p < pixels)
break;
}
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
tile_image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if ((jpeg == MagickFalse) && (EOFBlob(image) == MagickFalse))
if ((code == 0x9a) || (code == 0x9b) ||
((bytes_per_line & 0x8000) != 0))
(void) CompositeImage(image,tile_image,CopyCompositeOp,
MagickTrue,(ssize_t) destination.left,(ssize_t)
destination.top,exception);
tile_image=DestroyImage(tile_image);
break;
}
case 0xa1:
{
unsigned char
*info;
size_t
type;
/*
Comment.
*/
type=ReadBlobMSBShort(image);
length=ReadBlobMSBShort(image);
if (length == 0)
break;
(void) ReadBlobMSBLong(image);
length-=MagickMin(length,4);
if (length == 0)
break;
info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info));
if (info == (unsigned char *) NULL)
break;
count=ReadBlob(image,length,info);
if (count != (ssize_t) length)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,"UnableToReadImageData");
}
switch (type)
{
case 0xe0:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"icc",profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
}
break;
}
case 0x1f2:
{
profile=BlobToStringInfo((const void *) NULL,length);
SetStringInfoDatum(profile,info);
status=SetImageProfile(image,"iptc",profile,exception);
if (status == MagickFalse)
{
info=(unsigned char *) RelinquishMagickMemory(info);
ThrowPICTException(ResourceLimitError,
"MemoryAllocationFailed");
}
profile=DestroyStringInfo(profile);
break;
}
default:
break;
}
info=(unsigned char *) RelinquishMagickMemory(info);
break;
}
default:
{
/*
Skip to next op code.
*/
if (codes[code].length == -1)
(void) ReadBlobMSBShort(image);
else
for (i=0; i < (ssize_t) codes[code].length; i++)
if (ReadBlobByte(image) == EOF)
break;
}
}
}
if (code == 0xc00)
{
/*
Skip header.
*/
for (i=0; i < 24; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if (((code >= 0xb0) && (code <= 0xcf)) ||
((code >= 0x8000) && (code <= 0x80ff)))
continue;
if (code == 0x8200)
{
char
filename[MaxTextExtent];
FILE
*file;
int
unique_file;
/*
Embedded JPEG.
*/
jpeg=MagickTrue;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s",
filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) RelinquishUniqueFileResource(read_info->filename);
(void) CopyMagickString(image->filename,read_info->filename,
MagickPathExtent);
ThrowPICTException(FileOpenError,"UnableToCreateTemporaryFile");
}
length=ReadBlobMSBLong(image);
if (length > 154)
{
for (i=0; i < 6; i++)
(void) ReadBlobMSBLong(image);
if (ReadRectangle(image,&frame) == MagickFalse)
{
(void) fclose(file);
(void) RelinquishUniqueFileResource(read_info->filename);
ThrowPICTException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < 122; i++)
if (ReadBlobByte(image) == EOF)
break;
for (i=0; i < (ssize_t) (length-154); i++)
{
c=ReadBlobByte(image);
if (c == EOF)
break;
(void) fputc(c,file);
}
}
(void) fclose(file);
(void) close(unique_file);
tile_image=ReadImage(read_info,exception);
(void) RelinquishUniqueFileResource(filename);
read_info=DestroyImageInfo(read_info);
if (tile_image == (Image *) NULL)
continue;
(void) FormatLocaleString(geometry,MagickPathExtent,"%.20gx%.20g",
(double) MagickMax(image->columns,tile_image->columns),
(double) MagickMax(image->rows,tile_image->rows));
(void) SetImageExtent(image,
MagickMax(image->columns,tile_image->columns),
MagickMax(image->rows,tile_image->rows),exception);
(void) TransformImageColorspace(image,tile_image->colorspace,exception);
(void) CompositeImage(image,tile_image,CopyCompositeOp,MagickTrue,
(ssize_t) frame.left,(ssize_t) frame.right,exception);
image->compression=tile_image->compression;
tile_image=DestroyImage(tile_image);
continue;
}
if ((code == 0xff) || (code == 0xffff))
break;
if (((code >= 0xd0) && (code <= 0xfe)) ||
((code >= 0x8100) && (code <= 0xffff)))
{
/*
Skip reserved.
*/
length=ReadBlobMSBShort(image);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
if ((code >= 0x100) && (code <= 0x7fff))
{
/*
Skip reserved.
*/
length=(size_t) ((code >> 7) & 0xff);
for (i=0; i < (ssize_t) length; i++)
if (ReadBlobByte(image) == EOF)
break;
continue;
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1199
CWE ID: CWE-20
Target: 1
Example 2:
Code: SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
{
return query_info(xid, tcon, persistent_fid, volatile_fid,
FILE_INTERNAL_INFORMATION,
sizeof(struct smb2_file_internal_info),
sizeof(struct smb2_file_internal_info), uniqueid);
}
Commit Message: [CIFS] Possible null ptr deref in SMB2_tcon
As Raphael Geissert pointed out, tcon_error_exit can dereference tcon
and there is one path in which tcon can be null.
Signed-off-by: Steve French <[email protected]>
CC: Stable <[email protected]> # v3.7+
Reported-by: Raphael Geissert <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ext4_remove_blocks(handle_t *handle, struct inode *inode,
struct ext4_extent *ex,
ext4_lblk_t from, ext4_lblk_t to)
{
unsigned short ee_len = ext4_ext_get_actual_len(ex);
int flags = EXT4_FREE_BLOCKS_FORGET;
if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
flags |= EXT4_FREE_BLOCKS_METADATA;
#ifdef EXTENTS_STATS
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
spin_lock(&sbi->s_ext_stats_lock);
sbi->s_ext_blocks += ee_len;
sbi->s_ext_extents++;
if (ee_len < sbi->s_ext_min)
sbi->s_ext_min = ee_len;
if (ee_len > sbi->s_ext_max)
sbi->s_ext_max = ee_len;
if (ext_depth(inode) > sbi->s_depth_max)
sbi->s_depth_max = ext_depth(inode);
spin_unlock(&sbi->s_ext_stats_lock);
}
#endif
if (from >= le32_to_cpu(ex->ee_block)
&& to == le32_to_cpu(ex->ee_block) + ee_len - 1) {
/* tail removal */
ext4_lblk_t num;
ext4_fsblk_t start;
num = le32_to_cpu(ex->ee_block) + ee_len - from;
start = ext_pblock(ex) + ee_len - num;
ext_debug("free last %u blocks starting %llu\n", num, start);
ext4_free_blocks(handle, inode, 0, start, num, flags);
} else if (from == le32_to_cpu(ex->ee_block)
&& to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {
printk(KERN_INFO "strange request: removal %u-%u from %u:%u\n",
from, to, le32_to_cpu(ex->ee_block), ee_len);
} else {
printk(KERN_INFO "strange request: removal(2) "
"%u-%u from %u:%u\n",
from, to, le32_to_cpu(ex->ee_block), ee_len);
}
return 0;
}
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:
Output: | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.