instruction
stringclasses 1
value | input
stringlengths 306
235k
| output
stringclasses 4
values | __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
#define CFormat "/Filter [ /%s ]\n"
#define ObjectsPerImage 14
#define ThrowPDFException(exception,message) \
{ \
if (xref != (MagickOffsetType *) NULL) \
xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \
ThrowWriterException((exception),(message)); \
}
DisableMSCWarning(4310)
static const char
XMPProfile[]=
{
"<?xpacket begin=\"%s\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\">\n"
" <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n"
" <xap:ModifyDate>%s</xap:ModifyDate>\n"
" <xap:CreateDate>%s</xap:CreateDate>\n"
" <xap:MetadataDate>%s</xap:MetadataDate>\n"
" <xap:CreatorTool>%s</xap:CreatorTool>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"
" <dc:format>application/pdf</dc:format>\n"
" <dc:title>\n"
" <rdf:Alt>\n"
" <rdf:li xml:lang=\"x-default\">%s</rdf:li>\n"
" </rdf:Alt>\n"
" </dc:title>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n"
" <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\n"
" <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n"
" <pdf:Producer>%s</pdf:Producer>\n"
" </rdf:Description>\n"
" <rdf:Description rdf:about=\"\"\n"
" xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n"
" <pdfaid:part>3</pdfaid:part>\n"
" <pdfaid:conformance>B</pdfaid:conformance>\n"
" </rdf:Description>\n"
" </rdf:RDF>\n"
"</x:xmpmeta>\n"
"<?xpacket end=\"w\"?>\n"
},
XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 };
RestoreMSCWarning
char
basename[MagickPathExtent],
buffer[MagickPathExtent],
*escape,
date[MagickPathExtent],
**labels,
page_geometry[MagickPathExtent],
*url;
CompressionType
compression;
const char
*device,
*option,
*value;
const StringInfo
*profile;
double
pointsize;
GeometryInfo
geometry_info;
Image
*next,
*tile_image;
MagickBooleanType
status;
MagickOffsetType
offset,
scene,
*xref;
MagickSizeType
number_pixels;
MagickStatusType
flags;
PointInfo
delta,
resolution,
scale;
RectangleInfo
geometry,
media_info,
page_info;
register const Quantum
*p;
register unsigned char
*q;
register ssize_t
i,
x;
size_t
channels,
imageListLength,
info_id,
length,
object,
pages_id,
root_id,
text_size,
version;
ssize_t
count,
page_count,
y;
struct tm
local_time;
time_t
seconds;
unsigned char
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
/*
Allocate X ref memory.
*/
xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref));
if (xref == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(xref,0,2048UL*sizeof(*xref));
/*
Write Info object.
*/
object=0;
version=3;
if (image_info->compression == JPEG2000Compression)
version=(size_t) MagickMax(version,5);
for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
if (next->alpha_trait != UndefinedPixelTrait)
version=(size_t) MagickMax(version,4);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
version=(size_t) MagickMax(version,6);
profile=GetImageProfile(image,"icc");
if (profile != (StringInfo *) NULL)
version=(size_t) MagickMax(version,7);
(void) FormatLocaleString(buffer,MagickPathExtent,"%%PDF-1.%.20g \n",(double)
version);
(void) WriteBlobString(image,buffer);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
{
(void) WriteBlobByte(image,'%');
(void) WriteBlobByte(image,0xe2);
(void) WriteBlobByte(image,0xe3);
(void) WriteBlobByte(image,0xcf);
(void) WriteBlobByte(image,0xd3);
(void) WriteBlobByte(image,'\n');
}
/*
Write Catalog object.
*/
xref[object++]=TellBlob(image);
root_id=object;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (LocaleCompare(image_info->magick,"PDFA") != 0)
(void) FormatLocaleString(buffer,MagickPathExtent,"/Pages %.20g 0 R\n",
(double) object+1);
else
{
(void) FormatLocaleString(buffer,MagickPathExtent,"/Metadata %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Pages %.20g 0 R\n",
(double) object+2);
}
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Type /Catalog");
option=GetImageOption(image_info,"pdf:page-direction");
if ((option != (const char *) NULL) &&
(LocaleCompare(option,"right-to-left") == 0))
(void) WriteBlobString(image,"/ViewerPreferences<</PageDirection/R2L>>\n");
(void) WriteBlobString(image,"\n");
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
GetPathComponent(image->filename,BasePath,basename);
if (LocaleCompare(image_info->magick,"PDFA") == 0)
{
char
create_date[MagickPathExtent],
modify_date[MagickPathExtent],
timestamp[MagickPathExtent],
*url,
xmp_profile[MagickPathExtent];
/*
Write XMP object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Subtype /XML\n");
*modify_date='\0';
value=GetImageProperty(image,"date:modify",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(modify_date,value,MagickPathExtent);
*create_date='\0';
value=GetImageProperty(image,"date:create",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(create_date,value,MagickPathExtent);
(void) FormatMagickTime(time((time_t *) NULL),MagickPathExtent,timestamp);
url=(char *) MagickAuthoritativeURL;
escape=EscapeParenthesis(basename);
i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile,
XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url);
escape=DestroyString(escape);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g\n",
(double) i);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Type /Metadata\n");
(void) WriteBlobString(image,">>\nstream\n");
(void) WriteBlobString(image,xmp_profile);
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
}
/*
Write Pages object.
*/
xref[object++]=TellBlob(image);
pages_id=object;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /Pages\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Kids [ %.20g 0 R ",
(double) object+1);
(void) WriteBlobString(image,buffer);
count=(ssize_t) (pages_id+ObjectsPerImage+1);
page_count=1;
if (image_info->adjoin != MagickFalse)
{
Image
*kid_image;
/*
Predict page object id's.
*/
kid_image=image;
for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage)
{
page_count++;
profile=GetImageProfile(kid_image,"icc");
if (profile != (StringInfo *) NULL)
count+=2;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 R ",(double)
count);
(void) WriteBlobString(image,buffer);
kid_image=GetNextImageInList(kid_image);
}
xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL,
sizeof(*xref));
if (xref == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) WriteBlobString(image,"]\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Count %.20g\n",(double)
page_count);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
scene=0;
imageListLength=GetImageListLength(image);
do
{
MagickBooleanType
has_icc_profile;
profile=GetImageProfile(image,"icc");
has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse;
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if ((SetImageMonochrome(image,exception) == MagickFalse) ||
(image->alpha_trait != UndefinedPixelTrait))
compression=RLECompression;
break;
}
#if !defined(MAGICKCORE_JPEG_DELEGATE)
case JPEGCompression:
{
compression=RLECompression;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)",
image->filename);
break;
}
#endif
#if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
case JPEG2000Compression:
{
compression=RLECompression;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JP2)",
image->filename);
break;
}
#endif
#if !defined(MAGICKCORE_ZLIB_DELEGATE)
case ZipCompression:
{
compression=RLECompression;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)",
image->filename);
break;
}
#endif
case LZWCompression:
{
if (LocaleCompare(image_info->magick,"PDFA") == 0)
compression=RLECompression; /* LZW compression is forbidden */
break;
}
case NoCompression:
{
if (LocaleCompare(image_info->magick,"PDFA") == 0)
compression=RLECompression; /* ASCII 85 compression is forbidden */
break;
}
default:
break;
}
if (compression == JPEG2000Compression)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Scale relative to dots-per-inch.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
resolution.x=image->resolution.x;
resolution.y=image->resolution.y;
if ((resolution.x == 0.0) || (resolution.y == 0.0))
{
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (image_info->density != (char *) NULL)
{
flags=ParseGeometry(image_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
resolution.y=resolution.x;
}
if (image->units == PixelsPerCentimeterResolution)
{
resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0);
resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0);
}
SetGeometry(image,&geometry);
(void) FormatLocaleString(page_geometry,MagickPathExtent,"%.20gx%.20g",
(double) image->columns,(double) image->rows);
if (image_info->page != (char *) NULL)
(void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent);
else
if ((image->page.width != 0) && (image->page.height != 0))
(void) FormatLocaleString(page_geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double)
image->page.height,(double) image->page.x,(double) image->page.y);
else
if ((image->gravity != UndefinedGravity) &&
(LocaleCompare(image_info->magick,"PDF") == 0))
(void) CopyMagickString(page_geometry,PSPageGeometry,
MagickPathExtent);
(void) ConcatenateMagickString(page_geometry,">",MagickPathExtent);
(void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
scale.x=(double) (geometry.width*delta.x)/resolution.x;
geometry.width=(size_t) floor(scale.x+0.5);
scale.y=(double) (geometry.height*delta.y)/resolution.y;
geometry.height=(size_t) floor(scale.y+0.5);
(void) ParseAbsoluteGeometry(page_geometry,&media_info);
(void) ParseGravityGeometry(image,page_geometry,&page_info,exception);
if (image->gravity != UndefinedGravity)
{
geometry.x=(-page_info.x);
geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows);
}
pointsize=12.0;
if (image_info->pointsize != 0.0)
pointsize=image_info->pointsize;
text_size=0;
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
text_size=(size_t) (MultilineCensus(value)*pointsize+12);
(void) text_size;
/*
Write Page object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /Page\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Parent %.20g 0 R\n",
(double) pages_id);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/Resources <<\n");
labels=(char **) NULL;
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
labels=StringToList(value);
if (labels != (char **) NULL)
{
(void) FormatLocaleString(buffer,MagickPathExtent,
"/Font << /F%.20g %.20g 0 R >>\n",(double) image->scene,(double)
object+4);
(void) WriteBlobString(image,buffer);
}
(void) FormatLocaleString(buffer,MagickPathExtent,
"/XObject << /Im%.20g %.20g 0 R >>\n",(double) image->scene,(double)
object+5);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ProcSet %.20g 0 R >>\n",
(double) object+3);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"/MediaBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x,
72.0*media_info.height/resolution.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"/CropBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x,
72.0*media_info.height/resolution.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Contents %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Thumb %.20g 0 R\n",
(double) object+(has_icc_profile != MagickFalse ? 10 : 8));
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Contents object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
(void) WriteBlobString(image,"q\n");
if (labels != (char **) NULL)
for (i=0; labels[i] != (char *) NULL; i++)
{
(void) WriteBlobString(image,"BT\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/F%.20g %g Tf\n",
(double) image->scene,pointsize);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g Td\n",
(double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+
12));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"(%s) Tj\n",
labels[i]);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"ET\n");
labels[i]=DestroyString(labels[i]);
}
(void) FormatLocaleString(buffer,MagickPathExtent,
"%g 0 0 %g %.20g %.20g cm\n",scale.x,scale.y,(double) geometry.x,
(double) geometry.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Im%.20g Do\n",(double)
image->scene);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"Q\n");
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write Procset object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
if ((image->storage_class == DirectClass) || (image->colors > 256))
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageC",MagickPathExtent);
else
if ((compression == FaxCompression) || (compression == Group4Compression))
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageB",MagickPathExtent);
else
(void) CopyMagickString(buffer,"[ /PDF /Text /ImageI",MagickPathExtent);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ]\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Font object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (labels != (char **) NULL)
{
(void) WriteBlobString(image,"/Type /Font\n");
(void) WriteBlobString(image,"/Subtype /Type1\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Name /F%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/BaseFont /Helvetica\n");
(void) WriteBlobString(image,"/Encoding /MacRomanEncoding\n");
labels=(char **) RelinquishMagickMemory(labels);
}
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write XObject object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
(void) WriteBlobString(image,"/Type /XObject\n");
(void) WriteBlobString(image,"/Subtype /Image\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Name /Im%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"ASCII85Decode");
break;
}
case JPEGCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"DCTDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MagickPathExtent);
break;
}
case JPEG2000Compression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"JPXDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MagickPathExtent);
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"FlateDecode");
break;
}
case FaxCompression:
case Group4Compression:
{
(void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n",
MagickPathExtent);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/DecodeParms [ << "
"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam,
(double) image->columns,(double) image->rows);
break;
}
default:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",(double)
image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",(double)
image->rows);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ColorSpace %.20g 0 R\n",
(double) object+2);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/BitsPerComponent %d\n",
(compression == FaxCompression) || (compression == Group4Compression) ?
1 : 8);
(void) WriteBlobString(image,buffer);
if (image->alpha_trait != UndefinedPixelTrait)
{
(void) FormatLocaleString(buffer,MagickPathExtent,"/SMask %.20g 0 R\n",
(double) object+(has_icc_profile != MagickFalse ? 9 : 7));
(void) WriteBlobString(image,buffer);
}
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels)))
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
if ((compression == FaxCompression) || (compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse)))
{
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if (LocaleCompare(CCITTParam,"0") == 0)
{
(void) HuffmanEncodeImage(image_info,image,image,exception);
break;
}
(void) Huffman2DEncodeImage(image_info,image,image,exception);
break;
}
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,image,"jpeg",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,image,"jp2",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p)));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(image,p))));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
}
else
if ((image->storage_class == DirectClass) || (image->colors > 256) ||
(compression == JPEGCompression) ||
(compression == JPEG2000Compression))
switch (compression)
{
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,image,"jpeg",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,image,"jp2",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
length*=image->colorspace == CMYKColorspace ? 4UL : 3UL;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
xref=(MagickOffsetType *) RelinquishMagickMemory(xref);
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runoffset encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
if (image->colorspace == CMYKColorspace)
*q++=ScaleQuantumToChar(GetPixelBlack(image,p));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed DirectColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p)));
Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p)));
Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p)));
if (image->colorspace == CMYKColorspace)
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelBlack(image,p)));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
else
{
/*
Dump number of colors and colormap.
*/
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
xref=(MagickOffsetType *) RelinquishMagickMemory(xref);
ThrowPDFException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) GetPixelIndex(image,p);
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) y,image->rows);
if (status == MagickFalse)
break;
}
}
Ascii85Flush(image);
break;
}
}
}
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write Colorspace object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
device="DeviceRGB";
channels=0;
if (image->colorspace == CMYKColorspace)
{
device="DeviceCMYK";
channels=4;
}
else
if ((compression == FaxCompression) ||
(compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse)))
{
device="DeviceGray";
channels=1;
}
else
if ((image->storage_class == DirectClass) ||
(image->colors > 256) || (compression == JPEGCompression) ||
(compression == JPEG2000Compression))
{
device="DeviceRGB";
channels=3;
}
profile=GetImageProfile(image,"icc");
if ((profile == (StringInfo *) NULL) || (channels == 0))
{
if (channels != 0)
(void) FormatLocaleString(buffer,MagickPathExtent,"/%s\n",device);
else
(void) FormatLocaleString(buffer,MagickPathExtent,
"[ /Indexed /%s %.20g %.20g 0 R ]\n",device,(double) image->colors-
1,(double) object+3);
(void) WriteBlobString(image,buffer);
}
else
{
const unsigned char
*p;
/*
Write ICC profile.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"[/ICCBased %.20g 0 R]\n",(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",
(double) object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"<<\n/N %.20g\n"
"/Filter /ASCII85Decode\n/Length %.20g 0 R\n/Alternate /%s\n>>\n"
"stream\n",(double) channels,(double) object+1,device);
(void) WriteBlobString(image,buffer);
offset=TellBlob(image);
Ascii85Initialize(image);
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)
Ascii85Encode(image,(unsigned char) *p++);
Ascii85Flush(image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"endstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",
(double) object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Thumb object.
*/
SetGeometry(image,&geometry);
(void) ParseMetaGeometry("106x106+0+0>",&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception);
if (tile_image == (Image *) NULL)
return(MagickFalse);
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"ASCII85Decode");
break;
}
case JPEGCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"DCTDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MagickPathExtent);
break;
}
case JPEG2000Compression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"JPXDecode");
if (image->colorspace != CMYKColorspace)
break;
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
MagickPathExtent);
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"FlateDecode");
break;
}
case FaxCompression:
case Group4Compression:
{
(void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n",
MagickPathExtent);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/DecodeParms [ << "
"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam,
(double) tile_image->columns,(double) tile_image->rows);
break;
}
default:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",(double)
tile_image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",(double)
tile_image->rows);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ColorSpace %.20g 0 R\n",
(double) object-(has_icc_profile != MagickFalse ? 3 : 1));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/BitsPerComponent %d\n",
(compression == FaxCompression) || (compression == Group4Compression) ?
1 : 8);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows;
if ((compression == FaxCompression) ||
(compression == Group4Compression) ||
((image_info->type != TrueColorType) &&
(SetImageGray(tile_image,exception) != MagickFalse)))
{
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
if (LocaleCompare(CCITTParam,"0") == 0)
{
(void) HuffmanEncodeImage(image_info,image,tile_image,
exception);
break;
}
(void) Huffman2DEncodeImage(image_info,image,tile_image,exception);
break;
}
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,tile_image,"jpeg",
exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,tile_image,"jp2",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
*q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(
tile_image,p)));
p+=GetPixelChannels(tile_image);
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
GetPixelLuma(tile_image,p))));
p+=GetPixelChannels(tile_image);
}
}
Ascii85Flush(image);
break;
}
}
}
else
if ((tile_image->storage_class == DirectClass) ||
(tile_image->colors > 256) || (compression == JPEGCompression) ||
(compression == JPEG2000Compression))
switch (compression)
{
case JPEGCompression:
{
status=InjectImageBlob(image_info,image,tile_image,"jpeg",
exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case JPEG2000Compression:
{
status=InjectImageBlob(image_info,image,tile_image,"jp2",exception);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL;
pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(tile_image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p));
if (tile_image->colorspace == CMYKColorspace)
*q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p));
p+=GetPixelChannels(tile_image);
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed DirectColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelRed(tile_image,p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelGreen(tile_image,p)));
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelBlue(tile_image,p)));
if (image->colorspace == CMYKColorspace)
Ascii85Encode(image,ScaleQuantumToChar(
GetPixelBlack(tile_image,p)));
p+=GetPixelChannels(tile_image);
}
}
Ascii85Flush(image);
break;
}
}
else
{
/*
Dump number of colors and colormap.
*/
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
tile_image=DestroyImage(tile_image);
ThrowPDFException(ResourceLimitError,
"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
*q++=(unsigned char) GetPixelIndex(tile_image,p);
p+=GetPixelChannels(tile_image);
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
Ascii85Encode(image,(unsigned char)
GetPixelIndex(tile_image,p));
p+=GetPixelChannels(image);
}
}
Ascii85Flush(image);
break;
}
}
}
tile_image=DestroyImage(tile_image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if ((image->storage_class == DirectClass) || (image->colors > 256) ||
(compression == FaxCompression) || (compression == Group4Compression))
(void) WriteBlobString(image,">>\n");
else
{
/*
Write Colormap object.
*/
if (compression == NoCompression)
(void) WriteBlobString(image,"/Filter [ /ASCII85Decode ]\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
if (compression == NoCompression)
Ascii85Initialize(image);
for (i=0; i < (ssize_t) image->colors; i++)
{
if (compression == NoCompression)
{
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[i].red)));
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[i].green)));
Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[i].blue)));
continue;
}
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].red)));
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].green)));
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].blue)));
}
if (compression == NoCompression)
Ascii85Flush(image);
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
/*
Write softmask object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (image->alpha_trait == UndefinedPixelTrait)
(void) WriteBlobString(image,">>\n");
else
{
(void) WriteBlobString(image,"/Type /XObject\n");
(void) WriteBlobString(image,"/Subtype /Image\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Name /Ma%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
switch (compression)
{
case NoCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"ASCII85Decode");
break;
}
case LZWCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"LZWDecode");
break;
}
case ZipCompression:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"FlateDecode");
break;
}
default:
{
(void) FormatLocaleString(buffer,MagickPathExtent,CFormat,
"RunLengthDecode");
break;
}
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",
(double) image->columns);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",
(double) image->rows);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"/ColorSpace /DeviceGray\n");
(void) FormatLocaleString(buffer,MagickPathExtent,
"/BitsPerComponent %d\n",(compression == FaxCompression) ||
(compression == Group4Compression) ? 1 : 8);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n",
(double) object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"stream\n");
offset=TellBlob(image);
number_pixels=(MagickSizeType) image->columns*image->rows;
switch (compression)
{
case RLECompression:
default:
{
MemoryInfo
*pixel_info;
/*
Allocate pixel array.
*/
length=(size_t) number_pixels;
pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
{
image=DestroyImage(image);
ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Dump Runlength encoded pixels.
*/
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (compression == ZipCompression)
status=ZLIBEncodeImage(image,length,pixels,exception);
else
#endif
if (compression == LZWCompression)
status=LZWEncodeImage(image,length,pixels,exception);
else
status=PackbitsEncodeImage(image,length,pixels,exception);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (status == MagickFalse)
{
(void) CloseBlob(image);
return(MagickFalse);
}
break;
}
case NoCompression:
{
/*
Dump uncompressed PseudoColor packets.
*/
Ascii85Initialize(image);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p)));
p+=GetPixelChannels(image);
}
}
Ascii85Flush(image);
break;
}
}
offset=TellBlob(image)-offset;
(void) WriteBlobString(image,"\nendstream\n");
}
(void) WriteBlobString(image,"endobj\n");
/*
Write Length object.
*/
xref[object++]=TellBlob(image);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"endobj\n");
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
/*
Write Metadata object.
*/
xref[object++]=TellBlob(image);
info_id=object;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double)
object);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<<\n");
if (LocaleCompare(image_info->magick,"PDFA") == 0)
(void) FormatLocaleString(buffer,MagickPathExtent,"/Title (%s)\n",
EscapeParenthesis(basename));
else
{
wchar_t
*utf16;
utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length);
if (utf16 != (wchar_t *) NULL)
{
(void) FormatLocaleString(buffer,MagickPathExtent,"/Title (\xfe\xff");
(void) WriteBlobString(image,buffer);
for (i=0; i < (ssize_t) length; i++)
(void) WriteBlobMSBShort(image,(unsigned short) utf16[i]);
(void) FormatLocaleString(buffer,MagickPathExtent,")\n");
utf16=(wchar_t *) RelinquishMagickMemory(utf16);
}
}
(void) WriteBlobString(image,buffer);
seconds=time((time_t *) NULL);
#if defined(MAGICKCORE_HAVE_LOCALTIME_R)
(void) localtime_r(&seconds,&local_time);
#else
(void) memcpy(&local_time,localtime(&seconds),sizeof(local_time));
#endif
(void) FormatLocaleString(date,MagickPathExtent,"D:%04d%02d%02d%02d%02d%02d",
local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday,
local_time.tm_hour,local_time.tm_min,local_time.tm_sec);
(void) FormatLocaleString(buffer,MagickPathExtent,"/CreationDate (%s)\n",
date);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ModDate (%s)\n",date);
(void) WriteBlobString(image,buffer);
url=(char *) MagickAuthoritativeURL;
escape=EscapeParenthesis(url);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Producer (%s)\n",escape);
escape=DestroyString(escape);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"endobj\n");
/*
Write Xref object.
*/
offset=TellBlob(image)-xref[0]+
(LocaleCompare(image_info->magick,"PDFA") == 0 ? 6 : 0)+10;
(void) WriteBlobString(image,"xref\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"0 %.20g\n",(double)
object+1);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"0000000000 65535 f \n");
for (i=0; i < (ssize_t) object; i++)
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%010lu 00000 n \n",
(unsigned long) xref[i]);
(void) WriteBlobString(image,buffer);
}
(void) WriteBlobString(image,"trailer\n");
(void) WriteBlobString(image,"<<\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"/Size %.20g\n",(double)
object+1);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Info %.20g 0 R\n",(double)
info_id);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"/Root %.20g 0 R\n",(double)
root_id);
(void) WriteBlobString(image,buffer);
(void) SignatureImage(image,exception);
(void) FormatLocaleString(buffer,MagickPathExtent,"/ID [<%s> <%s>]\n",
GetImageProperty(image,"signature",exception),
GetImageProperty(image,"signature",exception));
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,">>\n");
(void) WriteBlobString(image,"startxref\n");
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"%%EOF\n");
xref=(MagickOffsetType *) RelinquishMagickMemory(xref);
(void) CloseBlob(image);
return(MagickTrue);
}
Vulnerability Type:
CWE ID: CWE-399
Summary: In ImageMagick before 7.0.8-25 and GraphicsMagick through 1.3.31, several memory leaks exist in WritePDFImage in coders/pdf.c.
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1454 | Low | 169,728 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void V8LazyEventListener::prepareListenerObject(ExecutionContext* executionContext)
{
if (!executionContext)
return;
v8::HandleScope handleScope(toIsolate(executionContext));
v8::Local<v8::Context> v8Context = toV8Context(executionContext, world());
if (v8Context.IsEmpty())
return;
ScriptState* scriptState = ScriptState::from(v8Context);
if (!scriptState->contextIsValid())
return;
if (executionContext->isDocument() && !toDocument(executionContext)->allowInlineEventHandlers(m_node, this, m_sourceURL, m_position.m_line)) {
clearListenerObject();
return;
}
if (hasExistingListenerObject())
return;
ASSERT(executionContext->isDocument());
ScriptState::Scope scope(scriptState);
String listenerSource = InspectorInstrumentation::preprocessEventListener(toDocument(executionContext)->frame(), m_code, m_sourceURL, m_functionName);
String code = "(function() {"
"with (this[2]) {"
"with (this[1]) {"
"with (this[0]) {"
"return function(" + m_eventParameterName + ") {" +
listenerSource + "\n" // Insert '\n' otherwise //-style comments could break the handler.
"};"
"}}}})";
v8::Handle<v8::String> codeExternalString = v8String(isolate(), code);
v8::Local<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(codeExternalString, isolate(), m_sourceURL, m_position);
if (result.IsEmpty())
return;
ASSERT(result->IsFunction());
v8::Local<v8::Function> intermediateFunction = result.As<v8::Function>();
HTMLFormElement* formElement = 0;
if (m_node && m_node->isHTMLElement())
formElement = toHTMLElement(m_node)->formOwner();
v8::Handle<v8::Object> nodeWrapper = toObjectWrapper<Node>(m_node, scriptState);
v8::Handle<v8::Object> formWrapper = toObjectWrapper<HTMLFormElement>(formElement, scriptState);
v8::Handle<v8::Object> documentWrapper = toObjectWrapper<Document>(m_node ? m_node->ownerDocument() : 0, scriptState);
v8::Local<v8::Object> thisObject = v8::Object::New(isolate());
if (thisObject.IsEmpty())
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 0), nodeWrapper))
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 1), formWrapper))
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 2), documentWrapper))
return;
v8::Local<v8::Value> innerValue = V8ScriptRunner::callInternalFunction(intermediateFunction, thisObject, 0, 0, isolate());
if (innerValue.IsEmpty() || !innerValue->IsFunction())
return;
v8::Local<v8::Function> wrappedFunction = innerValue.As<v8::Function>();
v8::Local<v8::Function> toStringFunction = v8::Function::New(isolate(), V8LazyEventListenerToString);
ASSERT(!toStringFunction.IsEmpty());
String toStringString = "function " + m_functionName + "(" + m_eventParameterName + ") {\n " + m_code + "\n}";
V8HiddenValue::setHiddenValue(isolate(), wrappedFunction, V8HiddenValue::toStringString(isolate()), v8String(isolate(), toStringString));
wrappedFunction->Set(v8AtomicString(isolate(), "toString"), toStringFunction);
wrappedFunction->SetName(v8String(isolate(), m_functionName));
setListenerObject(wrappedFunction);
}
Vulnerability Type: DoS
CWE ID: CWE-17
Summary: The V8LazyEventListener::prepareListenerObject function in bindings/core/v8/V8LazyEventListener.cpp in the V8 bindings in Blink, as used in Google Chrome before 41.0.2272.76, does not properly compile listeners, which allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors that leverage *type confusion.*
Commit Message: Turn a bunch of ASSERTs into graceful failures when compiling listeners
BUG=456192
[email protected]
Review URL: https://codereview.chromium.org/906193002
git-svn-id: svn://svn.chromium.org/blink/trunk@189796 bbb929c8-8fbe-4397-9dbb-9b2b20218538 | Low | 172,025 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: xsltParseStylesheetAttributeSet(xsltStylesheetPtr style, xmlNodePtr cur) {
const xmlChar *ncname;
const xmlChar *prefix;
xmlChar *value;
xmlNodePtr child;
xsltAttrElemPtr attrItems;
if ((cur == NULL) || (style == NULL) || (cur->type != XML_ELEMENT_NODE))
return;
value = xmlGetNsProp(cur, (const xmlChar *)"name", NULL);
if (value == NULL) {
xsltGenericError(xsltGenericErrorContext,
"xsl:attribute-set : name is missing\n");
return;
}
ncname = xsltSplitQName(style->dict, value, &prefix);
xmlFree(value);
value = NULL;
if (style->attributeSets == NULL) {
#ifdef WITH_XSLT_DEBUG_ATTRIBUTES
xsltGenericDebug(xsltGenericDebugContext,
"creating attribute set table\n");
#endif
style->attributeSets = xmlHashCreate(10);
}
if (style->attributeSets == NULL)
return;
attrItems = xmlHashLookup2(style->attributeSets, ncname, prefix);
/*
* Parse the content. Only xsl:attribute elements are allowed.
*/
child = cur->children;
while (child != NULL) {
/*
* Report invalid nodes.
*/
if ((child->type != XML_ELEMENT_NODE) ||
(child->ns == NULL) ||
(! IS_XSLT_ELEM(child)))
{
if (child->type == XML_ELEMENT_NODE)
xsltTransformError(NULL, style, child,
"xsl:attribute-set : unexpected child %s\n",
child->name);
else
xsltTransformError(NULL, style, child,
"xsl:attribute-set : child of unexpected type\n");
} else if (!IS_XSLT_NAME(child, "attribute")) {
xsltTransformError(NULL, style, child,
"xsl:attribute-set : unexpected child xsl:%s\n",
child->name);
} else {
#ifdef XSLT_REFACTORED
xsltAttrElemPtr nextAttr, curAttr;
/*
* Process xsl:attribute
* ---------------------
*/
#ifdef WITH_XSLT_DEBUG_ATTRIBUTES
xsltGenericDebug(xsltGenericDebugContext,
"add attribute to list %s\n", ncname);
#endif
/*
* The following was taken over from
* xsltAddAttrElemList().
*/
if (attrItems == NULL) {
attrItems = xsltNewAttrElem(child);
} else {
curAttr = attrItems;
while (curAttr != NULL) {
nextAttr = curAttr->next;
if (curAttr->attr == child) {
/*
* URGENT TODO: Can somebody explain
* why attrItems is set to curAttr
* here? Is this somehow related to
* avoidance of recursions?
*/
attrItems = curAttr;
goto next_child;
}
if (curAttr->next == NULL)
curAttr->next = xsltNewAttrElem(child);
curAttr = nextAttr;
}
}
/*
* Parse the xsl:attribute and its content.
*/
xsltParseAnyXSLTElem(XSLT_CCTXT(style), child);
#else
#ifdef WITH_XSLT_DEBUG_ATTRIBUTES
xsltGenericDebug(xsltGenericDebugContext,
"add attribute to list %s\n", ncname);
#endif
/*
* OLD behaviour:
*/
attrItems = xsltAddAttrElemList(attrItems, child);
#endif
}
#ifdef XSLT_REFACTORED
next_child:
#endif
child = child->next;
}
/*
* Process attribue "use-attribute-sets".
*/
/* TODO check recursion */
value = xmlGetNsProp(cur, (const xmlChar *)"use-attribute-sets",
NULL);
if (value != NULL) {
const xmlChar *curval, *endval;
curval = value;
while (*curval != 0) {
while (IS_BLANK(*curval)) curval++;
if (*curval == 0)
break;
endval = curval;
while ((*endval != 0) && (!IS_BLANK(*endval))) endval++;
curval = xmlDictLookup(style->dict, curval, endval - curval);
if (curval) {
const xmlChar *ncname2 = NULL;
const xmlChar *prefix2 = NULL;
xsltAttrElemPtr refAttrItems;
#ifdef WITH_XSLT_DEBUG_ATTRIBUTES
xsltGenericDebug(xsltGenericDebugContext,
"xsl:attribute-set : %s adds use %s\n", ncname, curval);
#endif
ncname2 = xsltSplitQName(style->dict, curval, &prefix2);
refAttrItems = xsltNewAttrElem(NULL);
if (refAttrItems != NULL) {
refAttrItems->set = ncname2;
refAttrItems->ns = prefix2;
attrItems = xsltMergeAttrElemList(style,
attrItems, refAttrItems);
xsltFreeAttrElem(refAttrItems);
}
}
curval = endval;
}
xmlFree(value);
value = NULL;
}
/*
* Update the value
*/
/*
* TODO: Why is this dummy entry needed.?
*/
if (attrItems == NULL)
attrItems = xsltNewAttrElem(NULL);
xmlHashUpdateEntry2(style->attributeSets, ncname, prefix, attrItems, NULL);
#ifdef WITH_XSLT_DEBUG_ATTRIBUTES
xsltGenericDebug(xsltGenericDebugContext,
"updated attribute list %s\n", ncname);
#endif
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: numbers.c in libxslt before 1.1.29, as used in Google Chrome before 51.0.2704.63, mishandles namespace nodes, which allows remote attackers to cause a denial of service (out-of-bounds heap memory access) or possibly have unspecified other impact via a crafted document.
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338} | High | 173,298 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static int em_jmp_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned short sel;
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = load_segment_descriptor(ctxt, sel, VCPU_SREG_CS);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->_eip = 0;
memcpy(&ctxt->_eip, ctxt->src.valptr, ctxt->op_bytes);
return X86EMUL_CONTINUE;
}
Vulnerability Type: DoS
CWE ID: CWE-264
Summary: arch/x86/kvm/emulate.c in the KVM subsystem in the Linux kernel through 3.17.2 does not properly perform RIP changes, which allows guest OS users to cause a denial of service (guest OS crash) via a crafted application.
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]> | Low | 166,339 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static int vivid_fb_ioctl(struct fb_info *info, unsigned cmd, unsigned long arg)
{
struct vivid_dev *dev = (struct vivid_dev *)info->par;
switch (cmd) {
case FBIOGET_VBLANK: {
struct fb_vblank vblank;
vblank.flags = FB_VBLANK_HAVE_COUNT | FB_VBLANK_HAVE_VCOUNT |
FB_VBLANK_HAVE_VSYNC;
vblank.count = 0;
vblank.vcount = 0;
vblank.hcount = 0;
if (copy_to_user((void __user *)arg, &vblank, sizeof(vblank)))
return -EFAULT;
return 0;
}
default:
dprintk(dev, 1, "Unknown ioctl %08x\n", cmd);
return -EINVAL;
}
return 0;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: The vivid_fb_ioctl function in drivers/media/platform/vivid/vivid-osd.c in the Linux kernel through 4.3.3 does not initialize a certain structure member, which allows local users to obtain sensitive information from kernel memory via a crafted application.
Commit Message: [media] media/vivid-osd: fix info leak in ioctl
The vivid_fb_ioctl() code fails to initialize the 16 _reserved bytes of
struct fb_vblank after the ->hcount member. Add an explicit
memset(0) before filling the structure to avoid the info leak.
Signed-off-by: Salva Peiró <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]> | Medium | 166,575 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: check_entry_size_and_hooks(struct ip6t_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct ip6t_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
Vulnerability Type: DoS Overflow +Priv Mem. Corr.
CWE ID: CWE-119
Summary: The netfilter subsystem in the Linux kernel through 4.5.2 does not validate certain offset fields, which allows local users to gain privileges or cause a denial of service (heap memory corruption) via an IPT_SO_SET_REPLACE setsockopt call.
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]> | Low | 167,372 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
content::CauseForGpuLaunch cause_for_gpu_launch) {
if (gpu_channel_.get()) {
if (gpu_channel_->state() == GpuChannelHost::kUnconnected ||
gpu_channel_->state() == GpuChannelHost::kConnected)
return GetGpuChannel();
gpu_channel_ = NULL;
}
int client_id = 0;
IPC::ChannelHandle channel_handle;
base::ProcessHandle renderer_process_for_gpu;
content::GPUInfo gpu_info;
if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
&client_id,
&channel_handle,
&renderer_process_for_gpu,
&gpu_info)) ||
channel_handle.name.empty() ||
#if defined(OS_POSIX)
channel_handle.socket.fd == -1 ||
#endif
renderer_process_for_gpu == base::kNullProcessHandle) {
gpu_channel_ = NULL;
return NULL;
}
gpu_channel_ = new GpuChannelHost(this, 0, client_id);
gpu_channel_->set_gpu_info(gpu_info);
content::GetContentClient()->SetGpuInfo(gpu_info);
gpu_channel_->Connect(channel_handle, renderer_process_for_gpu);
return GetGpuChannel();
}
Vulnerability Type: DoS
CWE ID:
Summary: Google Chrome before 20.0.1132.43 on Windows does not properly isolate sandboxed processes, which might allow remote attackers to cause a denial of service (process interference) via unspecified vectors.
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 | Low | 170,954 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static MagickBooleanType ClonePixelCacheRepository(
CacheInfo *restrict clone_info,CacheInfo *restrict cache_info,
ExceptionInfo *exception)
{
#define MaxCacheThreads 2
#define cache_threads(source,destination,chunk) \
num_threads((chunk) < (16*GetMagickResourceLimit(ThreadResource)) ? 1 : \
GetMagickResourceLimit(ThreadResource) < MaxCacheThreads ? \
GetMagickResourceLimit(ThreadResource) : MaxCacheThreads)
MagickBooleanType
status;
NexusInfo
**restrict cache_nexus,
**restrict clone_nexus;
size_t
length;
ssize_t
y;
assert(cache_info != (CacheInfo *) NULL);
assert(clone_info != (CacheInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
if (cache_info->type == PingCache)
return(MagickTrue);
if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) &&
((clone_info->type == MemoryCache) || (clone_info->type == MapCache)) &&
(cache_info->columns == clone_info->columns) &&
(cache_info->rows == clone_info->rows) &&
(cache_info->active_index_channel == clone_info->active_index_channel))
{
/*
Identical pixel cache morphology.
*/
CopyPixels(clone_info->pixels,cache_info->pixels,cache_info->columns*
cache_info->rows);
if ((cache_info->active_index_channel != MagickFalse) &&
(clone_info->active_index_channel != MagickFalse))
(void) memcpy(clone_info->indexes,cache_info->indexes,
cache_info->columns*cache_info->rows*sizeof(*cache_info->indexes));
return(MagickTrue);
}
/*
Mismatched pixel cache morphology.
*/
cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads);
clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads);
if ((cache_nexus == (NexusInfo **) NULL) ||
(clone_nexus == (NexusInfo **) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
length=(size_t) MagickMin(cache_info->columns,clone_info->columns)*
sizeof(*cache_info->pixels);
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
cache_threads(cache_info,clone_info,cache_info->rows)
#endif
for (y=0; y < (ssize_t) cache_info->rows; y++)
{
const int
id = GetOpenMPThreadId();
PixelPacket
*pixels;
RectangleInfo
region;
if (status == MagickFalse)
continue;
if (y >= (ssize_t) clone_info->rows)
continue;
region.width=cache_info->columns;
region.height=1;
region.x=0;
region.y=y;
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,MagickTrue,
cache_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception);
if (status == MagickFalse)
continue;
region.width=clone_info->columns;
pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,MagickTrue,
clone_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
(void) ResetMagickMemory(clone_nexus[id]->pixels,0,(size_t)
clone_nexus[id]->length);
(void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length);
status=WritePixelCachePixels(clone_info,clone_nexus[id],exception);
}
if ((cache_info->active_index_channel != MagickFalse) &&
(clone_info->active_index_channel != MagickFalse))
{
/*
Clone indexes.
*/
length=(size_t) MagickMin(cache_info->columns,clone_info->columns)*
sizeof(*cache_info->indexes);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
cache_threads(cache_info,clone_info,cache_info->rows)
#endif
for (y=0; y < (ssize_t) cache_info->rows; y++)
{
const int
id = GetOpenMPThreadId();
PixelPacket
*pixels;
RectangleInfo
region;
if (status == MagickFalse)
continue;
if (y >= (ssize_t) clone_info->rows)
continue;
region.width=cache_info->columns;
region.height=1;
region.x=0;
region.y=y;
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,MagickTrue,
cache_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
status=ReadPixelCacheIndexes(cache_info,cache_nexus[id],exception);
if (status == MagickFalse)
continue;
region.width=clone_info->columns;
pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,MagickTrue,
clone_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
(void) memcpy(clone_nexus[id]->indexes,cache_nexus[id]->indexes,length);
status=WritePixelCacheIndexes(clone_info,clone_nexus[id],exception);
}
}
cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads);
clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads);
if (cache_info->debug != MagickFalse)
{
char
message[MaxTextExtent];
(void) FormatLocaleString(message,MaxTextExtent,"%s => %s",
CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type),
CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type));
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
return(status);
}
Vulnerability Type: DoS
CWE ID: CWE-189
Summary: Off-by-one error in magick/cache.c in ImageMagick allows remote attackers to cause a denial of service (segmentation fault) via unspecified vectors.
Commit Message: | Medium | 168,810 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: int mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx,
mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret;
mbedtls_mpi r, s;
ECDSA_VALIDATE_RET( ctx != NULL );
ECDSA_VALIDATE_RET( hash != NULL );
ECDSA_VALIDATE_RET( sig != NULL );
ECDSA_VALIDATE_RET( slen != NULL );
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
(void) f_rng;
(void) p_rng;
MBEDTLS_MPI_CHK( ecdsa_sign_det_restartable( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, md_alg, rs_ctx ) );
#else
(void) md_alg;
#if defined(MBEDTLS_ECDSA_SIGN_ALT)
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng ) );
#else
MBEDTLS_MPI_CHK( ecdsa_sign_restartable( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng, rs_ctx ) );
#endif /* MBEDTLS_ECDSA_SIGN_ALT */
#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) );
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
return( ret );
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: Arm Mbed TLS before 2.19.0 and Arm Mbed Crypto before 2.0.0, when deterministic ECDSA is enabled, use an RNG with insufficient entropy for blinding, which might allow an attacker to recover a private key via side-channel attacks if a victim signs the same message many times. (For Mbed TLS, the fix is also available in versions 2.7.12 and 2.16.3.)
Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/556' into mbedtls-2.16-restricted | High | 169,509 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void SoftAVC::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
if (mEOSStatus == OUTPUT_FRAMES_FLUSHED) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
if (mHeadersDecoded) {
drainAllOutputBuffers(false /* eos */);
}
H264SwDecRet ret = H264SWDEC_PIC_RDY;
bool portWillReset = false;
while ((mEOSStatus != INPUT_DATA_AVAILABLE || !inQueue.empty())
&& outQueue.size() == kNumOutputBuffers) {
if (mEOSStatus == INPUT_EOS_SEEN) {
drainAllOutputBuffers(true /* eos */);
return;
}
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
++mPicId;
OMX_BUFFERHEADERTYPE *header = new OMX_BUFFERHEADERTYPE;
memset(header, 0, sizeof(OMX_BUFFERHEADERTYPE));
header->nTimeStamp = inHeader->nTimeStamp;
header->nFlags = inHeader->nFlags;
if (header->nFlags & OMX_BUFFERFLAG_EOS) {
mEOSStatus = INPUT_EOS_SEEN;
}
mPicToHeaderMap.add(mPicId, header);
inQueue.erase(inQueue.begin());
H264SwDecInput inPicture;
H264SwDecOutput outPicture;
memset(&inPicture, 0, sizeof(inPicture));
inPicture.dataLen = inHeader->nFilledLen;
inPicture.pStream = inHeader->pBuffer + inHeader->nOffset;
inPicture.picId = mPicId;
inPicture.intraConcealmentMethod = 1;
H264SwDecPicture decodedPicture;
while (inPicture.dataLen > 0) {
ret = H264SwDecDecode(mHandle, &inPicture, &outPicture);
if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY ||
ret == H264SWDEC_PIC_RDY_BUFF_NOT_EMPTY) {
inPicture.dataLen -= (u32)(outPicture.pStrmCurrPos - inPicture.pStream);
inPicture.pStream = outPicture.pStrmCurrPos;
if (ret == H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY) {
mHeadersDecoded = true;
H264SwDecInfo decoderInfo;
CHECK(H264SwDecGetInfo(mHandle, &decoderInfo) == H264SWDEC_OK);
SoftVideoDecoderOMXComponent::CropSettingsMode cropSettingsMode =
handleCropParams(decoderInfo);
handlePortSettingsChange(
&portWillReset, decoderInfo.picWidth, decoderInfo.picHeight,
cropSettingsMode);
}
} else {
if (portWillReset) {
if (H264SwDecNextPicture(mHandle, &decodedPicture, 0)
== H264SWDEC_PIC_RDY) {
saveFirstOutputBuffer(
decodedPicture.picId,
(uint8_t *)decodedPicture.pOutputPicture);
}
}
inPicture.dataLen = 0;
if (ret < 0) {
ALOGE("Decoder failed: %d", ret);
notify(OMX_EventError, OMX_ErrorUndefined,
ERROR_MALFORMED, NULL);
mSignalledError = true;
return;
}
}
}
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
if (portWillReset) {
return;
}
if (mFirstPicture && !outQueue.empty()) {
drainOneOutputBuffer(mFirstPictureId, mFirstPicture);
delete[] mFirstPicture;
mFirstPicture = NULL;
mFirstPictureId = -1;
}
drainAllOutputBuffers(false /* eos */);
}
}
Vulnerability Type: +Priv
CWE ID: CWE-20
Summary: libstagefright in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-06-01 allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 27833616.
Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec
Bug: 27833616
Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0
| Medium | 174,178 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static void smp_task_done(struct sas_task *task)
{
if (!del_timer(&task->slow_task->timer))
return;
complete(&task->slow_task->completion);
}
Vulnerability Type:
CWE ID: CWE-416
Summary: An issue was discovered in the Linux kernel before 4.20. There is a race condition in smp_task_timedout() and smp_task_done() in drivers/scsi/libsas/sas_expander.c, leading to a use-after-free.
Commit Message: scsi: libsas: fix a race condition when smp task timeout
When the lldd is processing the complete sas task in interrupt and set the
task stat as SAS_TASK_STATE_DONE, the smp timeout timer is able to be
triggered at the same time. And smp_task_timedout() will complete the task
wheter the SAS_TASK_STATE_DONE is set or not. Then the sas task may freed
before lldd end the interrupt process. Thus a use-after-free will happen.
Fix this by calling the complete() only when SAS_TASK_STATE_DONE is not
set. And remove the check of the return value of the del_timer(). Once the
LLDD sets DONE, it must call task->done(), which will call
smp_task_done()->complete() and the task will be completed and freed
correctly.
Reported-by: chenxiang <[email protected]>
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
CC: Hannes Reinecke <[email protected]>
Reviewed-by: Hannes Reinecke <[email protected]>
Reviewed-by: John Garry <[email protected]>
Reviewed-by: Johannes Thumshirn <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]> | Medium | 169,782 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers(
extensions::Dispatcher* dispatcher,
extensions::ModuleSystem* module_system,
extensions::ScriptContext* context) {
module_system->RegisterNativeHandler(
"app", std::unique_ptr<NativeHandler>(
new extensions::AppBindings(dispatcher, context)));
module_system->RegisterNativeHandler(
"sync_file_system",
std::unique_ptr<NativeHandler>(
new extensions::SyncFileSystemCustomBindings(context)));
module_system->RegisterNativeHandler(
"file_browser_handler",
std::unique_ptr<NativeHandler>(
new extensions::FileBrowserHandlerCustomBindings(context)));
module_system->RegisterNativeHandler(
"file_manager_private",
std::unique_ptr<NativeHandler>(
new extensions::FileManagerPrivateCustomBindings(context)));
module_system->RegisterNativeHandler(
"notifications_private",
std::unique_ptr<NativeHandler>(
new extensions::NotificationsNativeHandler(context)));
module_system->RegisterNativeHandler(
"mediaGalleries",
std::unique_ptr<NativeHandler>(
new extensions::MediaGalleriesCustomBindings(context)));
module_system->RegisterNativeHandler(
"page_capture", std::unique_ptr<NativeHandler>(
new extensions::PageCaptureCustomBindings(context)));
module_system->RegisterNativeHandler(
"platform_keys_natives",
std::unique_ptr<NativeHandler>(
new extensions::PlatformKeysNatives(context)));
module_system->RegisterNativeHandler(
"tabs", std::unique_ptr<NativeHandler>(
new extensions::TabsCustomBindings(context)));
module_system->RegisterNativeHandler(
"webstore", std::unique_ptr<NativeHandler>(
new extensions::WebstoreBindings(context)));
#if defined(ENABLE_WEBRTC)
module_system->RegisterNativeHandler(
"cast_streaming_natives",
std::unique_ptr<NativeHandler>(
new extensions::CastStreamingNativeHandler(context)));
#endif
module_system->RegisterNativeHandler(
"automationInternal",
std::unique_ptr<NativeHandler>(
new extensions::AutomationInternalCustomBindings(context)));
}
Vulnerability Type: Bypass
CWE ID: CWE-284
Summary: The extensions subsystem in Google Chrome before 51.0.2704.79 does not properly restrict bindings access, which allows remote attackers to bypass the Same Origin Policy via unspecified vectors.
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710} | Medium | 172,243 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: lrmd_remote_client_msg(gpointer data)
{
int id = 0;
int rc = 0;
int disconnected = 0;
xmlNode *request = NULL;
crm_client_t *client = data;
if (client->remote->tls_handshake_complete == FALSE) {
int rc = 0;
/* Muliple calls to handshake will be required, this callback
* will be invoked once the client sends more handshake data. */
do {
rc = gnutls_handshake(*client->remote->tls_session);
if (rc < 0 && rc != GNUTLS_E_AGAIN) {
crm_err("Remote lrmd tls handshake failed");
return -1;
}
} while (rc == GNUTLS_E_INTERRUPTED);
if (rc == 0) {
crm_debug("Remote lrmd tls handshake completed");
client->remote->tls_handshake_complete = TRUE;
if (client->remote->auth_timeout) {
g_source_remove(client->remote->auth_timeout);
}
client->remote->auth_timeout = 0;
}
return 0;
}
rc = crm_remote_ready(client->remote, 0);
if (rc == 0) {
/* no msg to read */
return 0;
} else if (rc < 0) {
crm_info("Client disconnected during remote client read");
return -1;
}
crm_remote_recv(client->remote, -1, &disconnected);
request = crm_remote_parse_buffer(client->remote);
while (request) {
crm_element_value_int(request, F_LRMD_REMOTE_MSG_ID, &id);
crm_trace("processing request from remote client with remote msg id %d", id);
if (!client->name) {
const char *value = crm_element_value(request, F_LRMD_CLIENTNAME);
if (value) {
client->name = strdup(value);
}
}
lrmd_call_id++;
if (lrmd_call_id < 1) {
lrmd_call_id = 1;
}
crm_xml_add(request, F_LRMD_CLIENTID, client->id);
crm_xml_add(request, F_LRMD_CLIENTNAME, client->name);
crm_xml_add_int(request, F_LRMD_CALLID, lrmd_call_id);
process_lrmd_message(client, id, request);
free_xml(request);
/* process all the messages in the current buffer */
request = crm_remote_parse_buffer(client->remote);
}
if (disconnected) {
crm_info("Client disconnect detected in tls msg dispatcher.");
return -1;
}
return 0;
}
Vulnerability Type: DoS
CWE ID: CWE-254
Summary: Pacemaker before 1.1.15, when using pacemaker remote, might allow remote attackers to cause a denial of service (node disconnection) via an unauthenticated connection.
Commit Message: Fix: remote: cl#5269 - Notify other clients of a new connection only if the handshake has completed (bsc#967388) | Low | 168,784 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static int sco_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct sco_pinfo *pi = sco_pi(sk);
lock_sock(sk);
if (sk->sk_state == BT_CONNECT2 &&
test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) {
sco_conn_defer_accept(pi->conn->hcon, pi->setting);
sk->sk_state = BT_CONFIG;
msg->msg_namelen = 0;
release_sock(sk);
return 0;
}
release_sock(sk);
return bt_sock_recvmsg(iocb, sock, msg, len, flags);
}
Vulnerability Type: +Info
CWE ID: CWE-20
Summary: The x25_recvmsg function in net/x25/af_x25.c in the Linux kernel before 3.12.4 updates a certain length value without ensuring that an associated data structure has been initialized, which allows local users to obtain sensitive information from kernel memory via a (1) recvfrom, (2) recvmmsg, or (3) recvmsg system call.
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]> | Low | 166,495 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp,
struct cftype *cft, struct eventfd_ctx *eventfd)
{
struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp);
struct mem_cgroup_thresholds *thresholds;
struct mem_cgroup_threshold_ary *new;
int type = MEMFILE_TYPE(cft->private);
u64 usage;
int i, j, size;
mutex_lock(&memcg->thresholds_lock);
if (type == _MEM)
thresholds = &memcg->thresholds;
else if (type == _MEMSWAP)
thresholds = &memcg->memsw_thresholds;
else
BUG();
/*
* Something went wrong if we trying to unregister a threshold
* if we don't have thresholds
*/
BUG_ON(!thresholds);
usage = mem_cgroup_usage(memcg, type == _MEMSWAP);
/* Check if a threshold crossed before removing */
__mem_cgroup_threshold(memcg, type == _MEMSWAP);
/* Calculate new number of threshold */
size = 0;
for (i = 0; i < thresholds->primary->size; i++) {
if (thresholds->primary->entries[i].eventfd != eventfd)
size++;
}
new = thresholds->spare;
/* Set thresholds array to NULL if we don't have thresholds */
if (!size) {
kfree(new);
new = NULL;
goto swap_buffers;
}
new->size = size;
/* Copy thresholds and find current threshold */
new->current_threshold = -1;
for (i = 0, j = 0; i < thresholds->primary->size; i++) {
if (thresholds->primary->entries[i].eventfd == eventfd)
continue;
new->entries[j] = thresholds->primary->entries[i];
if (new->entries[j].threshold < usage) {
/*
* new->current_threshold will not be used
* until rcu_assign_pointer(), so it's safe to increment
* it here.
*/
++new->current_threshold;
}
j++;
}
swap_buffers:
/* Swap primary and spare array */
thresholds->spare = thresholds->primary;
rcu_assign_pointer(thresholds->primary, new);
/* To be sure that nobody uses thresholds */
synchronize_rcu();
mutex_unlock(&memcg->thresholds_lock);
}
Vulnerability Type: DoS
CWE ID:
Summary: The mem_cgroup_usage_unregister_event function in mm/memcontrol.c in the Linux kernel before 3.2.10 does not properly handle multiple events that are attached to the same eventfd, which allows local users to cause a denial of service (NULL pointer dereference and system crash) or possibly have unspecified other impact by registering memory threshold events.
Commit Message: mm: memcg: Correct unregistring of events attached to the same eventfd
There is an issue when memcg unregisters events that were attached to
the same eventfd:
- On the first call mem_cgroup_usage_unregister_event() removes all
events attached to a given eventfd, and if there were no events left,
thresholds->primary would become NULL;
- Since there were several events registered, cgroups core will call
mem_cgroup_usage_unregister_event() again, but now kernel will oops,
as the function doesn't expect that threshold->primary may be NULL.
That's a good question whether mem_cgroup_usage_unregister_event()
should actually remove all events in one go, but nowadays it can't
do any better as cftype->unregister_event callback doesn't pass
any private event-associated cookie. So, let's fix the issue by
simply checking for threshold->primary.
FWIW, w/o the patch the following oops may be observed:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000004
IP: [<ffffffff810be32c>] mem_cgroup_usage_unregister_event+0x9c/0x1f0
Pid: 574, comm: kworker/0:2 Not tainted 3.3.0-rc4+ #9 Bochs Bochs
RIP: 0010:[<ffffffff810be32c>] [<ffffffff810be32c>] mem_cgroup_usage_unregister_event+0x9c/0x1f0
RSP: 0018:ffff88001d0b9d60 EFLAGS: 00010246
Process kworker/0:2 (pid: 574, threadinfo ffff88001d0b8000, task ffff88001de91cc0)
Call Trace:
[<ffffffff8107092b>] cgroup_event_remove+0x2b/0x60
[<ffffffff8103db94>] process_one_work+0x174/0x450
[<ffffffff8103e413>] worker_thread+0x123/0x2d0
Cc: stable <[email protected]>
Signed-off-by: Anton Vorontsov <[email protected]>
Acked-by: KAMEZAWA Hiroyuki <[email protected]>
Cc: Kirill A. Shutemov <[email protected]>
Cc: Michal Hocko <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]> | Low | 165,643 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static inline int mk_vhost_fdt_close(struct session_request *sr)
{
int id;
unsigned int hash;
struct vhost_fdt_hash_table *ht = NULL;
struct vhost_fdt_hash_chain *hc;
if (config->fdt == MK_FALSE) {
return close(sr->fd_file);
}
id = sr->vhost_fdt_id;
hash = sr->vhost_fdt_hash;
ht = mk_vhost_fdt_table_lookup(id, sr->host_conf);
if (mk_unlikely(!ht)) {
return close(sr->fd_file);
}
/* We got the hash table, now look around the chains array */
hc = mk_vhost_fdt_chain_lookup(hash, ht);
if (hc) {
/* Increment the readers and check if we should close */
hc->readers--;
if (hc->readers == 0) {
hc->fd = -1;
hc->hash = 0;
ht->av_slots++;
return close(sr->fd_file);
}
else {
return 0;
}
}
return close(sr->fd_file);
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: Monkey HTTP Server before 1.5.3, when the File Descriptor Table (FDT) is enabled and custom error messages are set, allows remote attackers to cause a denial of service (file descriptor consumption) via an HTTP request that triggers an error message.
Commit Message: Request: new request session flag to mark those files opened by FDT
This patch aims to fix a potential DDoS problem that can be caused
in the server quering repetitive non-existent resources.
When serving a static file, the core use Vhost FDT mechanism, but if
it sends a static error page it does a direct open(2). When closing
the resources for the same request it was just calling mk_vhost_close()
which did not clear properly the file descriptor.
This patch adds a new field on the struct session_request called 'fd_is_fdt',
which contains MK_TRUE or MK_FALSE depending of how fd_file was opened.
Thanks to Matthew Daley <[email protected]> for report and troubleshoot this
problem.
Signed-off-by: Eduardo Silva <[email protected]> | Medium | 166,278 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static struct sock * tcp_v6_syn_recv_sock(struct sock *sk, struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst)
{
struct inet6_request_sock *treq;
struct ipv6_pinfo *newnp, *np = inet6_sk(sk);
struct tcp6_sock *newtcp6sk;
struct inet_sock *newinet;
struct tcp_sock *newtp;
struct sock *newsk;
struct ipv6_txoptions *opt;
#ifdef CONFIG_TCP_MD5SIG
struct tcp_md5sig_key *key;
#endif
if (skb->protocol == htons(ETH_P_IP)) {
/*
* v6 mapped
*/
newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst);
if (newsk == NULL)
return NULL;
newtcp6sk = (struct tcp6_sock *)newsk;
inet_sk(newsk)->pinet6 = &newtcp6sk->inet6;
newinet = inet_sk(newsk);
newnp = inet6_sk(newsk);
newtp = tcp_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
ipv6_addr_set_v4mapped(newinet->inet_daddr, &newnp->daddr);
ipv6_addr_set_v4mapped(newinet->inet_saddr, &newnp->saddr);
ipv6_addr_copy(&newnp->rcv_saddr, &newnp->saddr);
inet_csk(newsk)->icsk_af_ops = &ipv6_mapped;
newsk->sk_backlog_rcv = tcp_v4_do_rcv;
#ifdef CONFIG_TCP_MD5SIG
newtp->af_specific = &tcp_sock_ipv6_mapped_specific;
#endif
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks count
* here, tcp_create_openreq_child now does this for us, see the comment in
* that function for the gory details. -acme
*/
/* It is tricky place. Until this moment IPv4 tcp
worked with IPv6 icsk.icsk_af_ops.
Sync it now.
*/
tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie);
return newsk;
}
treq = inet6_rsk(req);
opt = np->opt;
if (sk_acceptq_is_full(sk))
goto out_overflow;
if (!dst) {
dst = inet6_csk_route_req(sk, req);
if (!dst)
goto out;
}
newsk = tcp_create_openreq_child(sk, req, skb);
if (newsk == NULL)
goto out_nonewsk;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks
* count here, tcp_create_openreq_child now does this for us, see the
* comment in that function for the gory details. -acme
*/
newsk->sk_gso_type = SKB_GSO_TCPV6;
__ip6_dst_store(newsk, dst, NULL, NULL);
newtcp6sk = (struct tcp6_sock *)newsk;
inet_sk(newsk)->pinet6 = &newtcp6sk->inet6;
newtp = tcp_sk(newsk);
newinet = inet_sk(newsk);
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
ipv6_addr_copy(&newnp->daddr, &treq->rmt_addr);
ipv6_addr_copy(&newnp->saddr, &treq->loc_addr);
ipv6_addr_copy(&newnp->rcv_saddr, &treq->loc_addr);
newsk->sk_bound_dev_if = treq->iif;
/* Now IPv6 options...
First: no IPv4 options.
*/
newinet->opt = NULL;
newnp->ipv6_fl_list = NULL;
/* Clone RX bits */
newnp->rxopt.all = np->rxopt.all;
/* Clone pktoptions received with SYN */
newnp->pktoptions = NULL;
if (treq->pktopts != NULL) {
newnp->pktoptions = skb_clone(treq->pktopts, GFP_ATOMIC);
kfree_skb(treq->pktopts);
treq->pktopts = NULL;
if (newnp->pktoptions)
skb_set_owner_r(newnp->pktoptions, newsk);
}
newnp->opt = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/* Clone native IPv6 options from listening socket (if any)
Yes, keeping reference count would be much more clever,
but we make one more one thing there: reattach optmem
to newsk.
*/
if (opt) {
newnp->opt = ipv6_dup_options(newsk, opt);
if (opt != np->opt)
sock_kfree_s(sk, opt, opt->tot_len);
}
inet_csk(newsk)->icsk_ext_hdr_len = 0;
if (newnp->opt)
inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen +
newnp->opt->opt_flen);
tcp_mtup_init(newsk);
tcp_sync_mss(newsk, dst_mtu(dst));
newtp->advmss = dst_metric_advmss(dst);
tcp_initialize_rcv_mss(newsk);
newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6;
newinet->inet_rcv_saddr = LOOPBACK4_IPV6;
#ifdef CONFIG_TCP_MD5SIG
/* Copy over the MD5 key from the original socket */
if ((key = tcp_v6_md5_do_lookup(sk, &newnp->daddr)) != NULL) {
/* We're using one, so create a matching key
* on the newsk structure. If we fail to get
* memory, then we end up not copying the key
* across. Shucks.
*/
char *newkey = kmemdup(key->key, key->keylen, GFP_ATOMIC);
if (newkey != NULL)
tcp_v6_md5_do_add(newsk, &newnp->daddr,
newkey, key->keylen);
}
#endif
if (__inet_inherit_port(sk, newsk) < 0) {
sock_put(newsk);
goto out;
}
__inet6_hash(newsk, NULL);
return newsk;
out_overflow:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
out_nonewsk:
if (opt && opt != np->opt)
sock_kfree_s(sk, opt, opt->tot_len);
dst_release(dst);
out:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS);
return NULL;
}
Vulnerability Type: DoS
CWE ID: CWE-362
Summary: Race condition in the IP implementation in the Linux kernel before 3.0 might allow remote attackers to cause a denial of service (slab corruption and system crash) by sending packets to an application that sets socket options during the handling of network traffic.
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]> | High | 165,574 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: status_t CameraClient::dump(int fd, const Vector<String16>& args) {
const size_t SIZE = 256;
char buffer[SIZE];
size_t len = snprintf(buffer, SIZE, "Client[%d] (%p) PID: %d\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
mClientPid);
len = (len > SIZE - 1) ? SIZE - 1 : len;
write(fd, buffer, len);
return mHardware->dump(fd, args);
}
Vulnerability Type: +Priv
CWE ID: CWE-264
Summary: libcameraservice in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.x before 2016-03-01 does not require use of the ICameraService::dump method for a camera service dump, which allows attackers to gain privileges via a crafted application that directly dumps, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 26265403.
Commit Message: Camera: Disallow dumping clients directly
Camera service dumps should only be initiated through
ICameraService::dump.
Bug: 26265403
Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803
| Medium | 173,938 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | 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;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-190
Summary: drivers/vfio/pci/vfio_pci_intrs.c in the Linux kernel through 4.8.11 misuses the kzalloc function, which allows local users to cause a denial of service (integer overflow) or have unspecified other impact by leveraging access to a vfio PCI device file.
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]> | Low | 166,901 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static struct page *follow_page_pte(struct vm_area_struct *vma,
unsigned long address, pmd_t *pmd, unsigned int flags,
struct dev_pagemap **pgmap)
{
struct mm_struct *mm = vma->vm_mm;
struct page *page;
spinlock_t *ptl;
pte_t *ptep, pte;
retry:
if (unlikely(pmd_bad(*pmd)))
return no_page_table(vma, flags);
ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
pte = *ptep;
if (!pte_present(pte)) {
swp_entry_t entry;
/*
* KSM's break_ksm() relies upon recognizing a ksm page
* even while it is being migrated, so for that case we
* need migration_entry_wait().
*/
if (likely(!(flags & FOLL_MIGRATION)))
goto no_page;
if (pte_none(pte))
goto no_page;
entry = pte_to_swp_entry(pte);
if (!is_migration_entry(entry))
goto no_page;
pte_unmap_unlock(ptep, ptl);
migration_entry_wait(mm, pmd, address);
goto retry;
}
if ((flags & FOLL_NUMA) && pte_protnone(pte))
goto no_page;
if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
pte_unmap_unlock(ptep, ptl);
return NULL;
}
page = vm_normal_page(vma, address, pte);
if (!page && pte_devmap(pte) && (flags & FOLL_GET)) {
/*
* Only return device mapping pages in the FOLL_GET case since
* they are only valid while holding the pgmap reference.
*/
*pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
if (*pgmap)
page = pte_page(pte);
else
goto no_page;
} else if (unlikely(!page)) {
if (flags & FOLL_DUMP) {
/* Avoid special (like zero) pages in core dumps */
page = ERR_PTR(-EFAULT);
goto out;
}
if (is_zero_pfn(pte_pfn(pte))) {
page = pte_page(pte);
} else {
int ret;
ret = follow_pfn_pte(vma, address, ptep, flags);
page = ERR_PTR(ret);
goto out;
}
}
if (flags & FOLL_SPLIT && PageTransCompound(page)) {
int ret;
get_page(page);
pte_unmap_unlock(ptep, ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
if (ret)
return ERR_PTR(ret);
goto retry;
}
if (flags & FOLL_GET)
get_page(page);
if (flags & FOLL_TOUCH) {
if ((flags & FOLL_WRITE) &&
!pte_dirty(pte) && !PageDirty(page))
set_page_dirty(page);
/*
* pte_mkyoung() would be more correct here, but atomic care
* is needed to avoid losing the dirty bit: it is easier to use
* mark_page_accessed().
*/
mark_page_accessed(page);
}
if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
/* Do not mlock pte-mapped THP */
if (PageTransCompound(page))
goto out;
/*
* The preliminary mapping check is mainly to avoid the
* pointless overhead of lock_page on the ZERO_PAGE
* which might bounce very badly if there is contention.
*
* If the page is already locked, we don't need to
* handle it now - vmscan will handle it later if and
* when it attempts to reclaim the page.
*/
if (page->mapping && trylock_page(page)) {
lru_add_drain(); /* push cached pages to LRU */
/*
* Because we lock page here, and migration is
* blocked by the pte's page reference, and we
* know the page is still mapped, we don't even
* need to check for file-cache page truncation.
*/
mlock_vma_page(page);
unlock_page(page);
}
}
out:
pte_unmap_unlock(ptep, ptl);
return page;
no_page:
pte_unmap_unlock(ptep, ptl);
if (!pte_none(pte))
return NULL;
return no_page_table(vma, flags);
}
Vulnerability Type: Overflow
CWE ID: CWE-416
Summary: The Linux kernel before 5.1-rc5 allows page->_refcount reference count overflow, with resultant use-after-free issues, if about 140 GiB of RAM exists. This is related to fs/fuse/dev.c, fs/pipe.c, fs/splice.c, include/linux/mm.h, include/linux/pipe_fs_i.h, kernel/trace/trace.c, mm/gup.c, and mm/hugetlb.c. It can occur with FUSE requests.
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit | Low | 170,222 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void net_checksum_calculate(uint8_t *data, int length)
{
int hlen, plen, proto, csum_offset;
uint16_t csum;
if ((data[14] & 0xf0) != 0x40)
return; /* not IPv4 */
hlen = (data[14] & 0x0f) * 4;
csum_offset = 16;
break;
case PROTO_UDP:
csum_offset = 6;
break;
default:
return;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The net_checksum_calculate function in net/checksum.c in QEMU allows local guest OS users to cause a denial of service (out-of-bounds heap read and crash) via the payload length in a crafted packet.
Commit Message: | Low | 165,182 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: status_t OMXNodeInstance::allocateBufferWithBackup(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
if (params == NULL || buffer == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size()) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = new BufferMeta(params, portIndex, true);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_AllocateBuffer(
mHandle, &header, portIndex, buffer_meta, allottedSize);
if (err != OMX_ErrorNone) {
CLOG_ERROR(allocateBufferWithBackup, err,
SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p",
params->size(), params->pointer(), allottedSize, header->pBuffer));
return OK;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: An information disclosure vulnerability in libstagefright in Mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, 6.x before 2016-11-01, and 7.0 before 2016-11-01 could enable a local malicious application to access data outside of its permission levels. This issue is rated as Moderate because it could be used to access sensitive data without permission. Android ID: A-29422020.
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
| Medium | 174,130 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: PluginChannel::~PluginChannel() {
if (renderer_handle_)
base::CloseProcessHandle(renderer_handle_);
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&PluginReleaseCallback),
base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes));
}
Vulnerability Type: DoS
CWE ID:
Summary: Google Chrome before 20.0.1132.43 on Windows does not properly isolate sandboxed processes, which might allow remote attackers to cause a denial of service (process interference) via unspecified vectors.
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 | Low | 170,951 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: apprentice_load(struct magic_set *ms, const char *fn, int action)
{
int errs = 0;
uint32_t i, j;
size_t files = 0, maxfiles = 0;
char **filearr = NULL;
struct stat st;
struct magic_map *map;
struct magic_entry_set mset[MAGIC_SETS];
php_stream *dir;
php_stream_dirent d;
TSRMLS_FETCH();
memset(mset, 0, sizeof(mset));
ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL)
{
file_oomem(ms, sizeof(*map));
return NULL;
}
/* print silly verbose header for USG compat. */
if (action == FILE_CHECK)
(void)fprintf(stderr, "%s\n", usg_hdr);
/* load directory or file */
/* FIXME: Read file names and sort them to prevent
non-determinism. See Debian bug #488562. */
if (php_sys_stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
int mflen;
char mfn[MAXPATHLEN];
dir = php_stream_opendir((char *)fn, REPORT_ERRORS, NULL);
if (!dir) {
errs++;
goto out;
}
while (php_stream_readdir(dir, &d)) {
if ((mflen = snprintf(mfn, sizeof(mfn), "%s/%s", fn, d.d_name)) < 0) {
file_oomem(ms,
strlen(fn) + strlen(d.d_name) + 2);
errs++;
php_stream_closedir(dir);
goto out;
}
if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
continue;
}
if (files >= maxfiles) {
size_t mlen;
maxfiles = (maxfiles + 1) * 2;
mlen = maxfiles * sizeof(*filearr);
if ((filearr = CAST(char **,
erealloc(filearr, mlen))) == NULL) {
file_oomem(ms, mlen);
efree(mfn);
php_stream_closedir(dir);
errs++;
goto out;
goto out;
}
}
filearr[files++] = estrndup(mfn, (mflen > sizeof(mfn) - 1)? sizeof(mfn) - 1: mflen);
}
php_stream_closedir(dir);
qsort(filearr, files, sizeof(*filearr), cmpstrp);
for (i = 0; i < files; i++) {
load_1(ms, action, filearr[i], &errs, mset);
efree(filearr[i]);
}
efree(filearr);
} else
load_1(ms, action, fn, &errs, mset);
if (errs)
goto out;
for (j = 0; j < MAGIC_SETS; j++) {
/* Set types of tests */
for (i = 0; i < mset[j].count; ) {
if (mset[j].me[i].mp->cont_level != 0) {
i++;
continue;
}
i = set_text_binary(ms, mset[j].me, mset[j].count, i);
}
qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),
apprentice_sort);
/*
* Make sure that any level 0 "default" line is last
* (if one exists).
*/
set_last_default(ms, mset[j].me, mset[j].count);
/* coalesce per file arrays into a single one */
if (coalesce_entries(ms, mset[j].me, mset[j].count,
&map->magic[j], &map->nmagic[j]) == -1) {
errs++;
goto out;
}
}
out:
for (j = 0; j < MAGIC_SETS; j++)
magic_entry_free(mset[j].me, mset[j].count);
if (errs) {
for (j = 0; j < MAGIC_SETS; j++) {
if (map->magic[j])
efree(map->magic[j]);
}
efree(map);
return NULL;
}
return map;
}
Vulnerability Type: DoS Mem. Corr.
CWE ID: CWE-17
Summary: ** DISPUTED ** The apprentice_load function in libmagic/apprentice.c in the Fileinfo component in PHP through 5.6.4 attempts to perform a free operation on a stack-based character array, which allows remote attackers to cause a denial of service (memory corruption or application crash) or possibly have unspecified other impact via unknown vectors. NOTE: this is disputed by the vendor because the standard erealloc behavior makes the free operation unreachable.
Commit Message: | Low | 164,882 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static ssize_t aio_setup_iocb(struct kiocb *kiocb, bool compat)
{
struct file *file = kiocb->ki_filp;
ssize_t ret = 0;
switch (kiocb->ki_opcode) {
case IOCB_CMD_PREAD:
ret = -EBADF;
if (unlikely(!(file->f_mode & FMODE_READ)))
break;
ret = -EFAULT;
if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf,
kiocb->ki_left)))
break;
ret = security_file_permission(file, MAY_READ);
if (unlikely(ret))
break;
ret = aio_setup_single_vector(kiocb);
if (ret)
break;
ret = -EINVAL;
if (file->f_op->aio_read)
kiocb->ki_retry = aio_rw_vect_retry;
break;
case IOCB_CMD_PWRITE:
ret = -EBADF;
if (unlikely(!(file->f_mode & FMODE_WRITE)))
break;
ret = -EFAULT;
if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf,
kiocb->ki_left)))
break;
ret = security_file_permission(file, MAY_WRITE);
if (unlikely(ret))
break;
ret = aio_setup_single_vector(kiocb);
if (ret)
break;
ret = -EINVAL;
if (file->f_op->aio_write)
kiocb->ki_retry = aio_rw_vect_retry;
break;
case IOCB_CMD_PREADV:
ret = -EBADF;
if (unlikely(!(file->f_mode & FMODE_READ)))
break;
ret = security_file_permission(file, MAY_READ);
if (unlikely(ret))
break;
ret = aio_setup_vectored_rw(READ, kiocb, compat);
if (ret)
break;
ret = -EINVAL;
if (file->f_op->aio_read)
kiocb->ki_retry = aio_rw_vect_retry;
break;
case IOCB_CMD_PWRITEV:
ret = -EBADF;
if (unlikely(!(file->f_mode & FMODE_WRITE)))
break;
ret = security_file_permission(file, MAY_WRITE);
if (unlikely(ret))
break;
ret = aio_setup_vectored_rw(WRITE, kiocb, compat);
if (ret)
break;
ret = -EINVAL;
if (file->f_op->aio_write)
kiocb->ki_retry = aio_rw_vect_retry;
break;
case IOCB_CMD_FDSYNC:
ret = -EINVAL;
if (file->f_op->aio_fsync)
kiocb->ki_retry = aio_fdsync;
break;
case IOCB_CMD_FSYNC:
ret = -EINVAL;
if (file->f_op->aio_fsync)
kiocb->ki_retry = aio_fsync;
break;
default:
dprintk("EINVAL: io_submit: no operation provided\n");
ret = -EINVAL;
}
if (!kiocb->ki_retry)
return ret;
return 0;
}
Vulnerability Type: DoS Overflow
CWE ID:
Summary: Integer overflow in fs/aio.c in the Linux kernel before 3.4.1 allows local users to cause a denial of service or possibly have unspecified other impact via a large AIO iovec.
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]> | Low | 167,611 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits)
{
stream_t *ps_stream = (stream_t *)pv_ctxt;
if (ps_stream->u4_offset < ps_stream->u4_max_offset)
{
FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned)
}
return;
}
Vulnerability Type: DoS +Info
CWE ID: CWE-200
Summary: decoder/impeg2d_bitstream.c in mediaserver in Android 6.x before 2016-07-01 allows attackers to obtain sensitive information from process memory or cause a denial of service (out-of-bounds read) via a crafted application, aka internal bug 28168413.
Commit Message: Fixed out of bound read in flush_bits
Bug: 28168413
Change-Id: I3db5432a08daf665e160c0dab2d1928a576418b4
| Low | 173,549 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: bool __net_get_random_once(void *buf, int nbytes, bool *done,
struct static_key *done_key)
{
static DEFINE_SPINLOCK(lock);
unsigned long flags;
spin_lock_irqsave(&lock, flags);
if (*done) {
spin_unlock_irqrestore(&lock, flags);
return false;
}
get_random_bytes(buf, nbytes);
*done = true;
spin_unlock_irqrestore(&lock, flags);
__net_random_once_disable_jump(done_key);
return true;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: The net_get_random_once implementation in net/core/utils.c in the Linux kernel 3.13.x and 3.14.x before 3.14.5 on certain Intel processors does not perform the intended slow-path operation to initialize random seeds, which makes it easier for remote attackers to spoof or disrupt IP communication by leveraging the predictability of TCP sequence numbers, TCP and UDP port numbers, and IP ID values.
Commit Message: net: avoid dependency of net_get_random_once on nop patching
net_get_random_once depends on the static keys infrastructure to patch up
the branch to the slow path during boot. This was realized by abusing the
static keys api and defining a new initializer to not enable the call
site while still indicating that the branch point should get patched
up. This was needed to have the fast path considered likely by gcc.
The static key initialization during boot up normally walks through all
the registered keys and either patches in ideal nops or enables the jump
site but omitted that step on x86 if ideal nops where already placed at
static_key branch points. Thus net_get_random_once branches not always
became active.
This patch switches net_get_random_once to the ordinary static_key
api and thus places the kernel fast path in the - by gcc considered -
unlikely path. Microbenchmarks on Intel and AMD x86-64 showed that
the unlikely path actually beats the likely path in terms of cycle cost
and that different nop patterns did not make much difference, thus this
switch should not be noticeable.
Fixes: a48e42920ff38b ("net: introduce new macro net_get_random_once")
Reported-by: Tuomas Räsänen <[email protected]>
Cc: Linus Torvalds <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]> | Low | 166,258 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: ldp_tlv_print(netdissect_options *ndo,
register const u_char *tptr,
u_short msg_tlen)
{
struct ldp_tlv_header {
uint8_t type[2];
uint8_t length[2];
};
const struct ldp_tlv_header *ldp_tlv_header;
u_short tlv_type,tlv_len,tlv_tlen,af,ft_flags;
u_char fec_type;
u_int ui,vc_info_len, vc_info_tlv_type, vc_info_tlv_len,idx;
char buf[100];
int i;
ldp_tlv_header = (const struct ldp_tlv_header *)tptr;
ND_TCHECK(*ldp_tlv_header);
tlv_len=EXTRACT_16BITS(ldp_tlv_header->length);
if (tlv_len + 4 > msg_tlen) {
ND_PRINT((ndo, "\n\t\t TLV contents go past end of message"));
return 0;
}
tlv_tlen=tlv_len;
tlv_type=LDP_MASK_TLV_TYPE(EXTRACT_16BITS(ldp_tlv_header->type));
/* FIXME vendor private / experimental check */
ND_PRINT((ndo, "\n\t %s TLV (0x%04x), length: %u, Flags: [%s and %s forward if unknown]",
tok2str(ldp_tlv_values,
"Unknown",
tlv_type),
tlv_type,
tlv_len,
LDP_MASK_U_BIT(EXTRACT_16BITS(&ldp_tlv_header->type)) ? "continue processing" : "ignore",
LDP_MASK_F_BIT(EXTRACT_16BITS(&ldp_tlv_header->type)) ? "do" : "don't"));
tptr+=sizeof(struct ldp_tlv_header);
switch(tlv_type) {
case LDP_TLV_COMMON_HELLO:
TLV_TCHECK(4);
ND_PRINT((ndo, "\n\t Hold Time: %us, Flags: [%s Hello%s]",
EXTRACT_16BITS(tptr),
(EXTRACT_16BITS(tptr+2)&0x8000) ? "Targeted" : "Link",
(EXTRACT_16BITS(tptr+2)&0x4000) ? ", Request for targeted Hellos" : ""));
break;
case LDP_TLV_IPV4_TRANSPORT_ADDR:
TLV_TCHECK(4);
ND_PRINT((ndo, "\n\t IPv4 Transport Address: %s", ipaddr_string(ndo, tptr)));
break;
case LDP_TLV_IPV6_TRANSPORT_ADDR:
TLV_TCHECK(16);
ND_PRINT((ndo, "\n\t IPv6 Transport Address: %s", ip6addr_string(ndo, tptr)));
break;
case LDP_TLV_CONFIG_SEQ_NUMBER:
TLV_TCHECK(4);
ND_PRINT((ndo, "\n\t Sequence Number: %u", EXTRACT_32BITS(tptr)));
break;
case LDP_TLV_ADDRESS_LIST:
TLV_TCHECK(LDP_TLV_ADDRESS_LIST_AFNUM_LEN);
af = EXTRACT_16BITS(tptr);
tptr+=LDP_TLV_ADDRESS_LIST_AFNUM_LEN;
tlv_tlen -= LDP_TLV_ADDRESS_LIST_AFNUM_LEN;
ND_PRINT((ndo, "\n\t Address Family: %s, addresses",
tok2str(af_values, "Unknown (%u)", af)));
switch (af) {
case AFNUM_INET:
while(tlv_tlen >= sizeof(struct in_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, " %s", ipaddr_string(ndo, tptr)));
tlv_tlen-=sizeof(struct in_addr);
tptr+=sizeof(struct in_addr);
}
break;
case AFNUM_INET6:
while(tlv_tlen >= sizeof(struct in6_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in6_addr));
ND_PRINT((ndo, " %s", ip6addr_string(ndo, tptr)));
tlv_tlen-=sizeof(struct in6_addr);
tptr+=sizeof(struct in6_addr);
}
break;
default:
/* unknown AF */
break;
}
break;
case LDP_TLV_COMMON_SESSION:
TLV_TCHECK(8);
ND_PRINT((ndo, "\n\t Version: %u, Keepalive: %us, Flags: [Downstream %s, Loop Detection %s]",
EXTRACT_16BITS(tptr), EXTRACT_16BITS(tptr+2),
(EXTRACT_16BITS(tptr+6)&0x8000) ? "On Demand" : "Unsolicited",
(EXTRACT_16BITS(tptr+6)&0x4000) ? "Enabled" : "Disabled"
));
break;
case LDP_TLV_FEC:
TLV_TCHECK(1);
fec_type = *tptr;
ND_PRINT((ndo, "\n\t %s FEC (0x%02x)",
tok2str(ldp_fec_values, "Unknown", fec_type),
fec_type));
tptr+=1;
tlv_tlen-=1;
switch(fec_type) {
case LDP_FEC_WILDCARD:
break;
case LDP_FEC_PREFIX:
TLV_TCHECK(2);
af = EXTRACT_16BITS(tptr);
tptr+=LDP_TLV_ADDRESS_LIST_AFNUM_LEN;
tlv_tlen-=LDP_TLV_ADDRESS_LIST_AFNUM_LEN;
if (af == AFNUM_INET) {
i=decode_prefix4(ndo, tptr, tlv_tlen, buf, sizeof(buf));
if (i == -2)
goto trunc;
if (i == -3)
ND_PRINT((ndo, ": IPv4 prefix (goes past end of TLV)"));
else if (i == -1)
ND_PRINT((ndo, ": IPv4 prefix (invalid length)"));
else
ND_PRINT((ndo, ": IPv4 prefix %s", buf));
}
else if (af == AFNUM_INET6) {
i=decode_prefix6(ndo, tptr, tlv_tlen, buf, sizeof(buf));
if (i == -2)
goto trunc;
if (i == -3)
ND_PRINT((ndo, ": IPv4 prefix (goes past end of TLV)"));
else if (i == -1)
ND_PRINT((ndo, ": IPv6 prefix (invalid length)"));
else
ND_PRINT((ndo, ": IPv6 prefix %s", buf));
}
else
ND_PRINT((ndo, ": Address family %u prefix", af));
break;
case LDP_FEC_HOSTADDRESS:
break;
case LDP_FEC_MARTINI_VC:
/*
* We assume the type was supposed to be one of the MPLS
* Pseudowire Types.
*/
TLV_TCHECK(7);
vc_info_len = *(tptr+2);
/*
* According to RFC 4908, the VC info Length field can be zero,
* in which case not only are there no interface parameters,
* there's no VC ID.
*/
if (vc_info_len == 0) {
ND_PRINT((ndo, ": %s, %scontrol word, group-ID %u, VC-info-length: %u",
tok2str(mpls_pw_types_values, "Unknown", EXTRACT_16BITS(tptr)&0x7fff),
EXTRACT_16BITS(tptr)&0x8000 ? "" : "no ",
EXTRACT_32BITS(tptr+3),
vc_info_len));
break;
}
/* Make sure we have the VC ID as well */
TLV_TCHECK(11);
ND_PRINT((ndo, ": %s, %scontrol word, group-ID %u, VC-ID %u, VC-info-length: %u",
tok2str(mpls_pw_types_values, "Unknown", EXTRACT_16BITS(tptr)&0x7fff),
EXTRACT_16BITS(tptr)&0x8000 ? "" : "no ",
EXTRACT_32BITS(tptr+3),
EXTRACT_32BITS(tptr+7),
vc_info_len));
if (vc_info_len < 4) {
/* minimum 4, for the VC ID */
ND_PRINT((ndo, " (invalid, < 4"));
return(tlv_len+4); /* Type & Length fields not included */
}
vc_info_len -= 4; /* subtract out the VC ID, giving the length of the interface parameters */
/* Skip past the fixed information and the VC ID */
tptr+=11;
tlv_tlen-=11;
TLV_TCHECK(vc_info_len);
while (vc_info_len > 2) {
vc_info_tlv_type = *tptr;
vc_info_tlv_len = *(tptr+1);
if (vc_info_tlv_len < 2)
break;
if (vc_info_len < vc_info_tlv_len)
break;
ND_PRINT((ndo, "\n\t\tInterface Parameter: %s (0x%02x), len %u",
tok2str(ldp_fec_martini_ifparm_values,"Unknown",vc_info_tlv_type),
vc_info_tlv_type,
vc_info_tlv_len));
switch(vc_info_tlv_type) {
case LDP_FEC_MARTINI_IFPARM_MTU:
ND_PRINT((ndo, ": %u", EXTRACT_16BITS(tptr+2)));
break;
case LDP_FEC_MARTINI_IFPARM_DESC:
ND_PRINT((ndo, ": "));
for (idx = 2; idx < vc_info_tlv_len; idx++)
safeputchar(ndo, *(tptr + idx));
break;
case LDP_FEC_MARTINI_IFPARM_VCCV:
ND_PRINT((ndo, "\n\t\t Control Channels (0x%02x) = [%s]",
*(tptr+2),
bittok2str(ldp_fec_martini_ifparm_vccv_cc_values, "none", *(tptr+2))));
ND_PRINT((ndo, "\n\t\t CV Types (0x%02x) = [%s]",
*(tptr+3),
bittok2str(ldp_fec_martini_ifparm_vccv_cv_values, "none", *(tptr+3))));
break;
default:
print_unknown_data(ndo, tptr+2, "\n\t\t ", vc_info_tlv_len-2);
break;
}
vc_info_len -= vc_info_tlv_len;
tptr += vc_info_tlv_len;
}
break;
}
break;
case LDP_TLV_GENERIC_LABEL:
TLV_TCHECK(4);
ND_PRINT((ndo, "\n\t Label: %u", EXTRACT_32BITS(tptr) & 0xfffff));
break;
case LDP_TLV_STATUS:
TLV_TCHECK(8);
ui = EXTRACT_32BITS(tptr);
tptr+=4;
ND_PRINT((ndo, "\n\t Status: 0x%02x, Flags: [%s and %s forward]",
ui&0x3fffffff,
ui&0x80000000 ? "Fatal error" : "Advisory Notification",
ui&0x40000000 ? "do" : "don't"));
ui = EXTRACT_32BITS(tptr);
tptr+=4;
if (ui)
ND_PRINT((ndo, ", causing Message ID: 0x%08x", ui));
break;
case LDP_TLV_FT_SESSION:
TLV_TCHECK(8);
ft_flags = EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t Flags: [%sReconnect, %sSave State, %sAll-Label Protection, %s Checkpoint, %sRe-Learn State]",
ft_flags&0x8000 ? "" : "No ",
ft_flags&0x8 ? "" : "Don't ",
ft_flags&0x4 ? "" : "No ",
ft_flags&0x2 ? "Sequence Numbered Label" : "All Labels",
ft_flags&0x1 ? "" : "Don't "));
tptr+=4;
ui = EXTRACT_32BITS(tptr);
if (ui)
ND_PRINT((ndo, ", Reconnect Timeout: %ums", ui));
tptr+=4;
ui = EXTRACT_32BITS(tptr);
if (ui)
ND_PRINT((ndo, ", Recovery Time: %ums", ui));
break;
case LDP_TLV_MTU:
TLV_TCHECK(2);
ND_PRINT((ndo, "\n\t MTU: %u", EXTRACT_16BITS(tptr)));
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case LDP_TLV_HOP_COUNT:
case LDP_TLV_PATH_VECTOR:
case LDP_TLV_ATM_LABEL:
case LDP_TLV_FR_LABEL:
case LDP_TLV_EXTD_STATUS:
case LDP_TLV_RETURNED_PDU:
case LDP_TLV_RETURNED_MSG:
case LDP_TLV_ATM_SESSION_PARM:
case LDP_TLV_FR_SESSION_PARM:
case LDP_TLV_LABEL_REQUEST_MSG_ID:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlv_tlen);
break;
}
return(tlv_len+4); /* Type & Length fields not included */
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
return 0;
badtlv:
ND_PRINT((ndo, "\n\t\t TLV contents go past end of TLV"));
return(tlv_len+4); /* Type & Length fields not included */
}
Vulnerability Type:
CWE ID: CWE-125
Summary: The LDP parser in tcpdump before 4.9.3 has a buffer over-read in print-ldp.c:ldp_tlv_print().
Commit Message: (for 4.9.3) CVE-2018-14461/LDP: Fix a bounds check
In ldp_tlv_print(), the FT Session TLV length must be 12, not 8 (RFC3479)
This fixes a buffer over-read discovered by Konrad Rieck and
Bhargava Shastry.
Add a test using the capture file supplied by the reporter(s).
Moreover:
Add and use tstr[].
Add a comment. | Low | 169,853 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: EffectPaintPropertyNode* EffectPaintPropertyNode::Root() {
DEFINE_STATIC_REF(EffectPaintPropertyNode, root,
(EffectPaintPropertyNode::Create(
nullptr, State{TransformPaintPropertyNode::Root(),
ClipPaintPropertyNode::Root()})));
return root;
}
Vulnerability Type: DoS
CWE ID:
Summary: Multiple unspecified vulnerabilities in Google Chrome before 47.0.2526.73 allow attackers to cause a denial of service or possibly have other impact via unknown vectors.
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} | Low | 171,834 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | 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;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The convolution implementation in Skia, as used in Google Chrome before 47.0.2526.73, does not properly constrain row lengths, which allows remote attackers to cause a denial of service (out-of-bounds memory access) or possibly have unspecified other impact via crafted graphics data.
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} | Low | 171,761 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static void sig_server_connect_copy(SERVER_CONNECT_REC **dest,
IRC_SERVER_CONNECT_REC *src)
{
IRC_SERVER_CONNECT_REC *rec;
g_return_if_fail(dest != NULL);
if (!IS_IRC_SERVER_CONNECT(src))
return;
rec = g_new0(IRC_SERVER_CONNECT_REC, 1);
rec->chat_type = IRC_PROTOCOL;
rec->max_cmds_at_once = src->max_cmds_at_once;
rec->cmd_queue_speed = src->cmd_queue_speed;
rec->max_query_chans = src->max_query_chans;
rec->max_kicks = src->max_kicks;
rec->max_modes = src->max_modes;
rec->max_msgs = src->max_msgs;
rec->max_whois = src->max_whois;
rec->usermode = g_strdup(src->usermode);
rec->alternate_nick = g_strdup(src->alternate_nick);
rec->sasl_mechanism = src->sasl_mechanism;
rec->sasl_username = src->sasl_username;
rec->sasl_password = src->sasl_password;
*dest = (SERVER_CONNECT_REC *) rec;
}
Vulnerability Type:
CWE ID: CWE-416
Summary: Irssi before 1.0.8, 1.1.x before 1.1.3, and 1.2.x before 1.2.1, when SASL is enabled, has a use after free when sending SASL login to the server.
Commit Message: Merge pull request #1058 from ailin-nemui/sasl-reconnect
copy sasl username and password values | Medium | 169,643 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: _dbus_header_byteswap (DBusHeader *header,
int new_order)
{
if (header->byte_order == new_order)
return;
_dbus_marshal_byteswap (&_dbus_header_signature_str,
0, header->byte_order,
new_order,
&header->data, 0);
header->byte_order = new_order;
}
Vulnerability Type: DoS +Info
CWE ID: CWE-20
Summary: The _dbus_header_byteswap function in dbus-marshal-header.c in D-Bus (aka DBus) 1.2.x before 1.2.28, 1.4.x before 1.4.12, and 1.5.x before 1.5.4 does not properly handle a non-native byte order, which allows local users to cause a denial of service (connection loss), obtain potentially sensitive information, or conduct unspecified state-modification attacks via crafted messages.
Commit Message: | Low | 164,686 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void EnterpriseEnrollmentScreen::OnAuthCancelled() {
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentCancelled,
policy::kMetricEnrollmentSize);
auth_fetcher_.reset();
registrar_.reset();
g_browser_process->browser_policy_connector()->DeviceStopAutoRetry();
get_screen_observer()->OnExit(
ScreenObserver::ENTERPRISE_ENROLLMENT_CANCELLED);
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in Google Chrome before 14.0.835.202 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors related to the Google V8 bindings.
Commit Message: Reset the device policy machinery upon retrying enrollment.
BUG=chromium-os:18208
TEST=See bug description
Review URL: http://codereview.chromium.org/7676005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 | Medium | 170,276 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: exit_ext2_xattr(void)
{
mb_cache_destroy(ext2_xattr_cache);
}
Vulnerability Type: DoS
CWE ID: CWE-19
Summary: The mbcache feature in the ext2 and ext4 filesystem implementations in the Linux kernel before 4.6 mishandles xattr block caching, which allows local users to cause a denial of service (soft lockup) via filesystem operations in environments that use many attributes, as demonstrated by Ceph and Samba.
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]> | Low | 169,976 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: const CuePoint::TrackPosition* CuePoint::Find(const Track* pTrack) const
{
assert(pTrack);
const long long n = pTrack->GetNumber();
const TrackPosition* i = m_track_positions;
const TrackPosition* const j = i + m_track_positions_count;
while (i != j)
{
const TrackPosition& p = *i++;
if (p.m_track == n)
return &p;
}
return NULL; //no matching track number found
}
Vulnerability Type: DoS Exec Code Overflow Mem. Corr.
CWE ID: CWE-119
Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792.
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 | Low | 174,278 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void VarianceTest<VarianceFunctionType>::OneQuarterTest() {
memset(src_, 255, block_size_);
const int half = block_size_ / 2;
memset(ref_, 255, half);
memset(ref_ + half, 0, half);
unsigned int sse;
unsigned int var;
REGISTER_STATE_CHECK(var = variance_(src_, width_, ref_, width_, &sse));
const unsigned int expected = block_size_ * 255 * 255 / 4;
EXPECT_EQ(expected, var);
}
Vulnerability Type: DoS Exec Code Overflow Mem. Corr.
CWE ID: CWE-119
Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792.
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
| Low | 174,585 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowDCMException(exception,message) \
{ \
if (info.scale != (Quantum *) NULL) \
info.scale=(Quantum *) RelinquishMagickMemory(info.scale); \
if (data != (unsigned char *) NULL) \
data=(unsigned char *) RelinquishMagickMemory(data); \
if (graymap != (int *) NULL) \
graymap=(int *) RelinquishMagickMemory(graymap); \
if (bluemap != (int *) NULL) \
bluemap=(int *) RelinquishMagickMemory(bluemap); \
if (greenmap != (int *) NULL) \
greenmap=(int *) RelinquishMagickMemory(greenmap); \
if (redmap != (int *) NULL) \
redmap=(int *) RelinquishMagickMemory(redmap); \
if (stream_info->offsets != (ssize_t *) NULL) \
stream_info->offsets=(ssize_t *) RelinquishMagickMemory( \
stream_info->offsets); \
if (stream_info != (DCMStreamInfo *) NULL) \
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); \
ThrowReaderException((exception),(message)); \
}
char
explicit_vr[MagickPathExtent],
implicit_vr[MagickPathExtent],
magick[MagickPathExtent],
photometric[MagickPathExtent];
DCMInfo
info;
DCMStreamInfo
*stream_info;
Image
*image;
int
*bluemap,
datum,
*greenmap,
*graymap,
*redmap;
MagickBooleanType
explicit_file,
explicit_retry,
use_explicit;
MagickOffsetType
offset;
register unsigned char
*p;
register ssize_t
i;
size_t
colors,
height,
length,
number_scenes,
quantum,
status,
width;
ssize_t
count,
scene;
unsigned char
*data;
unsigned short
group,
element;
/*
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);
}
image->depth=8UL;
image->endian=LSBEndian;
/*
Read DCM preamble.
*/
(void) memset(&info,0,sizeof(info));
data=(unsigned char *) NULL;
graymap=(int *) NULL;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info));
if (stream_info == (DCMStreamInfo *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(stream_info,0,sizeof(*stream_info));
count=ReadBlob(image,128,(unsigned char *) magick);
if (count != 128)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,4,(unsigned char *) magick);
if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0))
{
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
}
/*
Read DCM Medical image.
*/
(void) CopyMagickString(photometric,"MONOCHROME1 ",MagickPathExtent);
info.bits_allocated=8;
info.bytes_per_pixel=1;
info.depth=8;
info.mask=0xffff;
info.max_value=255UL;
info.samples_per_pixel=1;
info.signed_data=(~0UL);
info.rescale_slope=1.0;
data=(unsigned char *) NULL;
element=0;
explicit_vr[2]='\0';
explicit_file=MagickFalse;
colors=0;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
graymap=(int *) NULL;
height=0;
number_scenes=1;
use_explicit=MagickFalse;
explicit_retry = MagickFalse;
width=0;
while (TellBlob(image) < (MagickOffsetType) GetBlobSize(image))
{
for (group=0; (group != 0x7FE0) || (element != 0x0010) ; )
{
/*
Read a group.
*/
image->offset=(ssize_t) TellBlob(image);
group=ReadBlobLSBShort(image);
element=ReadBlobLSBShort(image);
if ((group == 0xfffc) && (element == 0xfffc))
break;
if ((group != 0x0002) && (image->endian == MSBEndian))
{
group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF));
element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF));
}
quantum=0;
/*
Find corresponding VR for this group and element.
*/
for (i=0; dicom_info[i].group < 0xffff; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent);
count=ReadBlob(image,2,(unsigned char *) explicit_vr);
if (count != 2)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
/*
Check for "explicitness", but meta-file headers always explicit.
*/
if ((explicit_file == MagickFalse) && (group != 0x0002))
explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) &&
(isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ?
MagickTrue : MagickFalse;
use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) ||
(explicit_file != MagickFalse) ? MagickTrue : MagickFalse;
if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0))
(void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent);
if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0))
{
offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR);
if (offset < 0)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
quantum=4;
}
else
{
/*
Assume explicit type.
*/
quantum=2;
if ((strncmp(explicit_vr,"OB",2) == 0) ||
(strncmp(explicit_vr,"UN",2) == 0) ||
(strncmp(explicit_vr,"OW",2) == 0) ||
(strncmp(explicit_vr,"SQ",2) == 0))
{
(void) ReadBlobLSBShort(image);
quantum=4;
}
}
datum=0;
if (quantum == 4)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if (quantum == 2)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
quantum=0;
length=1;
if (datum != 0)
{
if ((strncmp(implicit_vr,"OW",2) == 0) ||
(strncmp(implicit_vr,"SS",2) == 0) ||
(strncmp(implicit_vr,"US",2) == 0))
quantum=2;
else
if ((strncmp(implicit_vr,"FL",2) == 0) ||
(strncmp(implicit_vr,"OF",2) == 0) ||
(strncmp(implicit_vr,"SL",2) == 0) ||
(strncmp(implicit_vr,"UL",2) == 0))
quantum=4;
else
if (strncmp(implicit_vr,"FD",2) == 0)
quantum=8;
else
quantum=1;
if (datum != ~0)
length=(size_t) datum/quantum;
else
{
/*
Sequence and item of undefined length.
*/
quantum=0;
length=0;
}
}
if (image_info->verbose != MagickFalse)
{
/*
Display Dicom info.
*/
if (use_explicit == MagickFalse)
explicit_vr[0]='\0';
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)",
(unsigned long) image->offset,(long) length,implicit_vr,explicit_vr,
(unsigned long) group,(unsigned long) element);
if (dicom_info[i].description != (char *) NULL)
(void) FormatLocaleFile(stdout," %s",dicom_info[i].description);
(void) FormatLocaleFile(stdout,": ");
}
if ((group == 0x7FE0) && (element == 0x0010))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"\n");
break;
}
/*
Allocate space and read an array.
*/
data=(unsigned char *) NULL;
if ((length == 1) && (quantum == 1))
datum=ReadBlobByte(image);
else
if ((length == 1) && (quantum == 2))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
else
if ((length == 1) && (quantum == 4))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if ((quantum != 0) && (length != 0))
{
if (length > (size_t) GetBlobSize(image))
ThrowDCMException(CorruptImageError,
"InsufficientImageDataInFile");
if (~length >= 1)
data=(unsigned char *) AcquireQuantumMemory(length+1,quantum*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowDCMException(ResourceLimitError,
"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) quantum*length,data);
if (count != (ssize_t) (quantum*length))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"count=%d quantum=%d "
"length=%d group=%d\n",(int) count,(int) quantum,(int)
length,(int) group);
ThrowDCMException(CorruptImageError,
"InsufficientImageDataInFile");
}
data[length*quantum]='\0';
}
if ((((unsigned int) group << 16) | element) == 0xFFFEE0DD)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
continue;
}
switch (group)
{
case 0x0002:
{
switch (element)
{
case 0x0010:
{
char
transfer_syntax[MagickPathExtent];
/*
Transfer Syntax.
*/
if ((datum == 0) && (explicit_retry == MagickFalse))
{
explicit_retry=MagickTrue;
(void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET);
group=0;
element=0;
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,
"Corrupted image - trying explicit format\n");
break;
}
*transfer_syntax='\0';
if (data != (unsigned char *) NULL)
(void) CopyMagickString(transfer_syntax,(char *) data,
MagickPathExtent);
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"transfer_syntax=%s\n",
(const char *) transfer_syntax);
if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0)
{
int
subtype,
type;
type=1;
subtype=0;
if (strlen(transfer_syntax) > 17)
{
count=(ssize_t) sscanf(transfer_syntax+17,".%d.%d",&type,
&subtype);
if (count < 1)
ThrowDCMException(CorruptImageError,
"ImproperImageHeader");
}
switch (type)
{
case 1:
{
image->endian=LSBEndian;
break;
}
case 2:
{
image->endian=MSBEndian;
break;
}
case 4:
{
if ((subtype >= 80) && (subtype <= 81))
image->compression=JPEGCompression;
else
if ((subtype >= 90) && (subtype <= 93))
image->compression=JPEG2000Compression;
else
image->compression=JPEGCompression;
break;
}
case 5:
{
image->compression=RLECompression;
break;
}
}
}
break;
}
default:
break;
}
break;
}
case 0x0028:
{
switch (element)
{
case 0x0002:
{
/*
Samples per pixel.
*/
info.samples_per_pixel=(size_t) datum;
if ((info.samples_per_pixel == 0) || (info.samples_per_pixel > 4))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
break;
}
case 0x0004:
{
/*
Photometric interpretation.
*/
if (data == (unsigned char *) NULL)
break;
for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++)
photometric[i]=(char) data[i];
photometric[i]='\0';
info.polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ?
MagickTrue : MagickFalse;
break;
}
case 0x0006:
{
/*
Planar configuration.
*/
if (datum == 1)
image->interlace=PlaneInterlace;
break;
}
case 0x0008:
{
/*
Number of frames.
*/
if (data == (unsigned char *) NULL)
break;
number_scenes=StringToUnsignedLong((char *) data);
break;
}
case 0x0010:
{
/*
Image rows.
*/
height=(size_t) datum;
break;
}
case 0x0011:
{
/*
Image columns.
*/
width=(size_t) datum;
break;
}
case 0x0100:
{
/*
Bits allocated.
*/
info.bits_allocated=(size_t) datum;
info.bytes_per_pixel=1;
if (datum > 8)
info.bytes_per_pixel=2;
info.depth=info.bits_allocated;
if ((info.depth == 0) || (info.depth > 32))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
info.max_value=(1UL << info.bits_allocated)-1;
image->depth=info.depth;
break;
}
case 0x0101:
{
/*
Bits stored.
*/
info.significant_bits=(size_t) datum;
info.bytes_per_pixel=1;
if (info.significant_bits > 8)
info.bytes_per_pixel=2;
info.depth=info.significant_bits;
if ((info.depth == 0) || (info.depth > 16))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
info.max_value=(1UL << info.significant_bits)-1;
info.mask=(size_t) GetQuantumRange(info.significant_bits);
image->depth=info.depth;
break;
}
case 0x0102:
{
/*
High bit.
*/
break;
}
case 0x0103:
{
/*
Pixel representation.
*/
info.signed_data=(size_t) datum;
break;
}
case 0x1050:
{
/*
Visible pixel range: center.
*/
if (data != (unsigned char *) NULL)
info.window_center=StringToDouble((char *) data,(char **) NULL);
break;
}
case 0x1051:
{
/*
Visible pixel range: width.
*/
if (data != (unsigned char *) NULL)
info.window_width=StringToDouble((char *) data,(char **) NULL);
break;
}
case 0x1052:
{
/*
Rescale intercept
*/
if (data != (unsigned char *) NULL)
info.rescale_intercept=StringToDouble((char *) data,
(char **) NULL);
break;
}
case 0x1053:
{
/*
Rescale slope
*/
if (data != (unsigned char *) NULL)
info.rescale_slope=StringToDouble((char *) data,(char **) NULL);
break;
}
case 0x1200:
case 0x3006:
{
/*
Populate graymap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/info.bytes_per_pixel);
datum=(int) colors;
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
graymap=(int *) AcquireQuantumMemory(MagickMax(colors,65536),
sizeof(*graymap));
if (graymap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(graymap,0,MagickMax(colors,65536)*
sizeof(*graymap));
for (i=0; i < (ssize_t) colors; i++)
if (info.bytes_per_pixel == 1)
graymap[i]=(int) data[i];
else
graymap[i]=(int) ((short *) data)[i];
break;
}
case 0x1201:
{
unsigned short
index;
/*
Populate redmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
redmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536),
sizeof(*redmap));
if (redmap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(redmap,0,MagickMax(colors,65536)*
sizeof(*redmap));
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
redmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1202:
{
unsigned short
index;
/*
Populate greenmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
greenmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536),
sizeof(*greenmap));
if (greenmap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(greenmap,0,MagickMax(colors,65536)*
sizeof(*greenmap));
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
greenmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1203:
{
unsigned short
index;
/*
Populate bluemap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
bluemap=(int *) AcquireQuantumMemory(MagickMax(colors,65536),
sizeof(*bluemap));
if (bluemap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(bluemap,0,MagickMax(colors,65536)*
sizeof(*bluemap));
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
bluemap[i]=(int) index;
p+=2;
}
break;
}
default:
break;
}
break;
}
case 0x2050:
{
switch (element)
{
case 0x0020:
{
if ((data != (unsigned char *) NULL) &&
(strncmp((char *) data,"INVERSE",7) == 0))
info.polarity=MagickTrue;
break;
}
default:
break;
}
break;
}
default:
break;
}
if (data != (unsigned char *) NULL)
{
char
*attribute;
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
if (dicom_info[i].description != (char *) NULL)
{
attribute=AcquireString("dcm:");
(void) ConcatenateString(&attribute,dicom_info[i].description);
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i == (ssize_t) length) || (length > 4))
{
(void) SubstituteString(&attribute," ","");
(void) SetImageProperty(image,attribute,(char *) data,
exception);
}
attribute=DestroyString(attribute);
}
}
if (image_info->verbose != MagickFalse)
{
if (data == (unsigned char *) NULL)
(void) FormatLocaleFile(stdout,"%d\n",datum);
else
{
/*
Display group data.
*/
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i != (ssize_t) length) && (length <= 4))
{
ssize_t
j;
datum=0;
for (j=(ssize_t) length-1; j >= 0; j--)
datum=(256*datum+data[j]);
(void) FormatLocaleFile(stdout,"%d",datum);
}
else
for (i=0; i < (ssize_t) length; i++)
if (isprint((int) data[i]) != MagickFalse)
(void) FormatLocaleFile(stdout,"%c",data[i]);
else
(void) FormatLocaleFile(stdout,"%c",'.');
(void) FormatLocaleFile(stdout,"\n");
}
}
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
if ((group == 0xfffc) && (element == 0xfffc))
{
Image
*last;
last=RemoveLastImageFromList(&image);
if (last != (Image *) NULL)
last=DestroyImage(last);
break;
}
if ((width == 0) || (height == 0))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) width;
image->rows=(size_t) height;
if (info.signed_data == 0xffff)
info.signed_data=(size_t) (info.significant_bits == 16 ? 1 : 0);
if ((image->compression == JPEGCompression) ||
(image->compression == JPEG2000Compression))
{
Image
*images;
ImageInfo
*read_info;
int
c;
/*
Read offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
if (ReadBlobByte(image) == EOF)
break;
(void) (((ssize_t) ReadBlobLSBShort(image) << 16) |
ReadBlobLSBShort(image));
length=(size_t) ReadBlobLSBLong(image);
if (length > (size_t) GetBlobSize(image))
ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile");
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *) RelinquishMagickMemory(
stream_info->offsets);
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
/*
Handle non-native image formats.
*/
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
images=NewImageList();
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
char
filename[MagickPathExtent];
const char
*property;
FILE
*file;
Image
*jpeg_image;
int
unique_file;
unsigned int
tag;
tag=((unsigned int) ReadBlobLSBShort(image) << 16) |
ReadBlobLSBShort(image);
length=(size_t) ReadBlobLSBLong(image);
if (tag == 0xFFFEE0DD)
break; /* sequence delimiter tag */
if (tag != 0xFFFEE000)
{
read_info=DestroyImageInfo(read_info);
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
}
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if (file == (FILE *) NULL)
{
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
break;
}
for (c=EOF; length != 0; length--)
{
c=ReadBlobByte(image);
if (c == EOF)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
(void) fputc(c,file);
}
(void) fclose(file);
if (c == EOF)
break;
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"jpeg:%s",filename);
if (image->compression == JPEG2000Compression)
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"j2k:%s",filename);
jpeg_image=ReadImage(read_info,exception);
if (jpeg_image != (Image *) NULL)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
(void) SetImageProperty(jpeg_image,property,
GetImageProperty(image,property,exception),exception);
property=GetNextImageProperty(image);
}
AppendImageToList(&images,jpeg_image);
}
(void) RelinquishUniqueFileResource(filename);
}
read_info=DestroyImageInfo(read_info);
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (info.scale != (Quantum *) NULL)
info.scale=(Quantum *) RelinquishMagickMemory(info.scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
image=DestroyImageList(image);
return(GetFirstImageInList(images));
}
if (info.depth != (1UL*MAGICKCORE_QUANTUM_DEPTH))
{
QuantumAny
range;
/*
Compute pixel scaling table.
*/
length=(size_t) (GetQuantumRange(info.depth)+1);
if (length > (size_t) GetBlobSize(image))
ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile");
if (info.scale != (Quantum *) NULL)
info.scale=(Quantum *) RelinquishMagickMemory(info.scale);
info.scale=(Quantum *) AcquireQuantumMemory(MagickMax(length,256),
sizeof(*info.scale));
if (info.scale == (Quantum *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(info.scale,0,MagickMax(length,256)*
sizeof(*info.scale));
range=GetQuantumRange(info.depth);
for (i=0; i <= (ssize_t) GetQuantumRange(info.depth); i++)
info.scale[i]=ScaleAnyToQuantum((size_t) i,range);
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
tag=((unsigned int) ReadBlobLSBShort(image) << 16) |
ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
if (length > (size_t) GetBlobSize(image))
ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile");
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
{
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
if (EOFBlob(image) != MagickFalse)
break;
}
offset=TellBlob(image)+8;
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
}
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
if (image_info->ping != MagickFalse)
break;
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=info.depth;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
image->colorspace=RGBColorspace;
(void) SetImageBackgroundColor(image,exception);
if ((image->colormap == (PixelInfo *) NULL) &&
(info.samples_per_pixel == 1))
{
int
index;
size_t
one;
one=1;
if (colors == 0)
colors=one << info.depth;
if (AcquireImageColormap(image,colors,exception) == MagickFalse)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
if (redmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=redmap[i];
if ((info.scale != (Quantum *) NULL) && (index >= 0) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].red=(MagickRealType) index;
}
if (greenmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=greenmap[i];
if ((info.scale != (Quantum *) NULL) && (index >= 0) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].green=(MagickRealType) index;
}
if (bluemap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=bluemap[i];
if ((info.scale != (Quantum *) NULL) && (index >= 0) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].blue=(MagickRealType) index;
}
if (graymap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=graymap[i];
if ((info.scale != (Quantum *) NULL) && (index >= 0) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].red=(MagickRealType) index;
image->colormap[i].green=(MagickRealType) index;
image->colormap[i].blue=(MagickRealType) index;
}
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE segment table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
tag=((unsigned int) ReadBlobLSBShort(image) << 16) |
ReadBlobLSBShort(image);
stream_info->remaining=(size_t) ReadBlobLSBLong(image);
if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) ||
(EOFBlob(image) != MagickFalse))
{
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
}
stream_info->count=0;
stream_info->segment_count=ReadBlobLSBLong(image);
for (i=0; i < 15; i++)
stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image);
stream_info->remaining-=64;
if (stream_info->segment_count > 1)
{
info.bytes_per_pixel=1;
info.depth=8;
if (stream_info->offset_count > 0)
(void) SeekBlob(image,(MagickOffsetType)
stream_info->offsets[0]+stream_info->segments[0],SEEK_SET);
}
}
if ((info.samples_per_pixel > 1) && (image->interlace == PlaneInterlace))
{
register ssize_t
x;
register Quantum
*q;
ssize_t
y;
/*
Convert Planar RGB DCM Medical image to pixel packets.
*/
for (i=0; i < (ssize_t) info.samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch ((int) i)
{
case 0:
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 1:
{
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 2:
{
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 3:
{
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
default:
break;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
}
else
{
const char
*option;
/*
Convert DCM Medical image to pixel packets.
*/
option=GetImageOption(image_info,"dcm:display-range");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"reset") == 0)
info.window_width=0;
}
option=GetImageOption(image_info,"dcm:window");
if (option != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(option,&geometry_info);
if (flags & RhoValue)
info.window_center=geometry_info.rho;
if (flags & SigmaValue)
info.window_width=geometry_info.sigma;
info.rescale=MagickTrue;
}
option=GetImageOption(image_info,"dcm:rescale");
if (option != (char *) NULL)
info.rescale=IsStringTrue(option);
if ((info.window_center != 0) && (info.window_width == 0))
info.window_width=info.window_center;
status=ReadDCMPixels(image,&info,stream_info,MagickTrue,exception);
if ((status != MagickFalse) && (stream_info->segment_count > 1))
{
if (stream_info->offset_count > 0)
(void) SeekBlob(image,(MagickOffsetType)
stream_info->offsets[0]+stream_info->segments[1],SEEK_SET);
(void) ReadDCMPixels(image,&info,stream_info,MagickFalse,
exception);
}
}
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace,exception);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (number_scenes-1))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
if (TellBlob(image) < (MagickOffsetType) GetBlobSize(image))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
/*
Free resources.
*/
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (info.scale != (Quantum *) NULL)
info.scale=(Quantum *) RelinquishMagickMemory(info.scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The functions ReadDCMImage in coders/dcm.c, ReadPWPImage in coders/pwp.c, ReadCALSImage in coders/cals.c, and ReadPICTImage in coders/pict.c in ImageMagick 7.0.8-4 do not check the return value of the fputc function, which allows remote attackers to cause a denial of service via a crafted image file.
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1199 | Medium | 169,039 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static void sctp_v6_get_dst(struct sctp_transport *t, union sctp_addr *saddr,
struct flowi *fl, struct sock *sk)
{
struct sctp_association *asoc = t->asoc;
struct dst_entry *dst = NULL;
struct flowi6 *fl6 = &fl->u.ip6;
struct sctp_bind_addr *bp;
struct sctp_sockaddr_entry *laddr;
union sctp_addr *baddr = NULL;
union sctp_addr *daddr = &t->ipaddr;
union sctp_addr dst_saddr;
__u8 matchlen = 0;
__u8 bmatchlen;
sctp_scope_t scope;
memset(fl6, 0, sizeof(struct flowi6));
fl6->daddr = daddr->v6.sin6_addr;
fl6->fl6_dport = daddr->v6.sin6_port;
fl6->flowi6_proto = IPPROTO_SCTP;
if (ipv6_addr_type(&daddr->v6.sin6_addr) & IPV6_ADDR_LINKLOCAL)
fl6->flowi6_oif = daddr->v6.sin6_scope_id;
pr_debug("%s: dst=%pI6 ", __func__, &fl6->daddr);
if (asoc)
fl6->fl6_sport = htons(asoc->base.bind_addr.port);
if (saddr) {
fl6->saddr = saddr->v6.sin6_addr;
fl6->fl6_sport = saddr->v6.sin6_port;
pr_debug("src=%pI6 - ", &fl6->saddr);
}
dst = ip6_dst_lookup_flow(sk, fl6, NULL, false);
if (!asoc || saddr)
goto out;
bp = &asoc->base.bind_addr;
scope = sctp_scope(daddr);
/* ip6_dst_lookup has filled in the fl6->saddr for us. Check
* to see if we can use it.
*/
if (!IS_ERR(dst)) {
/* Walk through the bind address list and look for a bind
* address that matches the source address of the returned dst.
*/
sctp_v6_to_addr(&dst_saddr, &fl6->saddr, htons(bp->port));
rcu_read_lock();
list_for_each_entry_rcu(laddr, &bp->address_list, list) {
if (!laddr->valid || (laddr->state != SCTP_ADDR_SRC))
continue;
/* Do not compare against v4 addrs */
if ((laddr->a.sa.sa_family == AF_INET6) &&
(sctp_v6_cmp_addr(&dst_saddr, &laddr->a))) {
rcu_read_unlock();
goto out;
}
}
rcu_read_unlock();
/* None of the bound addresses match the source address of the
* dst. So release it.
*/
dst_release(dst);
dst = NULL;
}
/* Walk through the bind address list and try to get the
* best source address for a given destination.
*/
rcu_read_lock();
list_for_each_entry_rcu(laddr, &bp->address_list, list) {
if (!laddr->valid)
continue;
if ((laddr->state == SCTP_ADDR_SRC) &&
(laddr->a.sa.sa_family == AF_INET6) &&
(scope <= sctp_scope(&laddr->a))) {
bmatchlen = sctp_v6_addr_match_len(daddr, &laddr->a);
if (!baddr || (matchlen < bmatchlen)) {
baddr = &laddr->a;
matchlen = bmatchlen;
}
}
}
rcu_read_unlock();
if (baddr) {
fl6->saddr = baddr->v6.sin6_addr;
fl6->fl6_sport = baddr->v6.sin6_port;
dst = ip6_dst_lookup_flow(sk, fl6, NULL, false);
}
out:
if (!IS_ERR_OR_NULL(dst)) {
struct rt6_info *rt;
rt = (struct rt6_info *)dst;
t->dst = dst;
t->dst_cookie = rt->rt6i_node ? rt->rt6i_node->fn_sernum : 0;
pr_debug("rt6_dst:%pI6 rt6_src:%pI6\n", &rt->rt6i_dst.addr,
&fl6->saddr);
} else {
t->dst = NULL;
pr_debug("no route\n");
}
}
Vulnerability Type: +Info
CWE ID: CWE-310
Summary: The IPv6 SCTP implementation in net/sctp/ipv6.c in the Linux kernel through 3.11.1 uses data structures and function calls that do not trigger an intended configuration of IPsec encryption, which allows remote attackers to obtain sensitive information by sniffing the network.
Commit Message: net: sctp: fix ipv6 ipsec encryption bug in sctp_v6_xmit
Alan Chester reported an issue with IPv6 on SCTP that IPsec traffic is not
being encrypted, whereas on IPv4 it is. Setting up an AH + ESP transport
does not seem to have the desired effect:
SCTP + IPv4:
22:14:20.809645 IP (tos 0x2,ECT(0), ttl 64, id 0, offset 0, flags [DF], proto AH (51), length 116)
192.168.0.2 > 192.168.0.5: AH(spi=0x00000042,sumlen=16,seq=0x1): ESP(spi=0x00000044,seq=0x1), length 72
22:14:20.813270 IP (tos 0x2,ECT(0), ttl 64, id 0, offset 0, flags [DF], proto AH (51), length 340)
192.168.0.5 > 192.168.0.2: AH(spi=0x00000043,sumlen=16,seq=0x1):
SCTP + IPv6:
22:31:19.215029 IP6 (class 0x02, hlim 64, next-header SCTP (132) payload length: 364)
fe80::222:15ff:fe87:7fc.3333 > fe80::92e6:baff:fe0d:5a54.36767: sctp
1) [INIT ACK] [init tag: 747759530] [rwnd: 62464] [OS: 10] [MIS: 10]
Moreover, Alan says:
This problem was seen with both Racoon and Racoon2. Other people have seen
this with OpenSwan. When IPsec is configured to encrypt all upper layer
protocols the SCTP connection does not initialize. After using Wireshark to
follow packets, this is because the SCTP packet leaves Box A unencrypted and
Box B believes all upper layer protocols are to be encrypted so it drops
this packet, causing the SCTP connection to fail to initialize. When IPsec
is configured to encrypt just SCTP, the SCTP packets are observed unencrypted.
In fact, using `socat sctp6-listen:3333 -` on one end and transferring "plaintext"
string on the other end, results in cleartext on the wire where SCTP eventually
does not report any errors, thus in the latter case that Alan reports, the
non-paranoid user might think he's communicating over an encrypted transport on
SCTP although he's not (tcpdump ... -X):
...
0x0030: 5d70 8e1a 0003 001a 177d eb6c 0000 0000 ]p.......}.l....
0x0040: 0000 0000 706c 6169 6e74 6578 740a 0000 ....plaintext...
Only in /proc/net/xfrm_stat we can see XfrmInTmplMismatch increasing on the
receiver side. Initial follow-up analysis from Alan's bug report was done by
Alexey Dobriyan. Also thanks to Vlad Yasevich for feedback on this.
SCTP has its own implementation of sctp_v6_xmit() not calling inet6_csk_xmit().
This has the implication that it probably never really got updated along with
changes in inet6_csk_xmit() and therefore does not seem to invoke xfrm handlers.
SCTP's IPv4 xmit however, properly calls ip_queue_xmit() to do the work. Since
a call to inet6_csk_xmit() would solve this problem, but result in unecessary
route lookups, let us just use the cached flowi6 instead that we got through
sctp_v6_get_dst(). Since all SCTP packets are being sent through sctp_packet_transmit(),
we do the route lookup / flow caching in sctp_transport_route(), hold it in
tp->dst and skb_dst_set() right after that. If we would alter fl6->daddr in
sctp_v6_xmit() to np->opt->srcrt, we possibly could run into the same effect
of not having xfrm layer pick it up, hence, use fl6_update_dst() in sctp_v6_get_dst()
instead to get the correct source routed dst entry, which we assign to the skb.
Also source address routing example from 625034113 ("sctp: fix sctp to work with
ipv6 source address routing") still works with this patch! Nevertheless, in RFC5095
it is actually 'recommended' to not use that anyway due to traffic amplification [1].
So it seems we're not supposed to do that anyway in sctp_v6_xmit(). Moreover, if
we overwrite the flow destination here, the lower IPv6 layer will be unable to
put the correct destination address into IP header, as routing header is added in
ipv6_push_nfrag_opts() but then probably with wrong final destination. Things aside,
result of this patch is that we do not have any XfrmInTmplMismatch increase plus on
the wire with this patch it now looks like:
SCTP + IPv6:
08:17:47.074080 IP6 2620:52:0:102f:7a2b:cbff:fe27:1b0a > 2620:52:0:102f:213:72ff:fe32:7eba:
AH(spi=0x00005fb4,seq=0x1): ESP(spi=0x00005fb5,seq=0x1), length 72
08:17:47.074264 IP6 2620:52:0:102f:213:72ff:fe32:7eba > 2620:52:0:102f:7a2b:cbff:fe27:1b0a:
AH(spi=0x00003d54,seq=0x1): ESP(spi=0x00003d55,seq=0x1), length 296
This fixes Kernel Bugzilla 24412. This security issue seems to be present since
2.6.18 kernels. Lets just hope some big passive adversary in the wild didn't have
its fun with that. lksctp-tools IPv6 regression test suite passes as well with
this patch.
[1] http://www.secdev.org/conf/IPv6_RH_security-csw07.pdf
Reported-by: Alan Chester <[email protected]>
Reported-by: Alexey Dobriyan <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
Cc: Steffen Klassert <[email protected]>
Cc: Hannes Frederic Sowa <[email protected]>
Acked-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]> | Low | 165,989 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static void destroy_server_connect(SERVER_CONNECT_REC *conn)
{
IRC_SERVER_CONNECT_REC *ircconn;
ircconn = IRC_SERVER_CONNECT(conn);
if (ircconn == NULL)
return;
g_free_not_null(ircconn->usermode);
g_free_not_null(ircconn->alternate_nick);
}
Vulnerability Type:
CWE ID: CWE-416
Summary: Irssi before 1.0.8, 1.1.x before 1.1.3, and 1.2.x before 1.2.1, when SASL is enabled, has a use after free when sending SASL login to the server.
Commit Message: Merge pull request #1058 from ailin-nemui/sasl-reconnect
copy sasl username and password values | Medium | 169,642 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: gss_krb5int_export_lucid_sec_context(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
krb5_error_code kret = 0;
OM_uint32 retval;
krb5_gss_ctx_id_t ctx = (krb5_gss_ctx_id_t)context_handle;
void *lctx = NULL;
int version = 0;
gss_buffer_desc rep;
/* Assume failure */
retval = GSS_S_FAILURE;
*minor_status = 0;
*data_set = GSS_C_NO_BUFFER_SET;
retval = generic_gss_oid_decompose(minor_status,
GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID,
GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID_LENGTH,
desired_object,
&version);
if (GSS_ERROR(retval))
return retval;
/* Externalize a structure of the right version */
switch (version) {
case 1:
kret = make_external_lucid_ctx_v1((krb5_pointer)ctx,
version, &lctx);
break;
default:
kret = (OM_uint32) KG_LUCID_VERSION;
break;
}
if (kret)
goto error_out;
rep.value = &lctx;
rep.length = sizeof(lctx);
retval = generic_gss_add_buffer_set_member(minor_status, &rep, data_set);
if (GSS_ERROR(retval))
goto error_out;
error_out:
if (*minor_status == 0)
*minor_status = (OM_uint32) kret;
return(retval);
}
Vulnerability Type: DoS Exec Code
CWE ID:
Summary: The krb5_gss_process_context_token function in lib/gssapi/krb5/process_context_token.c in the libgssapi_krb5 library in MIT Kerberos 5 (aka krb5) through 1.11.5, 1.12.x through 1.12.2, and 1.13.x before 1.13.1 does not properly maintain security-context handles, which allows remote authenticated users to cause a denial of service (use-after-free and double free, and daemon crash) or possibly execute arbitrary code via crafted GSSAPI traffic, as demonstrated by traffic to kadmind.
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup | Low | 166,821 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void BrowserWindowGtk::TabDetachedAt(TabContents* contents, int index) {
if (index == browser_->active_index()) {
infobar_container_->ChangeTabContents(NULL);
UpdateDevToolsForContents(NULL);
}
contents_container_->DetachTab(contents);
}
Vulnerability Type:
CWE ID: CWE-20
Summary: The hyphenation functionality in Google Chrome before 24.0.1312.52 does not properly validate file names, which has unspecified impact and attack vectors.
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 | Low | 171,513 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static gboolean netscreen_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
gint64 offset;
int pkt_len;
char line[NETSCREEN_LINE_LENGTH];
char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH];
gboolean cap_dir;
char cap_dst[13];
/* Find the next packet */
offset = netscreen_seek_next_packet(wth, err, err_info, line);
if (offset < 0)
return FALSE;
/* Parse the header */
pkt_len = parse_netscreen_rec_hdr(&wth->phdr, line, cap_int, &cap_dir,
cap_dst, err, err_info);
if (pkt_len == -1)
return FALSE;
/* Convert the ASCII hex dump to binary data, and fill in some
struct wtap_pkthdr fields */
if (!parse_netscreen_hex_dump(wth->fh, pkt_len, cap_int,
cap_dst, &wth->phdr, wth->frame_buffer, err, err_info))
return FALSE;
/*
* If the per-file encapsulation isn't known, set it to this
* packet's encapsulation.
*
* If it *is* known, and it isn't this packet's encapsulation,
* set it to WTAP_ENCAP_PER_PACKET, as this file doesn't
* have a single encapsulation for all packets in the file.
*/
if (wth->file_encap == WTAP_ENCAP_UNKNOWN)
wth->file_encap = wth->phdr.pkt_encap;
else {
if (wth->file_encap != wth->phdr.pkt_encap)
wth->file_encap = WTAP_ENCAP_PER_PACKET;
}
*data_offset = offset;
return TRUE;
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: wiretap/netscreen.c in the NetScreen file parser in Wireshark 1.12.x before 1.12.12 and 2.x before 2.0.4 mishandles sscanf unsigned-integer processing, which allows remote attackers to cause a denial of service (application crash) via a crafted file.
Commit Message: Fix packet length handling.
Treat the packet length as unsigned - it shouldn't be negative in the
file. If it is, that'll probably cause the sscanf to fail, so we'll
report the file as bad.
Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to
allocate a huge amount of memory, just as we do in other file readers.
Use the now-validated packet size as the length in
ws_buffer_assure_space(), so we are certain to have enough space, and
don't allocate too much space.
Merge the header and packet data parsing routines while we're at it.
Bug: 12396
Change-Id: I7f981f9cdcbea7ecdeb88bfff2f12d875de2244f
Reviewed-on: https://code.wireshark.org/review/15176
Reviewed-by: Guy Harris <[email protected]> | Medium | 167,146 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static int ipx_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct ipx_sock *ipxs = ipx_sk(sk);
struct sockaddr_ipx *sipx = (struct sockaddr_ipx *)msg->msg_name;
struct ipxhdr *ipx = NULL;
struct sk_buff *skb;
int copied, rc;
lock_sock(sk);
/* put the autobinding in */
if (!ipxs->port) {
struct sockaddr_ipx uaddr;
uaddr.sipx_port = 0;
uaddr.sipx_network = 0;
#ifdef CONFIG_IPX_INTERN
rc = -ENETDOWN;
if (!ipxs->intrfc)
goto out; /* Someone zonked the iface */
memcpy(uaddr.sipx_node, ipxs->intrfc->if_node, IPX_NODE_LEN);
#endif /* CONFIG_IPX_INTERN */
rc = __ipx_bind(sock, (struct sockaddr *)&uaddr,
sizeof(struct sockaddr_ipx));
if (rc)
goto out;
}
rc = -ENOTCONN;
if (sock_flag(sk, SOCK_ZAPPED))
goto out;
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &rc);
if (!skb)
goto out;
ipx = ipx_hdr(skb);
copied = ntohs(ipx->ipx_pktsize) - sizeof(struct ipxhdr);
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
rc = skb_copy_datagram_iovec(skb, sizeof(struct ipxhdr), msg->msg_iov,
copied);
if (rc)
goto out_free;
if (skb->tstamp.tv64)
sk->sk_stamp = skb->tstamp;
msg->msg_namelen = sizeof(*sipx);
if (sipx) {
sipx->sipx_family = AF_IPX;
sipx->sipx_port = ipx->ipx_source.sock;
memcpy(sipx->sipx_node, ipx->ipx_source.node, IPX_NODE_LEN);
sipx->sipx_network = IPX_SKB_CB(skb)->ipx_source_net;
sipx->sipx_type = ipx->ipx_type;
sipx->sipx_zero = 0;
}
rc = copied;
out_free:
skb_free_datagram(sk, skb);
out:
release_sock(sk);
return rc;
}
Vulnerability Type: +Info
CWE ID: CWE-20
Summary: The x25_recvmsg function in net/x25/af_x25.c in the Linux kernel before 3.12.4 updates a certain length value without ensuring that an associated data structure has been initialized, which allows local users to obtain sensitive information from kernel memory via a (1) recvfrom, (2) recvmmsg, or (3) recvmsg system call.
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]> | Low | 166,500 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static void set_active_map(const vpx_codec_enc_cfg_t *cfg,
vpx_codec_ctx_t *codec) {
unsigned int i;
vpx_active_map_t map = {0};
map.rows = (cfg->g_h + 15) / 16;
map.cols = (cfg->g_w + 15) / 16;
map.active_map = (uint8_t *)malloc(map.rows * map.cols);
for (i = 0; i < map.rows * map.cols; ++i)
map.active_map[i] = i % 2;
if (vpx_codec_control(codec, VP8E_SET_ACTIVEMAP, &map))
die_codec(codec, "Failed to set active map");
free(map.active_map);
}
Vulnerability Type: DoS Exec Code Overflow Mem. Corr.
CWE ID: CWE-119
Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792.
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
| Low | 174,483 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int c, l;
xmlChar stop;
xmlChar *ret = NULL;
const xmlChar *cur = NULL;
xmlParserInputPtr input;
if (RAW == '"') stop = '"';
else if (RAW == '\'') stop = '\'';
else {
xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
/*
* The content of the entity definition is copied in a buffer.
*/
ctxt->instate = XML_PARSER_ENTITY_VALUE;
input = ctxt->input;
GROW;
NEXT;
c = CUR_CHAR(l);
/*
* NOTE: 4.4.5 Included in Literal
* When a parameter entity reference appears in a literal entity
* value, ... a single or double quote character in the replacement
* text is always treated as a normal data character and will not
* terminate the literal.
* In practice it means we stop the loop only when back at parsing
* the initial entity and the quote is found
*/
while ((IS_CHAR(c)) && ((c != stop) || /* checked */
(ctxt->input != input))) {
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
return(NULL);
}
buf = tmp;
}
COPY_BUF(l,buf,len,c);
NEXTL(l);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1)) /* non input consuming */
xmlPopInput(ctxt);
GROW;
c = CUR_CHAR(l);
if (c == 0) {
GROW;
c = CUR_CHAR(l);
}
}
buf[len] = 0;
/*
* Raise problem w.r.t. '&' and '%' being used in non-entities
* reference constructs. Note Charref will be handled in
* xmlStringDecodeEntities()
*/
cur = buf;
while (*cur != 0) { /* non input consuming */
if ((*cur == '%') || ((*cur == '&') && (cur[1] != '#'))) {
xmlChar *name;
xmlChar tmp = *cur;
cur++;
name = xmlParseStringName(ctxt, &cur);
if ((name == NULL) || (*cur != ';')) {
xmlFatalErrMsgInt(ctxt, XML_ERR_ENTITY_CHAR_ERROR,
"EntityValue: '%c' forbidden except for entities references\n",
tmp);
}
if ((tmp == '%') && (ctxt->inSubset == 1) &&
(ctxt->inputNr == 1)) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL);
}
if (name != NULL)
xmlFree(name);
if (*cur == 0)
break;
}
cur++;
}
/*
* Then PEReference entities are substituted.
*/
if (c != stop) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL);
xmlFree(buf);
} else {
NEXT;
/*
* NOTE: 4.4.7 Bypassed
* When a general entity reference appears in the EntityValue in
* an entity declaration, it is bypassed and left as is.
* so XML_SUBSTITUTE_REF is not set here.
*/
ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF,
0, 0, 0);
if (orig != NULL)
*orig = buf;
else
xmlFree(buf);
}
return(ret);
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: parser.c in libxml2 before 2.9.0, as used in Google Chrome before 28.0.1500.71 and other products, allows remote attackers to cause a denial of service (out-of-bounds read) via a document that ends abruptly, related to the lack of certain checks for the XML_PARSER_EOF state.
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 | Low | 171,290 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
{
uint8_t byte;
if (bytestream2_get_bytes_left(&s->g) < 5)
return AVERROR_INVALIDDATA;
/* nreslevels = number of resolution levels
= number of decomposition level +1 */
c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) {
av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels);
return AVERROR_INVALIDDATA;
}
/* compute number of resolution levels to decode */
if (c->nreslevels < s->reduction_factor)
c->nreslevels2decode = 1;
else
c->nreslevels2decode = c->nreslevels - s->reduction_factor;
c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
c->log2_cblk_width + c->log2_cblk_height > 12) {
av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
return AVERROR_INVALIDDATA;
}
c->cblk_style = bytestream2_get_byteu(&s->g);
if (c->cblk_style != 0) { // cblk style
av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
}
c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
/* set integer 9/7 DWT in case of BITEXACT flag */
if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
c->transform = FF_DWT97_INT;
if (c->csty & JPEG2000_CSTY_PREC) {
int i;
for (i = 0; i < c->nreslevels; i++) {
byte = bytestream2_get_byte(&s->g);
c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx
c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy
}
} else {
memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
}
return 0;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: libavcodec/jpeg2000dec.c in FFmpeg before 2.1 does not ensure the use of valid code-block dimension values, which allows remote attackers to cause a denial of service (out-of-bounds array access) or possibly have unspecified other impact via crafted JPEG2000 data.
Commit Message: jpeg2000: check log2_cblk dimensions
Fixes out of array access
Fixes Ticket2895
Found-by: Piotr Bandurski <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]> | Medium | 165,920 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: xsltCopyTextString(xsltTransformContextPtr ctxt, xmlNodePtr target,
const xmlChar *string, int noescape)
{
xmlNodePtr copy;
int len;
if (string == NULL)
return(NULL);
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_COPY_TEXT,xsltGenericDebug(xsltGenericDebugContext,
"xsltCopyTextString: copy text %s\n",
string));
#endif
/*
* Play safe and reset the merging mechanism for every new
* target node.
*/
if ((target == NULL) || (target->children == NULL)) {
ctxt->lasttext = NULL;
}
/* handle coalescing of text nodes here */
len = xmlStrlen(string);
if ((ctxt->type == XSLT_OUTPUT_XML) &&
(ctxt->style->cdataSection != NULL) &&
(target != NULL) &&
(target->type == XML_ELEMENT_NODE) &&
(((target->ns == NULL) &&
(xmlHashLookup2(ctxt->style->cdataSection,
target->name, NULL) != NULL)) ||
((target->ns != NULL) &&
(xmlHashLookup2(ctxt->style->cdataSection,
target->name, target->ns->href) != NULL))))
{
/*
* Process "cdata-section-elements".
*/
if ((target->last != NULL) &&
(target->last->type == XML_CDATA_SECTION_NODE))
{
return(xsltAddTextString(ctxt, target->last, string, len));
}
copy = xmlNewCDataBlock(ctxt->output, string, len);
} else if (noescape) {
/*
* Process "disable-output-escaping".
*/
if ((target != NULL) && (target->last != NULL) &&
(target->last->type == XML_TEXT_NODE) &&
(target->last->name == xmlStringTextNoenc))
{
return(xsltAddTextString(ctxt, target->last, string, len));
}
copy = xmlNewTextLen(string, len);
if (copy != NULL)
copy->name = xmlStringTextNoenc;
} else {
/*
* Default processing.
*/
if ((target != NULL) && (target->last != NULL) &&
(target->last->type == XML_TEXT_NODE) &&
(target->last->name == xmlStringText)) {
return(xsltAddTextString(ctxt, target->last, string, len));
}
copy = xmlNewTextLen(string, len);
}
if (copy != NULL) {
if (target != NULL)
copy = xsltAddChild(target, copy);
ctxt->lasttext = copy->content;
ctxt->lasttsize = len;
ctxt->lasttuse = len;
} else {
xsltTransformError(ctxt, NULL, target,
"xsltCopyTextString: text copy failed\n");
ctxt->lasttext = NULL;
}
return(copy);
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: numbers.c in libxslt before 1.1.29, as used in Google Chrome before 51.0.2704.63, mishandles namespace nodes, which allows remote attackers to cause a denial of service (out-of-bounds heap memory access) or possibly have unspecified other impact via a crafted document.
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338} | High | 173,323 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void TIFF_MetaHandler::ProcessXMP()
{
this->processedXMP = true; // Make sure we only come through here once.
bool found;
bool readOnly = ((this->parent->openFlags & kXMPFiles_OpenForUpdate) == 0);
if ( readOnly ) {
this->psirMgr = new PSIR_MemoryReader();
this->iptcMgr = new IPTC_Reader();
} else {
this->psirMgr = new PSIR_FileWriter();
this->iptcMgr = new IPTC_Writer(); // ! Parse it later.
}
TIFF_Manager & tiff = this->tiffMgr; // Give the compiler help in recognizing non-aliases.
PSIR_Manager & psir = *this->psirMgr;
IPTC_Manager & iptc = *this->iptcMgr;
TIFF_Manager::TagInfo psirInfo;
bool havePSIR = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_PSIR, &psirInfo );
if ( havePSIR ) { // ! Do the Photoshop 6 integration before other legacy analysis.
psir.ParseMemoryResources ( psirInfo.dataPtr, psirInfo.dataLen );
PSIR_Manager::ImgRsrcInfo buriedExif;
found = psir.GetImgRsrc ( kPSIR_Exif, &buriedExif );
if ( found ) {
tiff.IntegrateFromPShop6 ( buriedExif.dataPtr, buriedExif.dataLen );
if ( ! readOnly ) psir.DeleteImgRsrc ( kPSIR_Exif );
}
}
TIFF_Manager::TagInfo iptcInfo;
bool haveIPTC = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_IPTC, &iptcInfo ); // The TIFF IPTC tag.
int iptcDigestState = kDigestMatches;
if ( haveIPTC ) {
bool haveDigest = false;
PSIR_Manager::ImgRsrcInfo digestInfo;
if ( havePSIR ) haveDigest = psir.GetImgRsrc ( kPSIR_IPTCDigest, &digestInfo );
if ( digestInfo.dataLen != 16 ) haveDigest = false;
if ( ! haveDigest ) {
iptcDigestState = kDigestMissing;
} else {
iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, iptcInfo.dataLen, digestInfo.dataPtr );
if ( (iptcDigestState == kDigestDiffers) && (kTIFF_TypeSizes[iptcInfo.type] > 1) ) {
XMP_Uns8 * endPtr = (XMP_Uns8*)iptcInfo.dataPtr + iptcInfo.dataLen - 1;
XMP_Uns8 * minPtr = endPtr - kTIFF_TypeSizes[iptcInfo.type] + 1;
while ( (endPtr >= minPtr) && (*endPtr == 0) ) --endPtr;
iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, unpaddedLen, digestInfo.dataPtr );
}
}
}
XMP_OptionBits options = k2XMP_FileHadExif; // TIFF files are presumed to have Exif legacy.
if ( haveIPTC ) options |= k2XMP_FileHadIPTC;
if ( this->containsXMP ) options |= k2XMP_FileHadXMP;
bool haveXMP = false;
if ( ! this->xmpPacket.empty() ) {
XMP_Assert ( this->containsXMP );
XMP_StringPtr packetStr = this->xmpPacket.c_str();
XMP_StringLen packetLen = (XMP_StringLen)this->xmpPacket.size();
try {
this->xmpObj.ParseFromBuffer ( packetStr, packetLen );
} catch ( ... ) { /* Ignore parsing failures, someday we hope to get partial XMP back. */ }
haveXMP = true;
}
if ( haveIPTC && (! haveXMP) && (iptcDigestState == kDigestMatches) ) iptcDigestState = kDigestMissing;
bool parseIPTC = (iptcDigestState != kDigestMatches) || (! readOnly);
if ( parseIPTC ) iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen );
ImportPhotoData ( tiff, iptc, psir, iptcDigestState, &this->xmpObj, options );
this->containsXMP = true; // Assume we now have something in the XMP.
} // TIFF_MetaHandler::ProcessXMP
Vulnerability Type:
CWE ID: CWE-125
Summary: An issue was discovered in Exempi through 2.4.4. XMPFiles/source/FileHandlers/TIFF_Handler.cpp mishandles a case of a zero length, leading to a heap-based buffer over-read in the MD5Update() function in third-party/zuid/interfaces/MD5.cpp.
Commit Message: | Medium | 164,996 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static ssize_t clear_refs_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task;
char buffer[PROC_NUMBUF];
struct mm_struct *mm;
struct vm_area_struct *vma;
enum clear_refs_types type;
struct mmu_gather tlb;
int itype;
int rv;
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count))
return -EFAULT;
rv = kstrtoint(strstrip(buffer), 10, &itype);
if (rv < 0)
return rv;
type = (enum clear_refs_types)itype;
if (type < CLEAR_REFS_ALL || type >= CLEAR_REFS_LAST)
return -EINVAL;
task = get_proc_task(file_inode(file));
if (!task)
return -ESRCH;
mm = get_task_mm(task);
if (mm) {
struct mmu_notifier_range range;
struct clear_refs_private cp = {
.type = type,
};
struct mm_walk clear_refs_walk = {
.pmd_entry = clear_refs_pte_range,
.test_walk = clear_refs_test_walk,
.mm = mm,
.private = &cp,
};
if (type == CLEAR_REFS_MM_HIWATER_RSS) {
if (down_write_killable(&mm->mmap_sem)) {
count = -EINTR;
goto out_mm;
}
/*
* Writing 5 to /proc/pid/clear_refs resets the peak
* resident set size to this mm's current rss value.
*/
reset_mm_hiwater_rss(mm);
up_write(&mm->mmap_sem);
goto out_mm;
}
down_read(&mm->mmap_sem);
tlb_gather_mmu(&tlb, mm, 0, -1);
if (type == CLEAR_REFS_SOFT_DIRTY) {
for (vma = mm->mmap; vma; vma = vma->vm_next) {
if (!(vma->vm_flags & VM_SOFTDIRTY))
continue;
up_read(&mm->mmap_sem);
if (down_write_killable(&mm->mmap_sem)) {
count = -EINTR;
goto out_mm;
}
for (vma = mm->mmap; vma; vma = vma->vm_next) {
vma->vm_flags &= ~VM_SOFTDIRTY;
vma_set_page_prot(vma);
}
downgrade_write(&mm->mmap_sem);
break;
}
mmu_notifier_range_init(&range, mm, 0, -1UL);
mmu_notifier_invalidate_range_start(&range);
}
walk_page_range(0, mm->highest_vm_end, &clear_refs_walk);
if (type == CLEAR_REFS_SOFT_DIRTY)
mmu_notifier_invalidate_range_end(&range);
tlb_finish_mmu(&tlb, 0, -1);
up_read(&mm->mmap_sem);
out_mm:
mmput(mm);
}
put_task_struct(task);
return count;
}
Vulnerability Type: DoS +Info
CWE ID: CWE-362
Summary: The coredump implementation in the Linux kernel before 5.0.10 does not use locking or other mechanisms to prevent vma layout or vma flags changes while it runs, which allows local users to obtain sensitive information, cause a denial of service, or possibly have unspecified other impact by triggering a race condition with mmget_not_zero or get_task_mm calls. This is related to fs/userfaultfd.c, mm/mmap.c, fs/proc/task_mmu.c, and drivers/infiniband/core/uverbs_main.c.
Commit Message: coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping
The core dumping code has always run without holding the mmap_sem for
writing, despite that is the only way to ensure that the entire vma
layout will not change from under it. Only using some signal
serialization on the processes belonging to the mm is not nearly enough.
This was pointed out earlier. For example in Hugh's post from Jul 2017:
https://lkml.kernel.org/r/[email protected]
"Not strictly relevant here, but a related note: I was very surprised
to discover, only quite recently, how handle_mm_fault() may be called
without down_read(mmap_sem) - when core dumping. That seems a
misguided optimization to me, which would also be nice to correct"
In particular because the growsdown and growsup can move the
vm_start/vm_end the various loops the core dump does around the vma will
not be consistent if page faults can happen concurrently.
Pretty much all users calling mmget_not_zero()/get_task_mm() and then
taking the mmap_sem had the potential to introduce unexpected side
effects in the core dumping code.
Adding mmap_sem for writing around the ->core_dump invocation is a
viable long term fix, but it requires removing all copy user and page
faults and to replace them with get_dump_page() for all binary formats
which is not suitable as a short term fix.
For the time being this solution manually covers the places that can
confuse the core dump either by altering the vma layout or the vma flags
while it runs. Once ->core_dump runs under mmap_sem for writing the
function mmget_still_valid() can be dropped.
Allowing mmap_sem protected sections to run in parallel with the
coredump provides some minor parallelism advantage to the swapoff code
(which seems to be safe enough by never mangling any vma field and can
keep doing swapins in parallel to the core dumping) and to some other
corner case.
In order to facilitate the backporting I added "Fixes: 86039bd3b4e6"
however the side effect of this same race condition in /proc/pid/mem
should be reproducible since before 2.6.12-rc2 so I couldn't add any
other "Fixes:" because there's no hash beyond the git genesis commit.
Because find_extend_vma() is the only location outside of the process
context that could modify the "mm" structures under mmap_sem for
reading, by adding the mmget_still_valid() check to it, all other cases
that take the mmap_sem for reading don't need the new check after
mmget_not_zero()/get_task_mm(). The expand_stack() in page fault
context also doesn't need the new check, because all tasks under core
dumping are frozen.
Link: http://lkml.kernel.org/r/[email protected]
Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization")
Signed-off-by: Andrea Arcangeli <[email protected]>
Reported-by: Jann Horn <[email protected]>
Suggested-by: Oleg Nesterov <[email protected]>
Acked-by: Peter Xu <[email protected]>
Reviewed-by: Mike Rapoport <[email protected]>
Reviewed-by: Oleg Nesterov <[email protected]>
Reviewed-by: Jann Horn <[email protected]>
Acked-by: Jason Gunthorpe <[email protected]>
Acked-by: Michal Hocko <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]> | Medium | 169,685 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: png_do_read_interlace(png_structp png_ptr)
{
png_row_infop row_info = &(png_ptr->row_info);
png_bytep row = png_ptr->row_buf + 1;
int pass = png_ptr->pass;
png_uint_32 transformations = png_ptr->transformations;
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Offset to next interlace block */
PNG_CONST 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 + (png_size_t)((row_info->width - 1) >> 3);
png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
int sshift, dshift;
int s_start, s_end, s_inc;
int jstop = png_pass_inc[pass];
png_byte v;
png_uint_32 i;
int j;
#ifdef PNG_READ_PACKSWAP_SUPPORTED
if (transformations & PNG_PACKSWAP)
{
sshift = (int)((row_info->width + 7) & 0x07);
dshift = (int)((final_width + 7) & 0x07);
s_start = 7;
s_end = 0;
s_inc = -1;
}
else
#endif
{
sshift = 7 - (int)((row_info->width + 7) & 0x07);
dshift = 7 - (int)((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++)
{
*dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
*dp |= (png_byte)(v << dshift);
if (dshift == s_end)
{
dshift = s_start;
dp--;
}
else
dshift += s_inc;
}
if (sshift == s_end)
{
sshift = s_start;
sp--;
}
else
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);
int sshift, dshift;
int s_start, s_end, s_inc;
int jstop = png_pass_inc[pass];
png_uint_32 i;
#ifdef PNG_READ_PACKSWAP_SUPPORTED
if (transformations & PNG_PACKSWAP)
{
sshift = (int)(((row_info->width + 3) & 0x03) << 1);
dshift = (int)(((final_width + 3) & 0x03) << 1);
s_start = 6;
s_end = 0;
s_inc = -2;
}
else
#endif
{
sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
dshift = (int)((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++)
{
*dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
*dp |= (png_byte)(v << dshift);
if (dshift == s_end)
{
dshift = s_start;
dp--;
}
else
dshift += s_inc;
}
if (sshift == s_end)
{
sshift = s_start;
sp--;
}
else
sshift += s_inc;
}
break;
}
case 4:
{
png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
int sshift, dshift;
int s_start, s_end, s_inc;
png_uint_32 i;
int jstop = png_pass_inc[pass];
#ifdef PNG_READ_PACKSWAP_SUPPORTED
if (transformations & PNG_PACKSWAP)
{
sshift = (int)(((row_info->width + 1) & 0x01) << 2);
dshift = (int)(((final_width + 1) & 0x01) << 2);
s_start = 4;
s_end = 0;
s_inc = -4;
}
else
#endif
{
sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
dshift = (int)((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) & 0xf);
int j;
for (j = 0; j < jstop; j++)
{
*dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
*dp |= (png_byte)(v << dshift);
if (dshift == s_end)
{
dshift = s_start;
dp--;
}
else
dshift += s_inc;
}
if (sshift == s_end)
{
sshift = s_start;
sp--;
}
else
sshift += s_inc;
}
break;
}
default:
{
png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
png_bytep sp = row + (png_size_t)(row_info->width - 1)
* pixel_bytes;
png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
int jstop = png_pass_inc[pass];
png_uint_32 i;
for (i = 0; i < row_info->width; i++)
{
png_byte v[8];
int j;
png_memcpy(v, sp, pixel_bytes);
for (j = 0; j < jstop; j++)
{
png_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
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: Multiple buffer overflows in the (1) png_set_PLTE and (2) png_get_PLTE functions in libpng before 1.0.64, 1.1.x and 1.2.x before 1.2.54, 1.3.x and 1.4.x before 1.4.17, 1.5.x before 1.5.24, and 1.6.x before 1.6.19 allow remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a small bit-depth value in an IHDR (aka image header) chunk in a PNG image.
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} | Low | 172,172 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: OMX_ERRORTYPE omx_vdec::set_config(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_INDEXTYPE configIndex,
OMX_IN OMX_PTR configData)
{
(void) hComp;
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("Get Config in Invalid State");
return OMX_ErrorInvalidState;
}
OMX_ERRORTYPE ret = OMX_ErrorNone;
OMX_VIDEO_CONFIG_NALSIZE *pNal;
DEBUG_PRINT_LOW("Set Config Called");
if (configIndex == (OMX_INDEXTYPE)OMX_IndexVendorVideoExtraData) {
OMX_VENDOR_EXTRADATATYPE *config = (OMX_VENDOR_EXTRADATATYPE *) configData;
DEBUG_PRINT_LOW("Index OMX_IndexVendorVideoExtraData called");
if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.avc") ||
!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mvc")) {
DEBUG_PRINT_LOW("Index OMX_IndexVendorVideoExtraData AVC");
OMX_U32 extra_size;
nal_length = (config->pData[4] & 0x03) + 1;
extra_size = 0;
if (nal_length > 2) {
/* Presently we assume that only one SPS and one PPS in AvC1 Atom */
extra_size = (nal_length - 2) * 2;
}
OMX_U8 *pSrcBuf = (OMX_U8 *) (&config->pData[6]);
OMX_U8 *pDestBuf;
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize - 6 - 1 + extra_size;
m_vendor_config.pData = (OMX_U8 *) malloc(m_vendor_config.nDataSize);
OMX_U32 len;
OMX_U8 index = 0;
pDestBuf = m_vendor_config.pData;
DEBUG_PRINT_LOW("Rxd SPS+PPS nPortIndex[%u] len[%u] data[%p]",
(unsigned int)m_vendor_config.nPortIndex,
(unsigned int)m_vendor_config.nDataSize,
m_vendor_config.pData);
while (index < 2) {
uint8 *psize;
len = *pSrcBuf;
len = len << 8;
len |= *(pSrcBuf + 1);
psize = (uint8 *) & len;
memcpy(pDestBuf + nal_length, pSrcBuf + 2,len);
for (unsigned int i = 0; i < nal_length; i++) {
pDestBuf[i] = psize[nal_length - 1 - i];
}
pDestBuf += len + nal_length;
pSrcBuf += len + 2;
index++;
pSrcBuf++; // skip picture param set
len = 0;
}
} else if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg4") ||
!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg2")) {
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize;
m_vendor_config.pData = (OMX_U8 *) malloc((config->nDataSize));
memcpy(m_vendor_config.pData, config->pData,config->nDataSize);
} else if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.vc1")) {
if (m_vendor_config.pData) {
free(m_vendor_config.pData);
m_vendor_config.pData = NULL;
m_vendor_config.nDataSize = 0;
}
if (((*((OMX_U32 *) config->pData)) &
VC1_SP_MP_START_CODE_MASK) ==
VC1_SP_MP_START_CODE) {
DEBUG_PRINT_LOW("set_config - VC1 simple/main profile");
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize;
m_vendor_config.pData =
(OMX_U8 *) malloc(config->nDataSize);
memcpy(m_vendor_config.pData, config->pData,
config->nDataSize);
m_vc1_profile = VC1_SP_MP_RCV;
} else if (*((OMX_U32 *) config->pData) == VC1_AP_SEQ_START_CODE) {
DEBUG_PRINT_LOW("set_config - VC1 Advance profile");
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize;
m_vendor_config.pData =
(OMX_U8 *) malloc((config->nDataSize));
memcpy(m_vendor_config.pData, config->pData,
config->nDataSize);
m_vc1_profile = VC1_AP;
} else if ((config->nDataSize == VC1_STRUCT_C_LEN)) {
DEBUG_PRINT_LOW("set_config - VC1 Simple/Main profile struct C only");
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize;
m_vendor_config.pData = (OMX_U8*)malloc(config->nDataSize);
memcpy(m_vendor_config.pData,config->pData,config->nDataSize);
m_vc1_profile = VC1_SP_MP_RCV;
} else {
DEBUG_PRINT_LOW("set_config - Error: Unknown VC1 profile");
}
}
return ret;
} else if (configIndex == OMX_IndexConfigVideoNalSize) {
struct v4l2_control temp;
temp.id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT;
VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_NALSIZE);
pNal = reinterpret_cast < OMX_VIDEO_CONFIG_NALSIZE * >(configData);
switch (pNal->nNaluBytes) {
case 0:
temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_STARTCODES;
break;
case 2:
temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_TWO_BYTE_LENGTH;
break;
case 4:
temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_FOUR_BYTE_LENGTH;
break;
default:
return OMX_ErrorUnsupportedSetting;
}
if (!arbitrary_bytes) {
/* In arbitrary bytes mode, the assembler strips out nal size and replaces
* with start code, so only need to notify driver in frame by frame mode */
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &temp)) {
DEBUG_PRINT_ERROR("Failed to set V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT");
return OMX_ErrorHardware;
}
}
nal_length = pNal->nNaluBytes;
m_frame_parser.init_nal_length(nal_length);
DEBUG_PRINT_LOW("OMX_IndexConfigVideoNalSize called with Size %d", nal_length);
return ret;
} else if ((int)configIndex == (int)OMX_IndexVendorVideoFrameRate) {
OMX_VENDOR_VIDEOFRAMERATE *config = (OMX_VENDOR_VIDEOFRAMERATE *) configData;
DEBUG_PRINT_HIGH("Index OMX_IndexVendorVideoFrameRate %u", (unsigned int)config->nFps);
if (config->nPortIndex == OMX_CORE_INPUT_PORT_INDEX) {
if (config->bEnabled) {
if ((config->nFps >> 16) > 0) {
DEBUG_PRINT_HIGH("set_config: frame rate set by omx client : %u",
(unsigned int)config->nFps >> 16);
Q16ToFraction(config->nFps, drv_ctx.frame_rate.fps_numerator,
drv_ctx.frame_rate.fps_denominator);
if (!drv_ctx.frame_rate.fps_numerator) {
DEBUG_PRINT_ERROR("Numerator is zero setting to 30");
drv_ctx.frame_rate.fps_numerator = 30;
}
if (drv_ctx.frame_rate.fps_denominator) {
drv_ctx.frame_rate.fps_numerator = (int)
drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator;
}
drv_ctx.frame_rate.fps_denominator = 1;
frm_int = drv_ctx.frame_rate.fps_denominator * 1e6 /
drv_ctx.frame_rate.fps_numerator;
struct v4l2_outputparm oparm;
/*XXX: we're providing timing info as seconds per frame rather than frames
* per second.*/
oparm.timeperframe.numerator = drv_ctx.frame_rate.fps_denominator;
oparm.timeperframe.denominator = drv_ctx.frame_rate.fps_numerator;
struct v4l2_streamparm sparm;
sparm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
sparm.parm.output = oparm;
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_PARM, &sparm)) {
DEBUG_PRINT_ERROR("Unable to convey fps info to driver, \
performance might be affected");
ret = OMX_ErrorHardware;
}
client_set_fps = true;
} else {
DEBUG_PRINT_ERROR("Frame rate not supported.");
ret = OMX_ErrorUnsupportedSetting;
}
} else {
DEBUG_PRINT_HIGH("set_config: Disabled client's frame rate");
client_set_fps = false;
}
} else {
DEBUG_PRINT_ERROR(" Set_config: Bad Port idx %d",
(int)config->nPortIndex);
ret = OMX_ErrorBadPortIndex;
}
return ret;
} else if ((int)configIndex == (int)OMX_QcomIndexConfigPerfLevel) {
OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf =
(OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData;
struct v4l2_control control;
DEBUG_PRINT_LOW("Set perf level: %d", perf->ePerfLevel);
control.id = V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL;
switch (perf->ePerfLevel) {
case OMX_QCOM_PerfLevelNominal:
control.value = V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL;
break;
case OMX_QCOM_PerfLevelTurbo:
control.value = V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO;
break;
default:
ret = OMX_ErrorUnsupportedSetting;
break;
}
if (ret == OMX_ErrorNone) {
ret = (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control) < 0) ?
OMX_ErrorUnsupportedSetting : OMX_ErrorNone;
}
return ret;
} else if ((int)configIndex == (int)OMX_IndexConfigPriority) {
OMX_PARAM_U32TYPE *priority = (OMX_PARAM_U32TYPE *)configData;
DEBUG_PRINT_LOW("Set_config: priority %d", priority->nU32);
struct v4l2_control control;
control.id = V4L2_CID_MPEG_VIDC_VIDEO_PRIORITY;
if (priority->nU32 == 0)
control.value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_ENABLE;
else
control.value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_DISABLE;
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) {
DEBUG_PRINT_ERROR("Failed to set Priority");
ret = OMX_ErrorUnsupportedSetting;
}
return ret;
} else if ((int)configIndex == (int)OMX_IndexConfigOperatingRate) {
OMX_PARAM_U32TYPE *rate = (OMX_PARAM_U32TYPE *)configData;
DEBUG_PRINT_LOW("Set_config: operating-rate %u fps", rate->nU32 >> 16);
struct v4l2_control control;
control.id = V4L2_CID_MPEG_VIDC_VIDEO_OPERATING_RATE;
control.value = rate->nU32;
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) {
ret = errno == -EBUSY ? OMX_ErrorInsufficientResources :
OMX_ErrorUnsupportedSetting;
DEBUG_PRINT_ERROR("Failed to set operating rate %u fps (%s)",
rate->nU32 >> 16, errno == -EBUSY ? "HW Overload" : strerror(errno));
}
return ret;
}
return OMX_ErrorNotImplemented;
}
Vulnerability Type: +Priv
CWE ID: CWE-20
Summary: mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-06-01 mishandles pointers, which allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 27475409.
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: deprecate unused config OMX_IndexVendorVideoExtraData
This config (used to set header offline) is no longer used. Remove handling
this config since it uses non-process-safe ways to pass memory pointers.
Fixes: Security Vulnerability - Segfault in MediaServer (libOmxVdec problem #2)
Bug: 27475409
Change-Id: I7a535a3da485cbe83cf4605a05f9faf70dcca42f
| Medium | 173,797 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void OneClickSigninSyncStarter::UntrustedSigninConfirmed(
StartSyncMode response) {
if (response == UNDO_SYNC) {
CancelSigninAndDelete();
} else {
if (response == CONFIGURE_SYNC_FIRST)
start_mode_ = response;
SigninManager* signin = SigninManagerFactory::GetForProfile(profile_);
signin->CompletePendingSignin();
}
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: Google Chrome before 28.0.1500.71 does not properly determine the circumstances in which a renderer process can be considered a trusted process for sign-in and subsequent sync operations, which makes it easier for remote attackers to conduct phishing attacks via a crafted web site.
Commit Message: Display confirmation dialog for untrusted signins
BUG=252062
Review URL: https://chromiumcodereview.appspot.com/17482002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98 | Medium | 171,246 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static Image *ReadOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
Image
*alpha_image,
*color_image,
*image,
*jng_image;
ImageInfo
*alpha_image_info,
*color_image_info;
MagickBooleanType
logging;
ssize_t
y;
MagickBooleanType
status;
png_uint_32
jng_height,
jng_width;
png_byte
jng_color_type,
jng_image_sample_depth,
jng_image_compression_method,
jng_image_interlace_method,
jng_alpha_sample_depth,
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method;
register const Quantum
*s;
register ssize_t
i,
x;
register Quantum
*q;
register unsigned char
*p;
unsigned int
read_JSEP,
reading_idat;
size_t
length;
jng_alpha_compression_method=0;
jng_alpha_sample_depth=8;
jng_color_type=0;
jng_height=0;
jng_width=0;
alpha_image=(Image *) NULL;
color_image=(Image *) NULL;
alpha_image_info=(ImageInfo *) NULL;
color_image_info=(ImageInfo *) NULL;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneJNGImage()");
image=mng_info->image;
if (GetAuthenticPixelQueue(image) != (Quantum *) NULL)
{
/*
Allocate next image structure.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireNextImage()");
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
/*
Signature bytes have already been read.
*/
read_JSEP=MagickFalse;
reading_idat=MagickFalse;
for (;;)
{
char
type[MagickPathExtent];
unsigned char
*chunk;
unsigned int
count;
/*
Read a new JNG chunk.
*/
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
break;
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MagickPathExtent);
length=(size_t) ReadBlobMSBLong(image);
count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading JNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX || count == 0)
{
DestroyJNG(NULL,&color_image,&color_image_info,
&alpha_image,&alpha_image_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (length > GetBlobSize(image))
{
DestroyJNG(NULL,&color_image,&color_image_info,
&alpha_image,&alpha_image_info);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
for ( ; i < (ssize_t) length; i++)
chunk[i]='\0';
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
if (memcmp(type,mng_JHDR,4) == 0)
{
if (length == 16)
{
jng_width=(png_uint_32)mng_get_long(p);
jng_height=(png_uint_32)mng_get_long(&p[4]);
if ((jng_width == 0) || (jng_height == 0))
{
DestroyJNG(chunk,&color_image,&color_image_info,
&alpha_image,&alpha_image_info);
ThrowReaderException(CorruptImageError,
"NegativeOrZeroImageSize");
}
jng_color_type=p[8];
jng_image_sample_depth=p[9];
jng_image_compression_method=p[10];
jng_image_interlace_method=p[11];
image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :
NoInterlace;
jng_alpha_sample_depth=p[12];
jng_alpha_compression_method=p[13];
jng_alpha_filter_method=p[14];
jng_alpha_interlace_method=p[15];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_width: %16lu, jng_height: %16lu\n"
" jng_color_type: %16d, jng_image_sample_depth: %3d\n"
" jng_image_compression_method:%3d",
(unsigned long) jng_width, (unsigned long) jng_height,
jng_color_type, jng_image_sample_depth,
jng_image_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_image_interlace_method: %3d"
" jng_alpha_sample_depth: %3d",
jng_image_interlace_method,
jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_alpha_compression_method:%3d\n"
" jng_alpha_filter_method: %3d\n"
" jng_alpha_interlace_method: %3d",
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method);
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (jng_width > 65535 || jng_height > 65535 ||
(long) jng_width > GetMagickResourceLimit(WidthResource) ||
(long) jng_height > GetMagickResourceLimit(HeightResource))
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JNG width or height too large: (%lu x %lu)",
(long) jng_width, (long) jng_height);
DestroyJNG(chunk,&color_image,&color_image_info,
&alpha_image,&alpha_image_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
continue;
}
if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&
((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||
(memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))
{
/*
o create color_image
o open color_blob, attached to color_image
o if (color type has alpha)
open alpha_blob, attached to alpha_image
*/
color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));
if (color_image_info == (ImageInfo *) NULL)
{
DestroyJNG(chunk,&color_image,&color_image_info,
&alpha_image,&alpha_image_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
GetImageInfo(color_image_info);
color_image=AcquireImage(color_image_info,exception);
if (color_image == (Image *) NULL)
{
DestroyJNG(chunk,&color_image,&color_image_info,
&alpha_image,&alpha_image_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating color_blob.");
(void) AcquireUniqueFilename(color_image->filename);
status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
DestroyJNG(chunk,&color_image,&color_image_info,
&alpha_image,&alpha_image_info);
return(DestroyImageList(image));
}
if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
{
alpha_image_info=(ImageInfo *)
AcquireMagickMemory(sizeof(ImageInfo));
if (alpha_image_info == (ImageInfo *) NULL)
{
DestroyJNG(chunk,&color_image,&color_image_info,
&alpha_image,&alpha_image_info);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
GetImageInfo(alpha_image_info);
alpha_image=AcquireImage(alpha_image_info,exception);
if (alpha_image == (Image *) NULL)
{
DestroyJNG(chunk,&color_image,&color_image_info,
&alpha_image,&alpha_image_info);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating alpha_blob.");
(void) AcquireUniqueFilename(alpha_image->filename);
status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
DestroyJNG(chunk,&color_image,&color_image_info,
&alpha_image,&alpha_image_info);
return(DestroyImageList(image));
}
if (jng_alpha_compression_method == 0)
{
unsigned char
data[18];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing IHDR chunk to alpha_blob.");
(void) WriteBlob(alpha_image,8,(const unsigned char *)
"\211PNG\r\n\032\n");
(void) WriteBlobMSBULong(alpha_image,13L);
PNGType(data,mng_IHDR);
LogPNGChunk(logging,mng_IHDR,13L);
PNGLong(data+4,jng_width);
PNGLong(data+8,jng_height);
data[12]=jng_alpha_sample_depth;
data[13]=0; /* color_type gray */
data[14]=0; /* compression method 0 */
data[15]=0; /* filter_method 0 */
data[16]=0; /* interlace_method 0 */
(void) WriteBlob(alpha_image,17,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));
}
}
reading_idat=MagickTrue;
}
if (memcmp(type,mng_JDAT,4) == 0)
{
/* Copy chunk to color_image->blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAT chunk data to color_blob.");
if ((length != 0) && (color_image != (Image *) NULL))
(void) WriteBlob(color_image,length,chunk);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_IDAT,4) == 0)
{
png_byte
data[5];
/* Copy IDAT header and chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying IDAT chunk data to alpha_blob.");
(void) WriteBlobMSBULong(alpha_image,(size_t) length);
PNGType(data,mng_IDAT);
LogPNGChunk(logging,mng_IDAT,length);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlob(alpha_image,length,chunk);
(void) WriteBlobMSBULong(alpha_image,
crc32(crc32(0,data,4),chunk,(uInt) length));
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))
{
/* Copy chunk data to alpha_image->blob */
if ((alpha_image != NULL) && (image_info->ping == MagickFalse) &&
(length != 0))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAA chunk data to alpha_blob.");
(void) WriteBlob(alpha_image,length,chunk);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_JSEP,4) == 0)
{
read_JSEP=MagickTrue;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
if (length == 2)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=image->background_color.red;
image->background_color.blue=image->background_color.red;
}
if (length == 6)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=ScaleCharToQuantum(p[3]);
image->background_color.blue=ScaleCharToQuantum(p[5]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
image->gamma=((float) mng_get_long(p))*0.00001;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
if (length == 32)
{
image->chromaticity.white_point.x=0.00001*mng_get_long(p);
image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);
image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);
image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);
image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);
image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);
image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);
image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
if (length == 1)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_oFFs,4) == 0)
{
if (length > 8)
{
image->page.x=(ssize_t) mng_get_long(p);
image->page.y=(ssize_t) mng_get_long(&p[4]);
if ((int) p[8] != 0)
{
image->page.x/=10000;
image->page.y/=10000;
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
image->resolution.x=(double) mng_get_long(p);
image->resolution.y=(double) mng_get_long(&p[4]);
if ((int) p[8] == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->resolution.x=image->resolution.x/100.0f;
image->resolution.y=image->resolution.y/100.0f;
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if 0
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (memcmp(type,mng_IEND,4))
continue;
break;
}
/* IEND found */
/*
Finish up reading image data:
o read main image from color_blob.
o close color_blob.
o if (color_type has alpha)
if alpha_encoding is PNG
read secondary image from alpha_blob via ReadPNG
if alpha_encoding is JPEG
read secondary image from alpha_blob via ReadJPEG
o close alpha_blob.
o copy intensity of secondary image into
alpha samples of main image.
o destroy the secondary image.
*/
if (color_image_info == (ImageInfo *) NULL)
{
assert(color_image == (Image *) NULL);
assert(alpha_image == (Image *) NULL);
if (color_image != (Image *) NULL)
color_image=DestroyImageList(color_image);
return(DestroyImageList(image));
}
if (color_image == (Image *) NULL)
{
assert(alpha_image == (Image *) NULL);
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
}
(void) SeekBlob(color_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading jng_image from color_blob.");
assert(color_image_info != (ImageInfo *) NULL);
(void) FormatLocaleString(color_image_info->filename,MagickPathExtent,
"jpeg:%s",color_image->filename);
color_image_info->ping=MagickFalse; /* To do: avoid this */
jng_image=ReadImage(color_image_info,exception);
(void) RelinquishUniqueFileResource(color_image->filename);
color_image=DestroyImage(color_image);
color_image_info=DestroyImageInfo(color_image_info);
if (jng_image == (Image *) NULL)
{
DestroyJNG(NULL,NULL,NULL,&alpha_image,&alpha_image_info);
return(DestroyImageList(image));
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying jng_image pixels to main image.");
image->rows=jng_height;
image->columns=jng_width;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
{
DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image,
&alpha_image_info);
jng_image=DestroyImageList(jng_image);
return(DestroyImageList(image));
}
if ((image->columns != jng_image->columns) ||
(image->rows != jng_image->rows))
{
DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image,
&alpha_image_info);
jng_image=DestroyImageList(jng_image);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if ((s == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for (x=(ssize_t) image->columns; x != 0; x--)
{
SetPixelRed(image,GetPixelRed(jng_image,s),q);
SetPixelGreen(image,GetPixelGreen(jng_image,s),q);
SetPixelBlue(image,GetPixelBlue(jng_image,s),q);
q+=GetPixelChannels(image);
s+=GetPixelChannels(jng_image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
jng_image=DestroyImage(jng_image);
if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
{
if (jng_alpha_compression_method == 0)
{
png_byte
data[5];
(void) WriteBlobMSBULong(alpha_image,0x00000000L);
PNGType(data,mng_IEND);
LogPNGChunk(logging,mng_IEND,0L);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));
}
(void) CloseBlob(alpha_image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading alpha from alpha_blob.");
(void) FormatLocaleString(alpha_image_info->filename,MagickPathExtent,
"%s",alpha_image->filename);
jng_image=ReadImage(alpha_image_info,exception);
if (jng_image != (Image *) NULL)
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if ((s == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
if (image->alpha_trait != UndefinedPixelTrait)
for (x=(ssize_t) image->columns; x != 0; x--)
{
SetPixelAlpha(image,GetPixelRed(jng_image,s),q);
q+=GetPixelChannels(image);
s+=GetPixelChannels(jng_image);
}
else
for (x=(ssize_t) image->columns; x != 0; x--)
{
SetPixelAlpha(image,GetPixelRed(jng_image,s),q);
if (GetPixelAlpha(image,q) != OpaqueAlpha)
image->alpha_trait=BlendPixelTrait;
q+=GetPixelChannels(image);
s+=GetPixelChannels(jng_image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
(void) RelinquishUniqueFileResource(alpha_image->filename);
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
if (jng_image != (Image *) NULL)
jng_image=DestroyImage(jng_image);
}
/* Read the JNG image. */
if (mng_info->mng_type == 0)
{
mng_info->mng_width=jng_width;
mng_info->mng_height=jng_height;
}
if (image->page.width == 0 && image->page.height == 0)
{
image->page.width=jng_width;
image->page.height=jng_height;
}
if (image->page.x == 0 && image->page.y == 0)
{
image->page.x=mng_info->x_off[mng_info->object_id];
image->page.y=mng_info->y_off[mng_info->object_id];
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
mng_info->image_found++;
status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage()");
return(image);
}
Vulnerability Type:
CWE ID: CWE-772
Summary: ImageMagick 7.0.8-5 has a memory leak vulnerability in the function ReadOneJNGImage in coders/png.c.
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1201 | Medium | 169,044 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: DevToolsSession::DevToolsSession(DevToolsAgentHostImpl* agent_host,
DevToolsAgentHostClient* client)
: binding_(this),
agent_host_(agent_host),
client_(client),
process_(nullptr),
host_(nullptr),
dispatcher_(new protocol::UberDispatcher(this)),
weak_factory_(this) {
dispatcher_->setFallThroughForNotFound(true);
}
Vulnerability Type: Exec Code
CWE ID: CWE-20
Summary: An object lifetime issue in the developer tools network handler in Google Chrome prior to 66.0.3359.117 allowed a local attacker to execute arbitrary code via a crafted HTML page.
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} | Medium | 172,741 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: ClipPaintPropertyNode* ClipPaintPropertyNode::Root() {
DEFINE_STATIC_REF(
ClipPaintPropertyNode, root,
(ClipPaintPropertyNode::Create(
nullptr, State{TransformPaintPropertyNode::Root(),
FloatRoundedRect(LayoutRect::InfiniteIntRect())})));
return root;
}
Vulnerability Type: DoS
CWE ID:
Summary: Multiple unspecified vulnerabilities in Google Chrome before 47.0.2526.73 allow attackers to cause a denial of service or possibly have other impact via unknown vectors.
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} | Low | 171,832 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static void CopyTransportDIBHandleForMessage(
const TransportDIB::Handle& handle_in,
TransportDIB::Handle* handle_out) {
#if defined(OS_MACOSX)
if ((handle_out->fd = HANDLE_EINTR(dup(handle_in.fd))) < 0) {
PLOG(ERROR) << "dup()";
return;
}
handle_out->auto_close = true;
#else
*handle_out = handle_in;
#endif
}
Vulnerability Type: DoS
CWE ID:
Summary: Google Chrome before 20.0.1132.43 on Windows does not properly isolate sandboxed processes, which might allow remote attackers to cause a denial of service (process interference) via unspecified vectors.
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 | Low | 170,955 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
u32 val, ktime_t *abs_time, u32 bitset,
u32 __user *uaddr2)
{
struct hrtimer_sleeper timeout, *to = NULL;
struct rt_mutex_waiter rt_waiter;
struct rt_mutex *pi_mutex = NULL;
struct futex_hash_bucket *hb;
union futex_key key2 = FUTEX_KEY_INIT;
struct futex_q q = futex_q_init;
int res, ret;
if (!bitset)
return -EINVAL;
if (abs_time) {
to = &timeout;
hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
CLOCK_REALTIME : CLOCK_MONOTONIC,
HRTIMER_MODE_ABS);
hrtimer_init_sleeper(to, current);
hrtimer_set_expires_range_ns(&to->timer, *abs_time,
current->timer_slack_ns);
}
/*
* The waiter is allocated on our stack, manipulated by the requeue
* code while we sleep on uaddr.
*/
debug_rt_mutex_init_waiter(&rt_waiter);
rt_waiter.task = NULL;
ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
if (unlikely(ret != 0))
goto out;
q.bitset = bitset;
q.rt_waiter = &rt_waiter;
q.requeue_pi_key = &key2;
/*
* Prepare to wait on uaddr. On success, increments q.key (key1) ref
* count.
*/
ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
if (ret)
goto out_key2;
/* Queue the futex_q, drop the hb lock, wait for wakeup. */
futex_wait_queue_me(hb, &q, to);
spin_lock(&hb->lock);
ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to);
spin_unlock(&hb->lock);
if (ret)
goto out_put_keys;
/*
* In order for us to be here, we know our q.key == key2, and since
* we took the hb->lock above, we also know that futex_requeue() has
* completed and we no longer have to concern ourselves with a wakeup
* race with the atomic proxy lock acquisition by the requeue code. The
* futex_requeue dropped our key1 reference and incremented our key2
* reference count.
*/
/* Check if the requeue code acquired the second futex for us. */
if (!q.rt_waiter) {
/*
* Got the lock. We might not be the anticipated owner if we
* did a lock-steal - fix up the PI-state in that case.
*/
if (q.pi_state && (q.pi_state->owner != current)) {
spin_lock(q.lock_ptr);
ret = fixup_pi_state_owner(uaddr2, &q, current);
spin_unlock(q.lock_ptr);
}
} else {
/*
* We have been woken up by futex_unlock_pi(), a timeout, or a
* signal. futex_unlock_pi() will not destroy the lock_ptr nor
* the pi_state.
*/
WARN_ON(!q.pi_state);
pi_mutex = &q.pi_state->pi_mutex;
ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1);
debug_rt_mutex_free_waiter(&rt_waiter);
spin_lock(q.lock_ptr);
/*
* Fixup the pi_state owner and possibly acquire the lock if we
* haven't already.
*/
res = fixup_owner(uaddr2, &q, !ret);
/*
* If fixup_owner() returned an error, proprogate that. If it
* acquired the lock, clear -ETIMEDOUT or -EINTR.
*/
if (res)
ret = (res < 0) ? res : 0;
/* Unqueue and drop the lock. */
unqueue_me_pi(&q);
}
/*
* If fixup_pi_state_owner() faulted and was unable to handle the
* fault, unlock the rt_mutex and return the fault to userspace.
*/
if (ret == -EFAULT) {
if (pi_mutex && rt_mutex_owner(pi_mutex) == current)
rt_mutex_unlock(pi_mutex);
} else if (ret == -EINTR) {
/*
* We've already been requeued, but cannot restart by calling
* futex_lock_pi() directly. We could restart this syscall, but
* it would detect that the user space "val" changed and return
* -EWOULDBLOCK. Save the overhead of the restart and return
* -EWOULDBLOCK directly.
*/
ret = -EWOULDBLOCK;
}
out_put_keys:
put_futex_key(&q.key);
out_key2:
put_futex_key(&key2);
out:
if (to) {
hrtimer_cancel(&to->timer);
destroy_hrtimer_on_stack(&to->timer);
}
return ret;
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: The futex_wait_requeue_pi function in kernel/futex.c in the Linux kernel before 3.5.1 does not ensure that calls have two different futex addresses, which allows local users to cause a denial of service (NULL pointer dereference and system crash) or possibly have unspecified other impact via a crafted FUTEX_WAIT_REQUEUE_PI command.
Commit Message: futex: Forbid uaddr == uaddr2 in futex_wait_requeue_pi()
If uaddr == uaddr2, then we have broken the rule of only requeueing
from a non-pi futex to a pi futex with this call. If we attempt this,
as the trinity test suite manages to do, we miss early wakeups as
q.key is equal to key2 (because they are the same uaddr). We will then
attempt to dereference the pi_mutex (which would exist had the futex_q
been properly requeued to a pi futex) and trigger a NULL pointer
dereference.
Signed-off-by: Darren Hart <[email protected]>
Cc: Dave Jones <[email protected]>
Cc: [email protected]
Link: http://lkml.kernel.org/r/ad82bfe7f7d130247fbe2b5b4275654807774227.1342809673.git.dvhart@linux.intel.com
Signed-off-by: Thomas Gleixner <[email protected]> | Low | 166,548 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,
int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,
int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,
uint_fast32_t inmem)
{
jas_image_cmpt_t *cmpt;
size_t size;
cmpt = 0;
if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {
goto error;
}
if (!jas_safe_intfast32_add(tlx, width, 0) ||
!jas_safe_intfast32_add(tly, height, 0)) {
goto error;
}
if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
goto error;
}
cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
cmpt->tlx_ = tlx;
cmpt->tly_ = tly;
cmpt->hstep_ = hstep;
cmpt->vstep_ = vstep;
cmpt->width_ = width;
cmpt->height_ = height;
cmpt->prec_ = depth;
cmpt->sgnd_ = sgnd;
cmpt->stream_ = 0;
cmpt->cps_ = (depth + 7) / 8;
if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) ||
!jas_safe_size_mul(size, cmpt->cps_, &size)) {
goto error;
}
cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) :
jas_stream_tmpfile();
if (!cmpt->stream_) {
goto error;
}
/* Zero the component data. This isn't necessary, but it is
convenient for debugging purposes. */
/* Note: conversion of size - 1 to long can overflow */
if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
jas_stream_putc(cmpt->stream_, 0) == EOF ||
jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
goto error;
}
return cmpt;
error:
if (cmpt) {
jas_image_cmpt_destroy(cmpt);
}
return 0;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-190
Summary: Multiple integer overflows in the (1) jas_realloc function in base/jas_malloc.c and (2) mem_resize function in base/jas_stream.c in JasPer before 1.900.22 allow remote attackers to cause a denial of service via a crafted image, which triggers use after free vulnerabilities.
Commit Message: Made some changes to the I/O stream library for memory streams.
There were a number of potential problems due to the possibility
of integer overflow.
Changed some integral types to the larger types size_t or ssize_t.
For example, the function mem_resize now takes the buffer size parameter
as a size_t.
Added a new function jas_stream_memopen2, which takes a
buffer size specified as a size_t instead of an int.
This can be used in jas_image_cmpt_create to avoid potential
overflow problems.
Added a new function jas_deprecated to warn about reliance on
deprecated library behavior. | Medium | 168,744 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
EAS_PCM *pInputBuffer;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I32 numSamples;
#if (NUM_OUTPUT_CHANNELS == 2)
EAS_I32 gainLeft, gainRight;
#endif
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pMixBuffer = pWTIntFrame->pMixBuffer;
pInputBuffer = pWTIntFrame->pAudioBuffer;
/*lint -e{703} <avoid multiply for performance>*/
gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
/*lint -e{703} <avoid multiply for performance>*/
gain = pWTIntFrame->prevGain << 16;
#if (NUM_OUTPUT_CHANNELS == 2)
gainLeft = pWTVoice->gainLeft;
gainRight = pWTVoice->gainRight;
#endif
while (numSamples--) {
/* incremental gain step to prevent zipper noise */
tmp0 = *pInputBuffer++;
gain += gainIncrement;
/*lint -e{704} <avoid divide>*/
tmp2 = gain >> 16;
/* scale sample by gain */
tmp2 *= tmp0;
/* stereo output */
#if (NUM_OUTPUT_CHANNELS == 2)
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> 14;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* left channel */
tmp0 = tmp2 * gainLeft;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* right channel */
tmp0 = tmp2 * gainRight;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* mono output */
#else
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1);
tmp1 += tmp2;
*pMixBuffer++ = tmp1;
#endif
}
}
Vulnerability Type: DoS Exec Code Overflow Mem. Corr.
CWE ID: CWE-119
Summary: Sonivox in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-04-01 does not check for a negative number of samples, which allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to arm-wt-22k/lib_src/eas_wtengine.c and arm-wt-22k/lib_src/eas_wtsynth.c, aka internal bug 26366256.
Commit Message: Sonivox: add SafetyNet log.
Bug: 26366256
Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0
| Low | 174,606 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: l2tp_avp_print(netdissect_options *ndo, const u_char *dat, int length)
{
u_int len;
const uint16_t *ptr = (const uint16_t *)dat;
uint16_t attr_type;
int hidden = FALSE;
if (length <= 0) {
return;
}
ND_PRINT((ndo, " "));
ND_TCHECK(*ptr); /* Flags & Length */
len = EXTRACT_16BITS(ptr) & L2TP_AVP_HDR_LEN_MASK;
/* If it is not long enough to contain the header, we'll give up. */
if (len < 6)
goto trunc;
/* If it goes past the end of the remaining length of the packet,
we'll give up. */
if (len > (u_int)length)
goto trunc;
/* If it goes past the end of the remaining length of the captured
data, we'll give up. */
ND_TCHECK2(*ptr, len);
/* After this point, no need to worry about truncation */
if (EXTRACT_16BITS(ptr) & L2TP_AVP_HDR_FLAG_MANDATORY) {
ND_PRINT((ndo, "*"));
}
if (EXTRACT_16BITS(ptr) & L2TP_AVP_HDR_FLAG_HIDDEN) {
hidden = TRUE;
ND_PRINT((ndo, "?"));
}
ptr++;
if (EXTRACT_16BITS(ptr)) {
/* Vendor Specific Attribute */
ND_PRINT((ndo, "VENDOR%04x:", EXTRACT_16BITS(ptr))); ptr++;
ND_PRINT((ndo, "ATTR%04x", EXTRACT_16BITS(ptr))); ptr++;
ND_PRINT((ndo, "("));
print_octets(ndo, (const u_char *)ptr, len-6);
ND_PRINT((ndo, ")"));
} else {
/* IETF-defined Attributes */
ptr++;
attr_type = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "%s", tok2str(l2tp_avp2str, "AVP-#%u", attr_type)));
ND_PRINT((ndo, "("));
if (hidden) {
ND_PRINT((ndo, "???"));
} else {
switch (attr_type) {
case L2TP_AVP_MSGTYPE:
l2tp_msgtype_print(ndo, (const u_char *)ptr);
break;
case L2TP_AVP_RESULT_CODE:
l2tp_result_code_print(ndo, (const u_char *)ptr, len-6);
break;
case L2TP_AVP_PROTO_VER:
l2tp_proto_ver_print(ndo, ptr);
break;
case L2TP_AVP_FRAMING_CAP:
l2tp_framing_cap_print(ndo, (const u_char *)ptr);
break;
case L2TP_AVP_BEARER_CAP:
l2tp_bearer_cap_print(ndo, (const u_char *)ptr);
break;
case L2TP_AVP_TIE_BREAKER:
print_octets(ndo, (const u_char *)ptr, 8);
break;
case L2TP_AVP_FIRM_VER:
case L2TP_AVP_ASSND_TUN_ID:
case L2TP_AVP_RECV_WIN_SIZE:
case L2TP_AVP_ASSND_SESS_ID:
print_16bits_val(ndo, ptr);
break;
case L2TP_AVP_HOST_NAME:
case L2TP_AVP_VENDOR_NAME:
case L2TP_AVP_CALLING_NUMBER:
case L2TP_AVP_CALLED_NUMBER:
case L2TP_AVP_SUB_ADDRESS:
case L2TP_AVP_PROXY_AUTH_NAME:
case L2TP_AVP_PRIVATE_GRP_ID:
print_string(ndo, (const u_char *)ptr, len-6);
break;
case L2TP_AVP_CHALLENGE:
case L2TP_AVP_INI_RECV_LCP:
case L2TP_AVP_LAST_SENT_LCP:
case L2TP_AVP_LAST_RECV_LCP:
case L2TP_AVP_PROXY_AUTH_CHAL:
case L2TP_AVP_PROXY_AUTH_RESP:
case L2TP_AVP_RANDOM_VECTOR:
print_octets(ndo, (const u_char *)ptr, len-6);
break;
case L2TP_AVP_Q931_CC:
l2tp_q931_cc_print(ndo, (const u_char *)ptr, len-6);
break;
case L2TP_AVP_CHALLENGE_RESP:
print_octets(ndo, (const u_char *)ptr, 16);
break;
case L2TP_AVP_CALL_SER_NUM:
case L2TP_AVP_MINIMUM_BPS:
case L2TP_AVP_MAXIMUM_BPS:
case L2TP_AVP_TX_CONN_SPEED:
case L2TP_AVP_PHY_CHANNEL_ID:
case L2TP_AVP_RX_CONN_SPEED:
print_32bits_val(ndo, (const uint32_t *)ptr);
break;
case L2TP_AVP_BEARER_TYPE:
l2tp_bearer_type_print(ndo, (const u_char *)ptr);
break;
case L2TP_AVP_FRAMING_TYPE:
l2tp_framing_type_print(ndo, (const u_char *)ptr);
break;
case L2TP_AVP_PACKET_PROC_DELAY:
l2tp_packet_proc_delay_print(ndo);
break;
case L2TP_AVP_PROXY_AUTH_TYPE:
l2tp_proxy_auth_type_print(ndo, (const u_char *)ptr);
break;
case L2TP_AVP_PROXY_AUTH_ID:
l2tp_proxy_auth_id_print(ndo, (const u_char *)ptr);
break;
case L2TP_AVP_CALL_ERRORS:
l2tp_call_errors_print(ndo, (const u_char *)ptr);
break;
case L2TP_AVP_ACCM:
l2tp_accm_print(ndo, (const u_char *)ptr);
break;
case L2TP_AVP_SEQ_REQUIRED:
break; /* No Attribute Value */
case L2TP_AVP_PPP_DISCON_CC:
l2tp_ppp_discon_cc_print(ndo, (const u_char *)ptr, len-6);
break;
default:
break;
}
}
ND_PRINT((ndo, ")"));
}
l2tp_avp_print(ndo, dat+len, length-len);
return;
trunc:
ND_PRINT((ndo, "|..."));
}
Vulnerability Type:
CWE ID: CWE-125
Summary: The L2TP parser in tcpdump before 4.9.2 has a buffer over-read in print-l2tp.c, several functions.
Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s). | Low | 167,890 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: OVS_REQUIRES(ofproto_mutex)
{
const struct rule_actions *actions = rule_get_actions(rule);
/* A rule may not be reinserted. */
ovs_assert(rule->state == RULE_INITIALIZED);
if (rule->hard_timeout || rule->idle_timeout) {
ovs_list_insert(&ofproto->expirable, &rule->expirable);
}
cookies_insert(ofproto, rule);
eviction_group_add_rule(rule);
if (actions->has_meter) {
meter_insert_rule(rule);
}
if (actions->has_groups) {
const struct ofpact_group *a;
OFPACT_FOR_EACH_TYPE_FLATTENED (a, GROUP, actions->ofpacts,
actions->ofpacts_len) {
struct ofgroup *group;
group = ofproto_group_lookup(ofproto, a->group_id, OVS_VERSION_MAX,
false);
ovs_assert(group != NULL);
group_add_rule(group, rule);
}
}
rule->state = RULE_INSERTED;
}
Vulnerability Type:
CWE ID: CWE-617
Summary: An issue was discovered in Open vSwitch (OvS) 2.7.x through 2.7.6, affecting ofproto_rule_insert__ in ofproto/ofproto.c. During bundle commit, flows that are added in a bundle are applied to ofproto in order. If a flow cannot be added (e.g., the flow action is a go-to for a group id that does not exist), OvS tries to revert back all previous flows that were successfully applied from the same bundle. This is possible since OvS maintains list of old flows that were replaced by flows from the bundle. While reinserting old flows, OvS has an assertion failure due to a check on rule state != RULE_INITIALIZED. This would work for new flows, but for an old flow the rule state is RULE_REMOVED. The assertion failure causes an OvS crash.
Commit Message: ofproto: Fix OVS crash when reverting old flows in bundle commit
During bundle commit flows which are added in bundle are applied
to ofproto in-order. In case if a flow cannot be added (e.g. flow
action is go-to group id which does not exist), OVS tries to
revert back all previous flows which were successfully applied
from the same bundle. This is possible since OVS maintains list
of old flows which were replaced by flows from the bundle.
While reinserting old flows ovs asserts due to check on rule
state != RULE_INITIALIZED. This will work only for new flows, but
for old flow the rule state will be RULE_REMOVED. This is causing
an assert and OVS crash.
The ovs assert check should be modified to != RULE_INSERTED to prevent
any existing rule being re-inserted and allow new rules and old rules
(in case of revert) to get inserted.
Here is an example to trigger the assert:
$ ovs-vsctl add-br br-test -- set Bridge br-test datapath_type=netdev
$ cat flows.txt
flow add table=1,priority=0,in_port=2,actions=NORMAL
flow add table=1,priority=0,in_port=3,actions=NORMAL
$ ovs-ofctl dump-flows -OOpenflow13 br-test
cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=2 actions=NORMAL
cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=3 actions=NORMAL
$ cat flow-modify.txt
flow modify table=1,priority=0,in_port=2,actions=drop
flow modify table=1,priority=0,in_port=3,actions=group:10
$ ovs-ofctl bundle br-test flow-modify.txt -OOpenflow13
First flow rule will be modified since it is a valid rule. However second
rule is invalid since no group with id 10 exists. Bundle commit tries to
revert (insert) the first rule to old flow which results in ovs_assert at
ofproto_rule_insert__() since old rule->state = RULE_REMOVED.
Signed-off-by: Vishal Deep Ajmera <[email protected]>
Signed-off-by: Ben Pfaff <[email protected]> | Low | 169,024 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: grub_disk_read (grub_disk_t disk, grub_disk_addr_t sector,
grub_off_t offset, grub_size_t size, void *buf)
{
char *tmp_buf;
unsigned real_offset;
/* First of all, check if the region is within the disk. */
if (grub_disk_adjust_range (disk, §or, &offset, size) != GRUB_ERR_NONE)
{
grub_error_push ();
grub_dprintf ("disk", "Read out of range: sector 0x%llx (%s).\n",
(unsigned long long) sector, grub_errmsg);
grub_error_pop ();
return grub_errno;
}
real_offset = offset;
/* Allocate a temporary buffer. */
tmp_buf = grub_malloc (GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS);
if (! tmp_buf)
return grub_errno;
/* Until SIZE is zero... */
while (size)
{
char *data;
grub_disk_addr_t start_sector;
grub_size_t len;
grub_size_t pos;
/* For reading bulk data. */
start_sector = sector & ~(GRUB_DISK_CACHE_SIZE - 1);
pos = (sector - start_sector) << GRUB_DISK_SECTOR_BITS;
len = ((GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS)
- pos - real_offset);
if (len > size)
len = size;
/* Fetch the cache. */
data = grub_disk_cache_fetch (disk->dev->id, disk->id, start_sector);
if (data)
{
/* Just copy it! */
if (buf)
grub_memcpy (buf, data + pos + real_offset, len);
grub_disk_cache_unlock (disk->dev->id, disk->id, start_sector);
}
else
{
/* Otherwise read data from the disk actually. */
if (start_sector + GRUB_DISK_CACHE_SIZE > disk->total_sectors
|| (disk->dev->read) (disk, start_sector,
GRUB_DISK_CACHE_SIZE, tmp_buf)
!= GRUB_ERR_NONE)
{
/* Uggh... Failed. Instead, just read necessary data. */
unsigned num;
char *p;
grub_errno = GRUB_ERR_NONE;
num = ((size + real_offset + GRUB_DISK_SECTOR_SIZE - 1)
>> GRUB_DISK_SECTOR_BITS);
p = grub_realloc (tmp_buf, num << GRUB_DISK_SECTOR_BITS);
if (!p)
goto finish;
tmp_buf = p;
if ((disk->dev->read) (disk, sector, num, tmp_buf))
{
grub_error_push ();
grub_dprintf ("disk", "%s read failed\n", disk->name);
grub_error_pop ();
goto finish;
}
if (buf)
grub_memcpy (buf, tmp_buf + real_offset, size);
/* Call the read hook, if any. */
if (disk->read_hook)
while (size)
{
grub_size_t to_read;
to_read = size;
if (real_offset + to_read > GRUB_DISK_SECTOR_SIZE)
to_read = GRUB_DISK_SECTOR_SIZE - real_offset;
(disk->read_hook) (sector, real_offset,
to_read, disk->closure);
if (grub_errno != GRUB_ERR_NONE)
goto finish;
sector++;
size -= to_read;
real_offset = 0;
}
/* This must be the end. */
goto finish;
}
/* Copy it and store it in the disk cache. */
if (buf)
grub_memcpy (buf, tmp_buf + pos + real_offset, len);
grub_disk_cache_store (disk->dev->id, disk->id,
start_sector, tmp_buf);
}
/* Call the read hook, if any. */
if (disk->read_hook)
{
grub_disk_addr_t s = sector;
grub_size_t l = len;
while (l)
{
(disk->read_hook) (s, real_offset,
((l > GRUB_DISK_SECTOR_SIZE)
? GRUB_DISK_SECTOR_SIZE
: l), disk->closure);
if (l < GRUB_DISK_SECTOR_SIZE - real_offset)
break;
s++;
l -= GRUB_DISK_SECTOR_SIZE - real_offset;
real_offset = 0;
}
}
sector = start_sector + GRUB_DISK_CACHE_SIZE;
if (buf)
buf = (char *) buf + len;
size -= len;
real_offset = 0;
}
finish:
grub_free (tmp_buf);
return grub_errno;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The grub_memmove function in shlr/grub/kern/misc.c in radare2 1.5.0 allows remote attackers to cause a denial of service (heap-based buffer overflow and application crash) or possibly have unspecified other impact via a crafted binary file, possibly related to a read overflow in the grub_disk_read_small_real function in kern/disk.c in GNU GRUB 2.02.
Commit Message: Fix r2_hbo_grub_memmove ext2 crash | Medium | 168,058 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: bool asn1_write_LDAPString(struct asn1_data *data, const char *s)
{
asn1_write(data, s, strlen(s));
return !data->has_error;
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: The LDAP server in the AD domain controller in Samba 4.x before 4.1.22 does not check return values to ensure successful ASN.1 memory allocation, which allows remote attackers to cause a denial of service (memory consumption and daemon crash) via crafted packets.
Commit Message: | Low | 164,590 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: BufferMeta(const sp<IMemory> &mem, OMX_U32 portIndex, bool is_backup = false)
: mMem(mem),
mIsBackup(is_backup),
mPortIndex(portIndex) {
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: An information disclosure vulnerability in libstagefright in Mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, 6.x before 2016-11-01, and 7.0 before 2016-11-01 could enable a local malicious application to access data outside of its permission levels. This issue is rated as Moderate because it could be used to access sensitive data without permission. Android ID: A-29422020.
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
| Medium | 174,124 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: std::string ChromeOSGetKeyboardOverlayId(const std::string& input_method_id) {
for (size_t i = 0; i < arraysize(kKeyboardOverlayMap); ++i) {
if (kKeyboardOverlayMap[i].input_method_id == input_method_id) {
return kKeyboardOverlayMap[i].keyboard_overlay_id;
}
}
return "";
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Google Chrome before 13.0.782.107 does not properly handle nested functions in PDF documents, which allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted document.
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 | Low | 170,522 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void TypingCommand::insertText(Document& document,
const String& text,
Options options,
TextCompositionType composition,
const bool isIncrementalInsertion) {
LocalFrame* frame = document.frame();
DCHECK(frame);
if (!text.isEmpty())
document.frame()->spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
insertText(document, text,
frame->selection().computeVisibleSelectionInDOMTreeDeprecated(),
options, composition, isIncrementalInsertion);
}
Vulnerability Type: DoS
CWE ID:
Summary: Use-after-free vulnerability in Blink, as used in Google Chrome before 41.0.2272.76, allows remote attackers to cause a denial of service or possibly have unspecified other impact by leveraging incorrect ordering of operations in the Web SQL Database thread relative to Blink's main thread, related to the shutdown function in web/WebKit.cpp.
Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection
This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree|
instead of |VisibleSelection| to reduce usage of |VisibleSelection| for
improving code health.
BUG=657237
TEST=n/a
Review-Url: https://codereview.chromium.org/2733183002
Cr-Commit-Position: refs/heads/master@{#455368} | Low | 172,031 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: virtual ~InputMethodLibraryImpl() {
}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Google Chrome before 13.0.782.107 does not properly handle nested functions in PDF documents, which allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted document.
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 | Low | 170,516 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: init_copy(mrb_state *mrb, mrb_value dest, mrb_value obj)
{
switch (mrb_type(obj)) {
case MRB_TT_CLASS:
case MRB_TT_MODULE:
copy_class(mrb, dest, obj);
mrb_iv_copy(mrb, dest, obj);
mrb_iv_remove(mrb, dest, mrb_intern_lit(mrb, "__classname__"));
break;
case MRB_TT_OBJECT:
case MRB_TT_SCLASS:
case MRB_TT_HASH:
case MRB_TT_DATA:
case MRB_TT_EXCEPTION:
mrb_iv_copy(mrb, dest, obj);
break;
case MRB_TT_ISTRUCT:
mrb_istruct_copy(dest, obj);
break;
default:
break;
}
mrb_funcall(mrb, dest, "initialize_copy", 1, obj);
}
Vulnerability Type: DoS
CWE ID: CWE-824
Summary: The init_copy function in kernel.c in mruby 1.4.1 makes initialize_copy calls for TT_ICLASS objects, which allows attackers to cause a denial of service (mrb_hash_keys uninitialized pointer and application crash) or possibly have unspecified other impact.
Commit Message: Should not call `initialize_copy` for `TT_ICLASS`; fix #4027
Since `TT_ICLASS` is a internal object that should never be revealed
to Ruby world. | Low | 169,206 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void file_sb_list_del(struct file *file)
{
if (!list_empty(&file->f_u.fu_list)) {
lg_local_lock_cpu(&files_lglock, file_list_cpu(file));
list_del_init(&file->f_u.fu_list);
lg_local_unlock_cpu(&files_lglock, file_list_cpu(file));
}
}
Vulnerability Type: DoS
CWE ID: CWE-17
Summary: The filesystem implementation in the Linux kernel before 3.13 performs certain operations on lists of files with an inappropriate locking approach, which allows local users to cause a denial of service (soft lockup or system crash) via unspecified use of Asynchronous I/O (AIO) operations.
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]> | Low | 166,799 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void PermissionsRequestFunction::InstallUIAbort(bool user_initiated) {
results_ = Request::Results::Create(false);
SendResponse(true);
Release(); // Balanced in RunImpl().
}
Vulnerability Type:
CWE ID: CWE-264
Summary: The extension functionality in Google Chrome before 26.0.1410.43 does not verify that use of the permissions API is consistent with file permissions, which has unspecified impact and attack vectors.
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 | Low | 171,441 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static int crypto_rng_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_rng *rng = __crypto_rng_cast(tfm);
struct rng_alg *alg = crypto_rng_alg(rng);
struct old_rng_alg *oalg = crypto_old_rng_alg(rng);
if (oalg->rng_make_random) {
rng->generate = generate;
rng->seed = rngapi_reset;
rng->seedsize = oalg->seedsize;
return 0;
}
rng->generate = alg->generate;
rng->seed = alg->seed;
rng->seedsize = alg->seedsize;
return 0;
}
Vulnerability Type: DoS
CWE ID: CWE-476
Summary: The rngapi_reset function in crypto/rng.c in the Linux kernel before 4.2 allows attackers to cause a denial of service (NULL pointer dereference).
Commit Message: crypto: rng - Remove old low-level rng interface
Now that all rng implementations have switched over to the new
interface, we can remove the old low-level interface.
Signed-off-by: Herbert Xu <[email protected]> | Low | 167,731 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: bool GDataCache::CreateCacheDirectories(
const std::vector<FilePath>& paths_to_create) {
bool success = true;
for (size_t i = 0; i < paths_to_create.size(); ++i) {
if (file_util::DirectoryExists(paths_to_create[i]))
continue;
if (!file_util::CreateDirectory(paths_to_create[i])) {
success = false;
PLOG(ERROR) << "Error creating directory " << paths_to_create[i].value();
} else {
DVLOG(1) << "Created directory " << paths_to_create[i].value();
}
}
return success;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The PDF functionality in Google Chrome before 22.0.1229.79 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors that trigger out-of-bounds write operations.
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 | Medium | 170,861 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static int csnmp_read_table(host_definition_t *host, data_definition_t *data) {
struct snmp_pdu *req;
struct snmp_pdu *res = NULL;
struct variable_list *vb;
const data_set_t *ds;
size_t oid_list_len = data->values_len + 1;
/* Holds the last OID returned by the device. We use this in the GETNEXT
* request to proceed. */
oid_t oid_list[oid_list_len];
/* Set to false when an OID has left its subtree so we don't re-request it
* again. */
_Bool oid_list_todo[oid_list_len];
int status;
size_t i;
/* `value_list_head' and `value_list_tail' implement a linked list for each
* value. `instance_list_head' and `instance_list_tail' implement a linked
* list of
* instance names. This is used to jump gaps in the table. */
csnmp_list_instances_t *instance_list_head;
csnmp_list_instances_t *instance_list_tail;
csnmp_table_values_t **value_list_head;
csnmp_table_values_t **value_list_tail;
DEBUG("snmp plugin: csnmp_read_table (host = %s, data = %s)", host->name,
data->name);
if (host->sess_handle == NULL) {
DEBUG("snmp plugin: csnmp_read_table: host->sess_handle == NULL");
return (-1);
}
ds = plugin_get_ds(data->type);
if (!ds) {
ERROR("snmp plugin: DataSet `%s' not defined.", data->type);
return (-1);
}
if (ds->ds_num != data->values_len) {
ERROR("snmp plugin: DataSet `%s' requires %zu values, but config talks "
"about %zu",
data->type, ds->ds_num, data->values_len);
return (-1);
}
assert(data->values_len > 0);
/* We need a copy of all the OIDs, because GETNEXT will destroy them. */
memcpy(oid_list, data->values, data->values_len * sizeof(oid_t));
if (data->instance.oid.oid_len > 0)
memcpy(oid_list + data->values_len, &data->instance.oid, sizeof(oid_t));
else /* no InstanceFrom option specified. */
oid_list_len--;
for (i = 0; i < oid_list_len; i++)
oid_list_todo[i] = 1;
/* We're going to construct n linked lists, one for each "value".
* value_list_head will contain pointers to the heads of these linked lists,
* value_list_tail will contain pointers to the tail of the lists. */
value_list_head = calloc(data->values_len, sizeof(*value_list_head));
value_list_tail = calloc(data->values_len, sizeof(*value_list_tail));
if ((value_list_head == NULL) || (value_list_tail == NULL)) {
ERROR("snmp plugin: csnmp_read_table: calloc failed.");
sfree(value_list_head);
sfree(value_list_tail);
return (-1);
}
instance_list_head = NULL;
instance_list_tail = NULL;
status = 0;
while (status == 0) {
int oid_list_todo_num;
req = snmp_pdu_create(SNMP_MSG_GETNEXT);
if (req == NULL) {
ERROR("snmp plugin: snmp_pdu_create failed.");
status = -1;
break;
}
oid_list_todo_num = 0;
for (i = 0; i < oid_list_len; i++) {
/* Do not rerequest already finished OIDs */
if (!oid_list_todo[i])
continue;
oid_list_todo_num++;
snmp_add_null_var(req, oid_list[i].oid, oid_list[i].oid_len);
}
if (oid_list_todo_num == 0) {
/* The request is still empty - so we are finished */
DEBUG("snmp plugin: all variables have left their subtree");
status = 0;
break;
}
res = NULL;
status = snmp_sess_synch_response(host->sess_handle, req, &res);
if ((status != STAT_SUCCESS) || (res == NULL)) {
char *errstr = NULL;
snmp_sess_error(host->sess_handle, NULL, NULL, &errstr);
c_complain(LOG_ERR, &host->complaint,
"snmp plugin: host %s: snmp_sess_synch_response failed: %s",
host->name, (errstr == NULL) ? "Unknown problem" : errstr);
if (res != NULL)
snmp_free_pdu(res);
res = NULL;
/* snmp_synch_response already freed our PDU */
req = NULL;
sfree(errstr);
csnmp_host_close_session(host);
status = -1;
break;
}
status = 0;
assert(res != NULL);
c_release(LOG_INFO, &host->complaint,
"snmp plugin: host %s: snmp_sess_synch_response successful.",
host->name);
vb = res->variables;
if (vb == NULL) {
status = -1;
break;
}
for (vb = res->variables, i = 0; (vb != NULL);
vb = vb->next_variable, i++) {
/* Calculate value index from todo list */
while ((i < oid_list_len) && !oid_list_todo[i])
i++;
/* An instance is configured and the res variable we process is the
* instance value (last index) */
if ((data->instance.oid.oid_len > 0) && (i == data->values_len)) {
if ((vb->type == SNMP_ENDOFMIBVIEW) ||
(snmp_oid_ncompare(
data->instance.oid.oid, data->instance.oid.oid_len, vb->name,
vb->name_length, data->instance.oid.oid_len) != 0)) {
DEBUG("snmp plugin: host = %s; data = %s; Instance left its subtree.",
host->name, data->name);
oid_list_todo[i] = 0;
continue;
}
/* Allocate a new `csnmp_list_instances_t', insert the instance name and
* add it to the list */
if (csnmp_instance_list_add(&instance_list_head, &instance_list_tail,
res, host, data) != 0) {
ERROR("snmp plugin: host %s: csnmp_instance_list_add failed.",
host->name);
status = -1;
break;
}
} else /* The variable we are processing is a normal value */
{
csnmp_table_values_t *vt;
oid_t vb_name;
oid_t suffix;
int ret;
csnmp_oid_init(&vb_name, vb->name, vb->name_length);
/* Calculate the current suffix. This is later used to check that the
* suffix is increasing. This also checks if we left the subtree */
ret = csnmp_oid_suffix(&suffix, &vb_name, data->values + i);
if (ret != 0) {
DEBUG("snmp plugin: host = %s; data = %s; i = %zu; "
"Value probably left its subtree.",
host->name, data->name, i);
oid_list_todo[i] = 0;
continue;
}
/* Make sure the OIDs returned by the agent are increasing. Otherwise
* our
* table matching algorithm will get confused. */
if ((value_list_tail[i] != NULL) &&
(csnmp_oid_compare(&suffix, &value_list_tail[i]->suffix) <= 0)) {
DEBUG("snmp plugin: host = %s; data = %s; i = %zu; "
"Suffix is not increasing.",
host->name, data->name, i);
oid_list_todo[i] = 0;
continue;
}
vt = calloc(1, sizeof(*vt));
if (vt == NULL) {
ERROR("snmp plugin: calloc failed.");
status = -1;
break;
}
vt->value =
csnmp_value_list_to_value(vb, ds->ds[i].type, data->scale,
data->shift, host->name, data->name);
memcpy(&vt->suffix, &suffix, sizeof(vt->suffix));
vt->next = NULL;
if (value_list_tail[i] == NULL)
value_list_head[i] = vt;
else
value_list_tail[i]->next = vt;
value_list_tail[i] = vt;
}
/* Copy OID to oid_list[i] */
memcpy(oid_list[i].oid, vb->name, sizeof(oid) * vb->name_length);
oid_list[i].oid_len = vb->name_length;
} /* for (vb = res->variables ...) */
if (res != NULL)
snmp_free_pdu(res);
res = NULL;
} /* while (status == 0) */
if (res != NULL)
snmp_free_pdu(res);
res = NULL;
if (req != NULL)
snmp_free_pdu(req);
req = NULL;
if (status == 0)
csnmp_dispatch_table(host, data, instance_list_head, value_list_head);
/* Free all allocated variables here */
while (instance_list_head != NULL) {
csnmp_list_instances_t *next = instance_list_head->next;
sfree(instance_list_head);
instance_list_head = next;
}
for (i = 0; i < data->values_len; i++) {
while (value_list_head[i] != NULL) {
csnmp_table_values_t *next = value_list_head[i]->next;
sfree(value_list_head[i]);
value_list_head[i] = next;
}
}
sfree(value_list_head);
sfree(value_list_tail);
return (0);
} /* int csnmp_read_table */
Vulnerability Type:
CWE ID: CWE-415
Summary: The csnmp_read_table function in snmp.c in the SNMP plugin in collectd before 5.6.3 is susceptible to a double free in a certain error case, which could lead to a crash (or potentially have other impact).
Commit Message: snmp plugin: Fix double free of request PDU
snmp_sess_synch_response() always frees request PDU, in both case of request
error and success. If error condition occurs inside of `while (status == 0)`
loop, double free of `req` happens.
Issue: #2291
Signed-off-by: Florian Forster <[email protected]> | Low | 167,667 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: raptor_libxml_resolveEntity(void* user_data,
const xmlChar *publicId, const xmlChar *systemId) {
raptor_sax2* sax2 = (raptor_sax2*)user_data;
return libxml2_resolveEntity(sax2->xc, publicId, systemId);
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: Redland Raptor (aka libraptor) before 2.0.7, as used by OpenOffice 3.3 and 3.4 Beta, LibreOffice before 3.4.6 and 3.5.x before 3.5.1, and other products, allows user-assisted remote attackers to read arbitrary files via a crafted XML external entity (XXE) declaration and reference in an RDF document.
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. | Medium | 165,659 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void impeg2d_dec_hdr(void *pv_dec,impeg2d_video_decode_ip_t *ps_ip,
impeg2d_video_decode_op_t *ps_op)
{
UWORD32 u4_bits_read;
dec_state_t *ps_dec;
ps_dec = (dec_state_t *)pv_dec;
ps_op->s_ivd_video_decode_op_t.u4_error_code = 0;
impeg2d_bit_stream_init(&(ps_dec->s_bit_stream),ps_ip->s_ivd_video_decode_ip_t.pv_stream_buffer,
ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes);
{
{
IMPEG2D_ERROR_CODES_T e_error;
e_error = impeg2d_process_video_header(ps_dec);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error;
u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream);
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3;
if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
}
if(ps_op->s_ivd_video_decode_op_t.u4_error_code == 0)
ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error;
impeg2d_next_code(ps_dec, SEQUENCE_HEADER_CODE);
return;
}
}
ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_vertical_size;
ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_horizontal_size;
ps_op->s_ivd_video_decode_op_t.e_pic_type = IV_NA_FRAME;
ps_op->s_ivd_video_decode_op_t.u4_error_code = IV_SUCCESS;
u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream);
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3;
if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
}
ps_op->s_ivd_video_decode_op_t.u4_frame_decoded_flag = 0;
/* MOD */
ps_dec->u2_header_done = 1;
}
}
Vulnerability Type: Exec Code Overflow Mem. Corr.
CWE ID: CWE-119
Summary: A remote code execution vulnerability in libmpeg2 in Mediaserver could enable an attacker using a specially crafted file to cause memory corruption during media file and data processing. This issue is rated as Critical due to the possibility of remote code execution within the context of the Mediaserver process. Product: Android. Versions: 6.0, 6.0.1, 7.0, 7.1.1, 7.1.2. Android ID: A-35219737.
Commit Message: Fix in handling header decode errors
If header decode was unsuccessful, do not try decoding a frame
Also, initialize pic_wd, pic_ht for reinitialization when
decoder is created with smaller dimensions
Bug: 28886651
Bug: 35219737
Change-Id: I8c06d9052910e47fce2e6fe25ad318d4c83d2c50
(cherry picked from commit 2b9fa9ace2dbedfbac026fc9b6ab6cdac7f68c27)
(cherry picked from commit c2395cd7cc0c286a66de674032dd2ed26500aef4)
| Medium | 174,034 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void setattr_copy(struct inode *inode, const struct iattr *attr)
{
unsigned int ia_valid = attr->ia_valid;
if (ia_valid & ATTR_UID)
inode->i_uid = attr->ia_uid;
if (ia_valid & ATTR_GID)
inode->i_gid = attr->ia_gid;
if (ia_valid & ATTR_ATIME)
inode->i_atime = timespec_trunc(attr->ia_atime,
inode->i_sb->s_time_gran);
if (ia_valid & ATTR_MTIME)
inode->i_mtime = timespec_trunc(attr->ia_mtime,
inode->i_sb->s_time_gran);
if (ia_valid & ATTR_CTIME)
inode->i_ctime = timespec_trunc(attr->ia_ctime,
inode->i_sb->s_time_gran);
if (ia_valid & ATTR_MODE) {
umode_t mode = attr->ia_mode;
if (!in_group_p(inode->i_gid) &&
!inode_capable(inode, CAP_FSETID))
mode &= ~S_ISGID;
inode->i_mode = mode;
}
}
Vulnerability Type: Bypass
CWE ID: CWE-264
Summary: The capabilities implementation in the Linux kernel before 3.14.8 does not properly consider that namespaces are inapplicable to inodes, which allows local users to bypass intended chmod restrictions by first creating a user namespace, as demonstrated by setting the setgid bit on a file with group ownership of root.
Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid
The kernel has no concept of capabilities with respect to inodes; inodes
exist independently of namespaces. For example, inode_capable(inode,
CAP_LINUX_IMMUTABLE) would be nonsense.
This patch changes inode_capable to check for uid and gid mappings and
renames it to capable_wrt_inode_uidgid, which should make it more
obvious what it does.
Fixes CVE-2014-4014.
Cc: Theodore Ts'o <[email protected]>
Cc: Serge Hallyn <[email protected]>
Cc: "Eric W. Biederman" <[email protected]>
Cc: Dave Chinner <[email protected]>
Cc: [email protected]
Signed-off-by: Andy Lutomirski <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]> | High | 166,318 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: int main(int argc, char **argv) {
FILE *infile = NULL;
vpx_codec_ctx_t codec = {0};
vpx_codec_enc_cfg_t cfg = {0};
int frame_count = 0;
vpx_image_t raw;
vpx_codec_err_t res;
VpxVideoInfo info = {0};
VpxVideoWriter *writer = NULL;
const VpxInterface *encoder = NULL;
int update_frame_num = 0;
const int fps = 30; // TODO(dkovalev) add command line argument
const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument
exec_name = argv[0];
if (argc != 6)
die("Invalid number of arguments");
encoder = get_vpx_encoder_by_name("vp8");
if (!encoder)
die("Unsupported codec.");
update_frame_num = atoi(argv[5]);
if (!update_frame_num)
die("Couldn't parse frame number '%s'\n", argv[5]);
info.codec_fourcc = encoder->fourcc;
info.frame_width = strtol(argv[1], NULL, 0);
info.frame_height = strtol(argv[2], NULL, 0);
info.time_base.numerator = 1;
info.time_base.denominator = fps;
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.");
}
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;
writer = vpx_video_writer_open(argv[4], kContainerIVF, &info);
if (!writer)
die("Failed to open %s for writing.", argv[4]);
if (!(infile = fopen(argv[3], "rb")))
die("Failed to open %s for reading.", argv[3]);
if (vpx_codec_enc_init(&codec, encoder->interface(), &cfg, 0))
die_codec(&codec, "Failed to initialize encoder");
while (vpx_img_read(&raw, infile)) {
if (frame_count + 1 == update_frame_num) {
vpx_ref_frame_t ref;
ref.frame_type = VP8_LAST_FRAME;
ref.img = raw;
if (vpx_codec_control(&codec, VP8_SET_REFERENCE, &ref))
die_codec(&codec, "Failed to set reference frame");
}
encode_frame(&codec, &raw, frame_count++, writer);
}
encode_frame(&codec, NULL, -1, writer);
printf("\n");
fclose(infile);
printf("Processed %d frames.\n", frame_count);
vpx_img_free(&raw);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec.");
vpx_video_writer_close(writer);
return EXIT_SUCCESS;
}
Vulnerability Type: DoS Exec Code Overflow Mem. Corr.
CWE ID: CWE-119
Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792.
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
| Low | 174,498 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: perf_event_read_event(struct perf_event *event,
struct task_struct *task)
{
struct perf_output_handle handle;
struct perf_sample_data sample;
struct perf_read_event read_event = {
.header = {
.type = PERF_RECORD_READ,
.misc = 0,
.size = sizeof(read_event) + event->read_size,
},
.pid = perf_event_pid(event, task),
.tid = perf_event_tid(event, task),
};
int ret;
perf_event_header__init_id(&read_event.header, &sample, event);
ret = perf_output_begin(&handle, event, read_event.header.size, 0, 0);
if (ret)
return;
perf_output_put(&handle, read_event);
perf_output_read(&handle, event);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-399
Summary: The Performance Events subsystem in the Linux kernel before 3.1 does not properly handle event overflows associated with PERF_COUNT_SW_CPU_CLOCK events, which allows local users to cause a denial of service (system hang) via a crafted application.
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]> | Low | 165,834 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static int string_scan_range(RList *list, RBinFile *bf, int min,
const ut64 from, const ut64 to, int type) {
ut8 tmp[R_STRING_SCAN_BUFFER_SIZE];
ut64 str_start, needle = from;
int count = 0, i, rc, runes;
int str_type = R_STRING_TYPE_DETECT;
if (type == -1) {
type = R_STRING_TYPE_DETECT;
}
if (from >= to) {
eprintf ("Invalid range to find strings 0x%llx .. 0x%llx\n", from, to);
return -1;
}
ut8 *buf = calloc (to - from, 1);
if (!buf || !min) {
return -1;
}
r_buf_read_at (bf->buf, from, buf, to - from);
while (needle < to) {
rc = r_utf8_decode (buf + needle - from, to - needle, NULL);
if (!rc) {
needle++;
continue;
}
if (type == R_STRING_TYPE_DETECT) {
char *w = (char *)buf + needle + rc - from;
if ((to - needle) > 5) {
bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];
if (is_wide32) {
str_type = R_STRING_TYPE_WIDE32;
} else {
bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];
str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;
}
} else {
str_type = R_STRING_TYPE_ASCII;
}
} else {
str_type = type;
}
runes = 0;
str_start = needle;
/* Eat a whole C string */
for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {
RRune r = {0};
if (str_type == R_STRING_TYPE_WIDE32) {
rc = r_utf32le_decode (buf + needle - from, to - needle, &r);
if (rc) {
rc = 4;
}
} else if (str_type == R_STRING_TYPE_WIDE) {
rc = r_utf16le_decode (buf + needle - from, to - needle, &r);
if (rc == 1) {
rc = 2;
}
} else {
rc = r_utf8_decode (buf + needle - from, to - needle, &r);
if (rc > 1) {
str_type = R_STRING_TYPE_UTF8;
}
}
/* Invalid sequence detected */
if (!rc) {
needle++;
break;
}
needle += rc;
if (r_isprint (r) && r != '\\') {
if (str_type == R_STRING_TYPE_WIDE32) {
if (r == 0xff) {
r = 0;
}
}
rc = r_utf8_encode (&tmp[i], r);
runes++;
/* Print the escape code */
} else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\033\\", (char)r)) {
if ((i + 32) < sizeof (tmp) && r < 93) {
tmp[i + 0] = '\\';
tmp[i + 1] = " abtnvfr e "
" "
" "
" \\"[r];
} else {
break;
}
rc = 2;
runes++;
} else {
/* \0 marks the end of C-strings */
break;
}
}
tmp[i++] = '\0';
if (runes >= min) {
if (str_type == R_STRING_TYPE_ASCII) {
int j;
for (j = 0; j < i; j++) {
char ch = tmp[j];
if (ch != '\n' && ch != '\r' && ch != '\t') {
if (!IS_PRINTABLE (tmp[j])) {
continue;
}
}
}
}
RBinString *bs = R_NEW0 (RBinString);
if (!bs) {
break;
}
bs->type = str_type;
bs->length = runes;
bs->size = needle - str_start;
bs->ordinal = count++;
switch (str_type) {
case R_STRING_TYPE_WIDE:
if (str_start -from> 1) {
const ut8 *p = buf + str_start - 2 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 2; // \xff\xfe
}
}
break;
case R_STRING_TYPE_WIDE32:
if (str_start -from> 3) {
const ut8 *p = buf + str_start - 4 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 4; // \xff\xfe\x00\x00
}
}
break;
}
bs->paddr = bs->vaddr = str_start;
bs->string = r_str_ndup ((const char *)tmp, i);
if (list) {
r_list_append (list, bs);
} else {
print_string (bs, bf);
r_bin_string_free (bs);
}
}
}
free (buf);
return count;
}
Vulnerability Type: DoS
CWE ID: CWE-125
Summary: The string_scan_range() function in radare2 2.5.0 allows remote attackers to cause a denial of service (heap-based out-of-bounds read and application crash) via a crafted binary file.
Commit Message: Fix #9902 - Fix oobread in RBin.string_scan_range | Medium | 169,224 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void CopyFromOMX(const OMX_BUFFERHEADERTYPE *header) {
if (!mIsBackup) {
return;
}
sp<ABuffer> codec = getBuffer(header, false /* backup */, true /* limit */);
memcpy((OMX_U8 *)mMem->pointer() + header->nOffset, codec->data(), codec->size());
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: An information disclosure vulnerability in libstagefright in Mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, 6.x before 2016-11-01, and 7.0 before 2016-11-01 could enable a local malicious application to access data outside of its permission levels. This issue is rated as Moderate because it could be used to access sensitive data without permission. Android ID: A-29422020.
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
| Medium | 174,127 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static irqreturn_t i8042_interrupt(int irq, void *dev_id)
{
struct i8042_port *port;
struct serio *serio;
unsigned long flags;
unsigned char str, data;
unsigned int dfl;
unsigned int port_no;
bool filtered;
int ret = 1;
spin_lock_irqsave(&i8042_lock, flags);
str = i8042_read_status();
if (unlikely(~str & I8042_STR_OBF)) {
spin_unlock_irqrestore(&i8042_lock, flags);
if (irq)
dbg("Interrupt %d, without any data\n", irq);
ret = 0;
goto out;
}
data = i8042_read_data();
if (i8042_mux_present && (str & I8042_STR_AUXDATA)) {
static unsigned long last_transmit;
static unsigned char last_str;
dfl = 0;
if (str & I8042_STR_MUXERR) {
dbg("MUX error, status is %02x, data is %02x\n",
str, data);
/*
* When MUXERR condition is signalled the data register can only contain
* 0xfd, 0xfe or 0xff if implementation follows the spec. Unfortunately
* it is not always the case. Some KBCs also report 0xfc when there is
* nothing connected to the port while others sometimes get confused which
* port the data came from and signal error leaving the data intact. They
* _do not_ revert to legacy mode (actually I've never seen KBC reverting
* to legacy mode yet, when we see one we'll add proper handling).
* Anyway, we process 0xfc, 0xfd, 0xfe and 0xff as timeouts, and for the
* rest assume that the data came from the same serio last byte
* was transmitted (if transmission happened not too long ago).
*/
switch (data) {
default:
if (time_before(jiffies, last_transmit + HZ/10)) {
str = last_str;
break;
}
/* fall through - report timeout */
case 0xfc:
case 0xfd:
case 0xfe: dfl = SERIO_TIMEOUT; data = 0xfe; break;
case 0xff: dfl = SERIO_PARITY; data = 0xfe; break;
}
}
port_no = I8042_MUX_PORT_NO + ((str >> 6) & 3);
last_str = str;
last_transmit = jiffies;
} else {
dfl = ((str & I8042_STR_PARITY) ? SERIO_PARITY : 0) |
((str & I8042_STR_TIMEOUT && !i8042_notimeout) ? SERIO_TIMEOUT : 0);
port_no = (str & I8042_STR_AUXDATA) ?
I8042_AUX_PORT_NO : I8042_KBD_PORT_NO;
}
port = &i8042_ports[port_no];
serio = port->exists ? port->serio : NULL;
filter_dbg(port->driver_bound, data, "<- i8042 (interrupt, %d, %d%s%s)\n",
port_no, irq,
dfl & SERIO_PARITY ? ", bad parity" : "",
dfl & SERIO_TIMEOUT ? ", timeout" : "");
filtered = i8042_filter(data, str, serio);
spin_unlock_irqrestore(&i8042_lock, flags);
if (likely(port->exists && !filtered))
serio_interrupt(serio, data, dfl);
out:
return IRQ_RETVAL(ret);
}
Vulnerability Type: DoS
CWE ID: CWE-476
Summary: drivers/input/serio/i8042.c in the Linux kernel before 4.12.4 allows attackers to cause a denial of service (NULL pointer dereference and system crash) or possibly have unspecified other impact because the port->exists value can change after it is validated.
Commit Message: Input: i8042 - fix crash at boot time
The driver checks port->exists twice in i8042_interrupt(), first when
trying to assign temporary "serio" variable, and second time when deciding
whether it should call serio_interrupt(). The value of port->exists may
change between the 2 checks, and we may end up calling serio_interrupt()
with a NULL pointer:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000050
IP: [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40
PGD 0
Oops: 0002 [#1] SMP
last sysfs file:
CPU 0
Modules linked in:
Pid: 1, comm: swapper Not tainted 2.6.32-358.el6.x86_64 #1 QEMU Standard PC (i440FX + PIIX, 1996)
RIP: 0010:[<ffffffff8150feaf>] [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40
RSP: 0018:ffff880028203cc0 EFLAGS: 00010082
RAX: 0000000000010000 RBX: 0000000000000000 RCX: 0000000000000000
RDX: 0000000000000282 RSI: 0000000000000098 RDI: 0000000000000050
RBP: ffff880028203cc0 R08: ffff88013e79c000 R09: ffff880028203ee0
R10: 0000000000000298 R11: 0000000000000282 R12: 0000000000000050
R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000098
FS: 0000000000000000(0000) GS:ffff880028200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b
CR2: 0000000000000050 CR3: 0000000001a85000 CR4: 00000000001407f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
Process swapper (pid: 1, threadinfo ffff88013e79c000, task ffff88013e79b500)
Stack:
ffff880028203d00 ffffffff813de186 ffffffffffffff02 0000000000000000
<d> 0000000000000000 0000000000000000 0000000000000000 0000000000000098
<d> ffff880028203d70 ffffffff813e0162 ffff880028203d20 ffffffff8103b8ac
Call Trace:
<IRQ>
[<ffffffff813de186>] serio_interrupt+0x36/0xa0
[<ffffffff813e0162>] i8042_interrupt+0x132/0x3a0
[<ffffffff8103b8ac>] ? kvm_clock_read+0x1c/0x20
[<ffffffff8103b8b9>] ? kvm_clock_get_cycles+0x9/0x10
[<ffffffff810e1640>] handle_IRQ_event+0x60/0x170
[<ffffffff8103b154>] ? kvm_guest_apic_eoi_write+0x44/0x50
[<ffffffff810e3d8e>] handle_edge_irq+0xde/0x180
[<ffffffff8100de89>] handle_irq+0x49/0xa0
[<ffffffff81516c8c>] do_IRQ+0x6c/0xf0
[<ffffffff8100b9d3>] ret_from_intr+0x0/0x11
[<ffffffff81076f63>] ? __do_softirq+0x73/0x1e0
[<ffffffff8109b75b>] ? hrtimer_interrupt+0x14b/0x260
[<ffffffff8100c1cc>] ? call_softirq+0x1c/0x30
[<ffffffff8100de05>] ? do_softirq+0x65/0xa0
[<ffffffff81076d95>] ? irq_exit+0x85/0x90
[<ffffffff81516d80>] ? smp_apic_timer_interrupt+0x70/0x9b
[<ffffffff8100bb93>] ? apic_timer_interrupt+0x13/0x20
To avoid the issue let's change the second check to test whether serio is
NULL or not.
Also, let's take i8042_lock in i8042_start() and i8042_stop() instead of
trying to be overly smart and using memory barriers.
Signed-off-by: Chen Hong <[email protected]>
[dtor: take lock in i8042_start()/i8042_stop()]
Cc: [email protected]
Signed-off-by: Dmitry Torokhov <[email protected]> | Low | 169,421 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static long bcm_char_ioctl(struct file *filp, UINT cmd, ULONG arg)
{
struct bcm_tarang_data *pTarang = filp->private_data;
void __user *argp = (void __user *)arg;
struct bcm_mini_adapter *Adapter = pTarang->Adapter;
INT Status = STATUS_FAILURE;
int timeout = 0;
struct bcm_ioctl_buffer IoBuffer;
int bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Parameters Passed to control IOCTL cmd=0x%X arg=0x%lX", cmd, arg);
if (_IOC_TYPE(cmd) != BCM_IOCTL)
return -EFAULT;
if (_IOC_DIR(cmd) & _IOC_READ)
Status = !access_ok(VERIFY_WRITE, argp, _IOC_SIZE(cmd));
else if (_IOC_DIR(cmd) & _IOC_WRITE)
Status = !access_ok(VERIFY_READ, argp, _IOC_SIZE(cmd));
else if (_IOC_NONE == (_IOC_DIR(cmd) & _IOC_NONE))
Status = STATUS_SUCCESS;
if (Status)
return -EFAULT;
if (Adapter->device_removed)
return -EFAULT;
if (FALSE == Adapter->fw_download_done) {
switch (cmd) {
case IOCTL_MAC_ADDR_REQ:
case IOCTL_LINK_REQ:
case IOCTL_CM_REQUEST:
case IOCTL_SS_INFO_REQ:
case IOCTL_SEND_CONTROL_MESSAGE:
case IOCTL_IDLE_REQ:
case IOCTL_BCM_GPIO_SET_REQUEST:
case IOCTL_BCM_GPIO_STATUS_REQUEST:
return -EACCES;
default:
break;
}
}
Status = vendorextnIoctl(Adapter, cmd, arg);
if (Status != CONTINUE_COMMON_PATH)
return Status;
switch (cmd) {
/* Rdms for Swin Idle... */
case IOCTL_BCM_REGISTER_READ_PRIVATE: {
struct bcm_rdm_buffer sRdmBuffer = {0};
PCHAR temp_buff;
UINT Bufflen;
u16 temp_value;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sRdmBuffer))
return -EINVAL;
if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if (IoBuffer.OutputLength > USHRT_MAX ||
IoBuffer.OutputLength == 0) {
return -EINVAL;
}
Bufflen = IoBuffer.OutputLength;
temp_value = 4 - (Bufflen % 4);
Bufflen += temp_value % 4;
temp_buff = kmalloc(Bufflen, GFP_KERNEL);
if (!temp_buff)
return -ENOMEM;
bytes = rdmalt(Adapter, (UINT)sRdmBuffer.Register,
(PUINT)temp_buff, Bufflen);
if (bytes > 0) {
Status = STATUS_SUCCESS;
if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) {
kfree(temp_buff);
return -EFAULT;
}
} else {
Status = bytes;
}
kfree(temp_buff);
break;
}
case IOCTL_BCM_REGISTER_WRITE_PRIVATE: {
struct bcm_wrm_buffer sWrmBuffer = {0};
UINT uiTempVar = 0;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sWrmBuffer))
return -EINVAL;
/* Get WrmBuffer structure */
if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK;
if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) &&
((uiTempVar == EEPROM_REJECT_REG_1) ||
(uiTempVar == EEPROM_REJECT_REG_2) ||
(uiTempVar == EEPROM_REJECT_REG_3) ||
(uiTempVar == EEPROM_REJECT_REG_4))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n");
return -EFAULT;
}
Status = wrmalt(Adapter, (UINT)sWrmBuffer.Register,
(PUINT)sWrmBuffer.Data, sizeof(ULONG));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Done\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Failed\n");
Status = -EFAULT;
}
break;
}
case IOCTL_BCM_REGISTER_READ:
case IOCTL_BCM_EEPROM_REGISTER_READ: {
struct bcm_rdm_buffer sRdmBuffer = {0};
PCHAR temp_buff = NULL;
UINT uiTempVar = 0;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle Mode, Blocking Rdms\n");
return -EACCES;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sRdmBuffer))
return -EINVAL;
if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if (IoBuffer.OutputLength > USHRT_MAX ||
IoBuffer.OutputLength == 0) {
return -EINVAL;
}
temp_buff = kmalloc(IoBuffer.OutputLength, GFP_KERNEL);
if (!temp_buff)
return STATUS_FAILURE;
if ((((ULONG)sRdmBuffer.Register & 0x0F000000) != 0x0F000000) ||
((ULONG)sRdmBuffer.Register & 0x3)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM Done On invalid Address : %x Access Denied.\n",
(int)sRdmBuffer.Register);
kfree(temp_buff);
return -EINVAL;
}
uiTempVar = sRdmBuffer.Register & EEPROM_REJECT_MASK;
bytes = rdmaltWithLock(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, IoBuffer.OutputLength);
if (bytes > 0) {
Status = STATUS_SUCCESS;
if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) {
kfree(temp_buff);
return -EFAULT;
}
} else {
Status = bytes;
}
kfree(temp_buff);
break;
}
case IOCTL_BCM_REGISTER_WRITE:
case IOCTL_BCM_EEPROM_REGISTER_WRITE: {
struct bcm_wrm_buffer sWrmBuffer = {0};
UINT uiTempVar = 0;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle Mode, Blocking Wrms\n");
return -EACCES;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sWrmBuffer))
return -EINVAL;
/* Get WrmBuffer structure */
if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if ((((ULONG)sWrmBuffer.Register & 0x0F000000) != 0x0F000000) ||
((ULONG)sWrmBuffer.Register & 0x3)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Done On invalid Address : %x Access Denied.\n", (int)sWrmBuffer.Register);
return -EINVAL;
}
uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK;
if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) &&
((uiTempVar == EEPROM_REJECT_REG_1) ||
(uiTempVar == EEPROM_REJECT_REG_2) ||
(uiTempVar == EEPROM_REJECT_REG_3) ||
(uiTempVar == EEPROM_REJECT_REG_4)) &&
(cmd == IOCTL_BCM_REGISTER_WRITE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n");
return -EFAULT;
}
Status = wrmaltWithLock(Adapter, (UINT)sWrmBuffer.Register,
(PUINT)sWrmBuffer.Data, sWrmBuffer.Length);
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, "WRM Done\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Failed\n");
Status = -EFAULT;
}
break;
}
case IOCTL_BCM_GPIO_SET_REQUEST: {
UCHAR ucResetValue[4];
UINT value = 0;
UINT uiBit = 0;
UINT uiOperation = 0;
struct bcm_gpio_info gpio_info = {0};
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "GPIO Can't be set/clear in Low power Mode");
return -EACCES;
}
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_info))
return -EINVAL;
if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
uiBit = gpio_info.uiGpioNumber;
uiOperation = gpio_info.uiGpioValue;
value = (1<<uiBit);
if (IsReqGpioIsLedInNVM(Adapter, value) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Sorry, Requested GPIO<0x%X> is not correspond to LED !!!", value);
Status = -EINVAL;
break;
}
/* Set - setting 1 */
if (uiOperation) {
/* Set the gpio output register */
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)(&value), sizeof(UINT));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO bit\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to set the %dth GPIO\n", uiBit);
break;
}
} else {
/* Set the gpio output register */
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)(&value), sizeof(UINT));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO bit\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to clear the %dth GPIO\n", uiBit);
break;
}
}
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"GPIO_MODE_REGISTER read failed");
break;
} else {
Status = STATUS_SUCCESS;
}
/* Set the gpio mode register to output */
*(UINT *)ucResetValue |= (1<<uiBit);
Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER,
(PUINT)ucResetValue, sizeof(UINT));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO to output Mode\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to put GPIO in Output Mode\n");
break;
}
}
break;
case BCM_LED_THREAD_STATE_CHANGE_REQ: {
struct bcm_user_thread_req threadReq = {0};
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "User made LED thread InActive");
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "GPIO Can't be set/clear in Low power Mode");
Status = -EACCES;
break;
}
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(threadReq))
return -EINVAL;
if (copy_from_user(&threadReq, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
/* if LED thread is running(Actively or Inactively) set it state to make inactive */
if (Adapter->LEDInfo.led_thread_running) {
if (threadReq.ThreadState == LED_THREAD_ACTIVATION_REQ) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Activating thread req");
Adapter->DriverState = LED_THREAD_ACTIVE;
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DeActivating Thread req.....");
Adapter->DriverState = LED_THREAD_INACTIVE;
}
/* signal thread. */
wake_up(&Adapter->LEDInfo.notify_led_event);
}
}
break;
case IOCTL_BCM_GPIO_STATUS_REQUEST: {
ULONG uiBit = 0;
UCHAR ucRead[4];
struct bcm_gpio_info gpio_info = {0};
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE))
return -EACCES;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_info))
return -EINVAL;
if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
uiBit = gpio_info.uiGpioNumber;
/* Set the gpio output register */
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER,
(PUINT)ucRead, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM Failed\n");
return Status;
} else {
Status = STATUS_SUCCESS;
}
}
break;
case IOCTL_BCM_GPIO_MULTI_REQUEST: {
UCHAR ucResetValue[4];
struct bcm_gpio_multi_info gpio_multi_info[MAX_IDX];
struct bcm_gpio_multi_info *pgpio_multi_info = (struct bcm_gpio_multi_info *)gpio_multi_info;
memset(pgpio_multi_info, 0, MAX_IDX * sizeof(struct bcm_gpio_multi_info));
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE))
return -EINVAL;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_multi_info))
return -EINVAL;
if (copy_from_user(&gpio_multi_info, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_info[WIMAX_IDX].uiGPIOMask) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!",
pgpio_multi_info[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap);
Status = -EINVAL;
break;
}
/* Set the gpio output register */
if ((pgpio_multi_info[WIMAX_IDX].uiGPIOMask) &
(pgpio_multi_info[WIMAX_IDX].uiGPIOCommand)) {
/* Set 1's in GPIO OUTPUT REGISTER */
*(UINT *)ucResetValue = pgpio_multi_info[WIMAX_IDX].uiGPIOMask &
pgpio_multi_info[WIMAX_IDX].uiGPIOCommand &
pgpio_multi_info[WIMAX_IDX].uiGPIOValue;
if (*(UINT *) ucResetValue)
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG,
(PUINT)ucResetValue, sizeof(ULONG));
if (Status != STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM to BCM_GPIO_OUTPUT_SET_REG Failed.");
return Status;
}
/* Clear to 0's in GPIO OUTPUT REGISTER */
*(UINT *)ucResetValue = (pgpio_multi_info[WIMAX_IDX].uiGPIOMask &
pgpio_multi_info[WIMAX_IDX].uiGPIOCommand &
(~(pgpio_multi_info[WIMAX_IDX].uiGPIOValue)));
if (*(UINT *) ucResetValue)
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)ucResetValue, sizeof(ULONG));
if (Status != STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM to BCM_GPIO_OUTPUT_CLR_REG Failed.");
return Status;
}
}
if (pgpio_multi_info[WIMAX_IDX].uiGPIOMask) {
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucResetValue, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM to GPIO_PIN_STATE_REGISTER Failed.");
return Status;
} else {
Status = STATUS_SUCCESS;
}
pgpio_multi_info[WIMAX_IDX].uiGPIOValue = (*(UINT *)ucResetValue &
pgpio_multi_info[WIMAX_IDX].uiGPIOMask);
}
Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_info, IoBuffer.OutputLength);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Failed while copying Content to IOBufer for user space err:%d", Status);
return -EFAULT;
}
}
break;
case IOCTL_BCM_GPIO_MODE_REQUEST: {
UCHAR ucResetValue[4];
struct bcm_gpio_multi_mode gpio_multi_mode[MAX_IDX];
struct bcm_gpio_multi_mode *pgpio_multi_mode = (struct bcm_gpio_multi_mode *)gpio_multi_mode;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE))
return -EINVAL;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_multi_mode))
return -EINVAL;
if (copy_from_user(&gpio_multi_mode, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Read of GPIO_MODE_REGISTER failed");
return Status;
} else {
Status = STATUS_SUCCESS;
}
/* Validating the request */
if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!",
pgpio_multi_mode[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap);
Status = -EINVAL;
break;
}
if (pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) {
/* write all OUT's (1's) */
*(UINT *) ucResetValue |= (pgpio_multi_mode[WIMAX_IDX].uiGPIOMode &
pgpio_multi_mode[WIMAX_IDX].uiGPIOMask);
/* write all IN's (0's) */
*(UINT *) ucResetValue &= ~((~pgpio_multi_mode[WIMAX_IDX].uiGPIOMode) &
pgpio_multi_mode[WIMAX_IDX].uiGPIOMask);
/* Currently implemented return the modes of all GPIO's
* else needs to bit AND with mask
*/
pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue;
Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(ULONG));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"WRM to GPIO_MODE_REGISTER Done");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"WRM to GPIO_MODE_REGISTER Failed");
Status = -EFAULT;
break;
}
} else {
/* if uiGPIOMask is 0 then return mode register configuration */
pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue;
}
Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_mode, IoBuffer.OutputLength);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Failed while copying Content to IOBufer for user space err:%d", Status);
return -EFAULT;
}
}
break;
case IOCTL_MAC_ADDR_REQ:
case IOCTL_LINK_REQ:
case IOCTL_CM_REQUEST:
case IOCTL_SS_INFO_REQ:
case IOCTL_SEND_CONTROL_MESSAGE:
case IOCTL_IDLE_REQ: {
PVOID pvBuffer = NULL;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength < sizeof(struct bcm_link_request))
return -EINVAL;
if (IoBuffer.InputLength > MAX_CNTL_PKT_SIZE)
return -EINVAL;
pvBuffer = memdup_user(IoBuffer.InputBuffer,
IoBuffer.InputLength);
if (IS_ERR(pvBuffer))
return PTR_ERR(pvBuffer);
down(&Adapter->LowPowerModeSync);
Status = wait_event_interruptible_timeout(Adapter->lowpower_mode_wait_queue,
!Adapter->bPreparingForLowPowerMode,
(1 * HZ));
if (Status == -ERESTARTSYS)
goto cntrlEnd;
if (Adapter->bPreparingForLowPowerMode) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Preparing Idle Mode is still True - Hence Rejecting control message\n");
Status = STATUS_FAILURE;
goto cntrlEnd;
}
Status = CopyBufferToControlPacket(Adapter, (PVOID)pvBuffer);
cntrlEnd:
up(&Adapter->LowPowerModeSync);
kfree(pvBuffer);
break;
}
case IOCTL_BCM_BUFFER_DOWNLOAD_START: {
if (down_trylock(&Adapter->NVMRdmWrmLock)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\n");
return -EACCES;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Starting the firmware download PID =0x%x!!!!\n", current->pid);
if (down_trylock(&Adapter->fw_download_sema))
return -EBUSY;
Adapter->bBinDownloaded = FALSE;
Adapter->fw_download_process_pid = current->pid;
Adapter->bCfgDownloaded = FALSE;
Adapter->fw_download_done = FALSE;
netif_carrier_off(Adapter->dev);
netif_stop_queue(Adapter->dev);
Status = reset_card_proc(Adapter);
if (Status) {
pr_err(PFX "%s: reset_card_proc Failed!\n", Adapter->dev->name);
up(&Adapter->fw_download_sema);
up(&Adapter->NVMRdmWrmLock);
return Status;
}
mdelay(10);
up(&Adapter->NVMRdmWrmLock);
return Status;
}
case IOCTL_BCM_BUFFER_DOWNLOAD: {
struct bcm_firmware_info *psFwInfo = NULL;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Starting the firmware download PID =0x%x!!!!\n", current->pid);
if (!down_trylock(&Adapter->fw_download_sema)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Invalid way to download buffer. Use Start and then call this!!!\n");
up(&Adapter->fw_download_sema);
Status = -EINVAL;
return Status;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) {
up(&Adapter->fw_download_sema);
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Length for FW DLD is : %lx\n", IoBuffer.InputLength);
if (IoBuffer.InputLength > sizeof(struct bcm_firmware_info)) {
up(&Adapter->fw_download_sema);
return -EINVAL;
}
psFwInfo = kmalloc(sizeof(*psFwInfo), GFP_KERNEL);
if (!psFwInfo) {
up(&Adapter->fw_download_sema);
return -ENOMEM;
}
if (copy_from_user(psFwInfo, IoBuffer.InputBuffer, IoBuffer.InputLength)) {
up(&Adapter->fw_download_sema);
kfree(psFwInfo);
return -EFAULT;
}
if (!psFwInfo->pvMappedFirmwareAddress ||
(psFwInfo->u32FirmwareLength == 0)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Something else is wrong %lu\n",
psFwInfo->u32FirmwareLength);
up(&Adapter->fw_download_sema);
kfree(psFwInfo);
Status = -EINVAL;
return Status;
}
Status = bcm_ioctl_fw_download(Adapter, psFwInfo);
if (Status != STATUS_SUCCESS) {
if (psFwInfo->u32StartingAddress == CONFIG_BEGIN_ADDR)
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL: Configuration File Upload Failed\n");
else
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL: Firmware File Upload Failed\n");
/* up(&Adapter->fw_download_sema); */
if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) {
Adapter->DriverState = DRIVER_INIT;
Adapter->LEDInfo.bLedInitDone = FALSE;
wake_up(&Adapter->LEDInfo.notify_led_event);
}
}
if (Status != STATUS_SUCCESS)
up(&Adapter->fw_download_sema);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, "IOCTL: Firmware File Uploaded\n");
kfree(psFwInfo);
return Status;
}
case IOCTL_BCM_BUFFER_DOWNLOAD_STOP: {
if (!down_trylock(&Adapter->fw_download_sema)) {
up(&Adapter->fw_download_sema);
return -EINVAL;
}
if (down_trylock(&Adapter->NVMRdmWrmLock)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"FW download blocked as EEPROM Read/Write is in progress\n");
up(&Adapter->fw_download_sema);
return -EACCES;
}
Adapter->bBinDownloaded = TRUE;
Adapter->bCfgDownloaded = TRUE;
atomic_set(&Adapter->CurrNumFreeTxDesc, 0);
Adapter->CurrNumRecvDescs = 0;
Adapter->downloadDDR = 0;
/* setting the Mips to Run */
Status = run_card_proc(Adapter);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Firm Download Failed\n");
up(&Adapter->fw_download_sema);
up(&Adapter->NVMRdmWrmLock);
return Status;
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG,
DBG_LVL_ALL, "Firm Download Over...\n");
}
mdelay(10);
/* Wait for MailBox Interrupt */
if (StartInterruptUrb((struct bcm_interface_adapter *)Adapter->pvInterfaceAdapter))
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Unable to send interrupt...\n");
timeout = 5*HZ;
Adapter->waiting_to_fw_download_done = FALSE;
wait_event_timeout(Adapter->ioctl_fw_dnld_wait_queue,
Adapter->waiting_to_fw_download_done, timeout);
Adapter->fw_download_process_pid = INVALID_PID;
Adapter->fw_download_done = TRUE;
atomic_set(&Adapter->CurrNumFreeTxDesc, 0);
Adapter->CurrNumRecvDescs = 0;
Adapter->PrevNumRecvDescs = 0;
atomic_set(&Adapter->cntrlpktCnt, 0);
Adapter->LinkUpStatus = 0;
Adapter->LinkStatus = 0;
if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) {
Adapter->DriverState = FW_DOWNLOAD_DONE;
wake_up(&Adapter->LEDInfo.notify_led_event);
}
if (!timeout)
Status = -ENODEV;
up(&Adapter->fw_download_sema);
up(&Adapter->NVMRdmWrmLock);
return Status;
}
case IOCTL_BE_BUCKET_SIZE:
Status = 0;
if (get_user(Adapter->BEBucketSize, (unsigned long __user *)arg))
Status = -EFAULT;
break;
case IOCTL_RTPS_BUCKET_SIZE:
Status = 0;
if (get_user(Adapter->rtPSBucketSize, (unsigned long __user *)arg))
Status = -EFAULT;
break;
case IOCTL_CHIP_RESET: {
INT NVMAccess = down_trylock(&Adapter->NVMRdmWrmLock);
if (NVMAccess) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, " IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\n");
return -EACCES;
}
down(&Adapter->RxAppControlQueuelock);
Status = reset_card_proc(Adapter);
flushAllAppQ();
up(&Adapter->RxAppControlQueuelock);
up(&Adapter->NVMRdmWrmLock);
ResetCounters(Adapter);
break;
}
case IOCTL_QOS_THRESHOLD: {
USHORT uiLoopIndex;
Status = 0;
for (uiLoopIndex = 0; uiLoopIndex < NO_OF_QUEUES; uiLoopIndex++) {
if (get_user(Adapter->PackInfo[uiLoopIndex].uiThreshold,
(unsigned long __user *)arg)) {
Status = -EFAULT;
break;
}
}
break;
}
case IOCTL_DUMP_PACKET_INFO:
DumpPackInfo(Adapter);
DumpPhsRules(&Adapter->stBCMPhsContext);
Status = STATUS_SUCCESS;
break;
case IOCTL_GET_PACK_INFO:
if (copy_to_user(argp, &Adapter->PackInfo, sizeof(struct bcm_packet_info)*NO_OF_QUEUES))
return -EFAULT;
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_SWITCH_TRANSFER_MODE: {
UINT uiData = 0;
if (copy_from_user(&uiData, argp, sizeof(UINT)))
return -EFAULT;
if (uiData) {
/* Allow All Packets */
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SWITCH_TRANSFER_MODE: ETH_PACKET_TUNNELING_MODE\n");
Adapter->TransferMode = ETH_PACKET_TUNNELING_MODE;
} else {
/* Allow IP only Packets */
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SWITCH_TRANSFER_MODE: IP_PACKET_ONLY_MODE\n");
Adapter->TransferMode = IP_PACKET_ONLY_MODE;
}
Status = STATUS_SUCCESS;
break;
}
case IOCTL_BCM_GET_DRIVER_VERSION: {
ulong len;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
len = min_t(ulong, IoBuffer.OutputLength, strlen(DRV_VERSION) + 1);
if (copy_to_user(IoBuffer.OutputBuffer, DRV_VERSION, len))
return -EFAULT;
Status = STATUS_SUCCESS;
break;
}
case IOCTL_BCM_GET_CURRENT_STATUS: {
struct bcm_link_state link_state;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "copy_from_user failed..\n");
return -EFAULT;
}
if (IoBuffer.OutputLength != sizeof(link_state)) {
Status = -EINVAL;
break;
}
memset(&link_state, 0, sizeof(link_state));
link_state.bIdleMode = Adapter->IdleMode;
link_state.bShutdownMode = Adapter->bShutStatus;
link_state.ucLinkStatus = Adapter->LinkStatus;
if (copy_to_user(IoBuffer.OutputBuffer, &link_state, min_t(size_t, sizeof(link_state), IoBuffer.OutputLength))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy_to_user Failed..\n");
return -EFAULT;
}
Status = STATUS_SUCCESS;
break;
}
case IOCTL_BCM_SET_MAC_TRACING: {
UINT tracing_flag;
/* copy ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&tracing_flag, IoBuffer.InputBuffer, sizeof(UINT)))
return -EFAULT;
if (tracing_flag)
Adapter->pTarangs->MacTracingEnabled = TRUE;
else
Adapter->pTarangs->MacTracingEnabled = FALSE;
break;
}
case IOCTL_BCM_GET_DSX_INDICATION: {
ULONG ulSFId = 0;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength < sizeof(struct bcm_add_indication_alt)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Mismatch req: %lx needed is =0x%zx!!!",
IoBuffer.OutputLength, sizeof(struct bcm_add_indication_alt));
return -EINVAL;
}
if (copy_from_user(&ulSFId, IoBuffer.InputBuffer, sizeof(ulSFId)))
return -EFAULT;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Get DSX Data SF ID is =%lx\n", ulSFId);
get_dsx_sf_data_to_application(Adapter, ulSFId, IoBuffer.OutputBuffer);
Status = STATUS_SUCCESS;
}
break;
case IOCTL_BCM_GET_HOST_MIBS: {
PVOID temp_buff;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength != sizeof(struct bcm_host_stats_mibs)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Length Check failed %lu %zd\n",
IoBuffer.OutputLength, sizeof(struct bcm_host_stats_mibs));
return -EINVAL;
}
/* FIXME: HOST_STATS are too big for kmalloc (122048)! */
temp_buff = kzalloc(sizeof(struct bcm_host_stats_mibs), GFP_KERNEL);
if (!temp_buff)
return STATUS_FAILURE;
Status = ProcessGetHostMibs(Adapter, temp_buff);
GetDroppedAppCntrlPktMibs(temp_buff, pTarang);
if (Status != STATUS_FAILURE)
if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, sizeof(struct bcm_host_stats_mibs))) {
kfree(temp_buff);
return -EFAULT;
}
kfree(temp_buff);
break;
}
case IOCTL_BCM_WAKE_UP_DEVICE_FROM_IDLE:
if ((FALSE == Adapter->bTriedToWakeUpFromlowPowerMode) && (TRUE == Adapter->IdleMode)) {
Adapter->usIdleModePattern = ABORT_IDLE_MODE;
Adapter->bWakeUpDevice = TRUE;
wake_up(&Adapter->process_rx_cntrlpkt);
}
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_BULK_WRM: {
struct bcm_bulk_wrm_buffer *pBulkBuffer;
UINT uiTempVar = 0;
PCHAR pvBuffer = NULL;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle/Shutdown Mode, Blocking Wrms\n");
Status = -EACCES;
break;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength < sizeof(ULONG) * 2)
return -EINVAL;
pvBuffer = memdup_user(IoBuffer.InputBuffer,
IoBuffer.InputLength);
if (IS_ERR(pvBuffer))
return PTR_ERR(pvBuffer);
pBulkBuffer = (struct bcm_bulk_wrm_buffer *)pvBuffer;
if (((ULONG)pBulkBuffer->Register & 0x0F000000) != 0x0F000000 ||
((ULONG)pBulkBuffer->Register & 0x3)) {
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Done On invalid Address : %x Access Denied.\n", (int)pBulkBuffer->Register);
kfree(pvBuffer);
Status = -EINVAL;
break;
}
uiTempVar = pBulkBuffer->Register & EEPROM_REJECT_MASK;
if (!((Adapter->pstargetparams->m_u32Customize)&VSG_MODE) &&
((uiTempVar == EEPROM_REJECT_REG_1) ||
(uiTempVar == EEPROM_REJECT_REG_2) ||
(uiTempVar == EEPROM_REJECT_REG_3) ||
(uiTempVar == EEPROM_REJECT_REG_4)) &&
(cmd == IOCTL_BCM_REGISTER_WRITE)) {
kfree(pvBuffer);
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n");
Status = -EFAULT;
break;
}
if (pBulkBuffer->SwapEndian == FALSE)
Status = wrmWithLock(Adapter, (UINT)pBulkBuffer->Register, (PCHAR)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG));
else
Status = wrmaltWithLock(Adapter, (UINT)pBulkBuffer->Register, (PUINT)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG));
if (Status != STATUS_SUCCESS)
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Failed\n");
kfree(pvBuffer);
break;
}
case IOCTL_BCM_GET_NVM_SIZE:
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (Adapter->eNVMType == NVM_EEPROM || Adapter->eNVMType == NVM_FLASH) {
if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiNVMDSDSize, sizeof(UINT)))
return -EFAULT;
}
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_CAL_INIT: {
UINT uiSectorSize = 0 ;
if (Adapter->eNVMType == NVM_FLASH) {
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&uiSectorSize, IoBuffer.InputBuffer, sizeof(UINT)))
return -EFAULT;
if ((uiSectorSize < MIN_SECTOR_SIZE) || (uiSectorSize > MAX_SECTOR_SIZE)) {
if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize,
sizeof(UINT)))
return -EFAULT;
} else {
if (IsFlash2x(Adapter)) {
if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT)))
return -EFAULT;
} else {
if ((TRUE == Adapter->bShutStatus) || (TRUE == Adapter->IdleMode)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device is in Idle/Shutdown Mode\n");
return -EACCES;
}
Adapter->uiSectorSize = uiSectorSize;
BcmUpdateSectorSize(Adapter, Adapter->uiSectorSize);
}
}
Status = STATUS_SUCCESS;
} else {
Status = STATUS_FAILURE;
}
}
break;
case IOCTL_BCM_SET_DEBUG:
#ifdef DEBUG
{
struct bcm_user_debug_state sUserDebugState;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "In SET_DEBUG ioctl\n");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&sUserDebugState, IoBuffer.InputBuffer, sizeof(struct bcm_user_debug_state)))
return -EFAULT;
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL_BCM_SET_DEBUG: OnOff=%d Type = 0x%x ",
sUserDebugState.OnOff, sUserDebugState.Type);
/* sUserDebugState.Subtype <<= 1; */
sUserDebugState.Subtype = 1 << sUserDebugState.Subtype;
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "actual Subtype=0x%x\n", sUserDebugState.Subtype);
/* Update new 'DebugState' in the Adapter */
Adapter->stDebugState.type |= sUserDebugState.Type;
/* Subtype: A bitmap of 32 bits for Subtype per Type.
* Valid indexes in 'subtype' array: 1,2,4,8
* corresponding to valid Type values. Hence we can use the 'Type' field
* as the index value, ignoring the array entries 0,3,5,6,7 !
*/
if (sUserDebugState.OnOff)
Adapter->stDebugState.subtype[sUserDebugState.Type] |= sUserDebugState.Subtype;
else
Adapter->stDebugState.subtype[sUserDebugState.Type] &= ~sUserDebugState.Subtype;
BCM_SHOW_DEBUG_BITMAP(Adapter);
}
#endif
break;
case IOCTL_BCM_NVM_READ:
case IOCTL_BCM_NVM_WRITE: {
struct bcm_nvm_readwrite stNVMReadWrite;
PUCHAR pReadData = NULL;
ULONG ulDSDMagicNumInUsrBuff = 0;
struct timeval tv0, tv1;
memset(&tv0, 0, sizeof(struct timeval));
memset(&tv1, 0, sizeof(struct timeval));
if ((Adapter->eNVMType == NVM_FLASH) && (Adapter->uiFlashLayoutMajorVersion == 0)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "The Flash Control Section is Corrupted. Hence Rejection on NVM Read/Write\n");
return -EFAULT;
}
if (IsFlash2x(Adapter)) {
if ((Adapter->eActiveDSD != DSD0) &&
(Adapter->eActiveDSD != DSD1) &&
(Adapter->eActiveDSD != DSD2)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "No DSD is active..hence NVM Command is blocked");
return STATUS_FAILURE;
}
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&stNVMReadWrite,
(IOCTL_BCM_NVM_READ == cmd) ? IoBuffer.OutputBuffer : IoBuffer.InputBuffer,
sizeof(struct bcm_nvm_readwrite)))
return -EFAULT;
/*
* Deny the access if the offset crosses the cal area limit.
*/
if (stNVMReadWrite.uiNumBytes > Adapter->uiNVMDSDSize)
return STATUS_FAILURE;
if (stNVMReadWrite.uiOffset > Adapter->uiNVMDSDSize - stNVMReadWrite.uiNumBytes) {
/* BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Can't allow access beyond NVM Size: 0x%x 0x%x\n", stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); */
return STATUS_FAILURE;
}
pReadData = memdup_user(stNVMReadWrite.pBuffer,
stNVMReadWrite.uiNumBytes);
if (IS_ERR(pReadData))
return PTR_ERR(pReadData);
do_gettimeofday(&tv0);
if (IOCTL_BCM_NVM_READ == cmd) {
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return -EACCES;
}
Status = BeceemNVMRead(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes);
up(&Adapter->NVMRdmWrmLock);
if (Status != STATUS_SUCCESS) {
kfree(pReadData);
return Status;
}
if (copy_to_user(stNVMReadWrite.pBuffer, pReadData, stNVMReadWrite.uiNumBytes)) {
kfree(pReadData);
return -EFAULT;
}
} else {
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return -EACCES;
}
Adapter->bHeaderChangeAllowed = TRUE;
if (IsFlash2x(Adapter)) {
/*
* New Requirement:-
* DSD section updation will be allowed in two case:-
* 1. if DSD sig is present in DSD header means dongle is ok and updation is fruitfull
* 2. if point 1 failes then user buff should have DSD sig. this point ensures that if dongle is
* corrupted then user space program first modify the DSD header with valid DSD sig so
* that this as well as further write may be worthwhile.
*
* This restriction has been put assuming that if DSD sig is corrupted, DSD
* data won't be considered valid.
*/
Status = BcmFlash2xCorruptSig(Adapter, Adapter->eActiveDSD);
if (Status != STATUS_SUCCESS) {
if (((stNVMReadWrite.uiOffset + stNVMReadWrite.uiNumBytes) != Adapter->uiNVMDSDSize) ||
(stNVMReadWrite.uiNumBytes < SIGNATURE_SIZE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DSD Sig is present neither in Flash nor User provided Input..");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return Status;
}
ulDSDMagicNumInUsrBuff = ntohl(*(PUINT)(pReadData + stNVMReadWrite.uiNumBytes - SIGNATURE_SIZE));
if (ulDSDMagicNumInUsrBuff != DSD_IMAGE_MAGIC_NUMBER) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DSD Sig is present neither in Flash nor User provided Input..");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return Status;
}
}
}
Status = BeceemNVMWrite(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes, stNVMReadWrite.bVerify);
if (IsFlash2x(Adapter))
BcmFlash2xWriteSig(Adapter, Adapter->eActiveDSD);
Adapter->bHeaderChangeAllowed = FALSE;
up(&Adapter->NVMRdmWrmLock);
if (Status != STATUS_SUCCESS) {
kfree(pReadData);
return Status;
}
}
do_gettimeofday(&tv1);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, " timetaken by Write/read :%ld msec\n", (tv1.tv_sec - tv0.tv_sec)*1000 + (tv1.tv_usec - tv0.tv_usec)/1000);
kfree(pReadData);
return STATUS_SUCCESS;
}
case IOCTL_BCM_FLASH2X_SECTION_READ: {
struct bcm_flash2x_readwrite sFlash2xRead = {0};
PUCHAR pReadBuff = NULL ;
UINT NOB = 0;
UINT BuffSize = 0;
UINT ReadBytes = 0;
UINT ReadOffset = 0;
void __user *OutPutBuff;
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_FLASH2X_SECTION_READ Called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
/* Reading FLASH 2.x READ structure */
if (copy_from_user(&sFlash2xRead, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite)))
return -EFAULT;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.Section :%x", sFlash2xRead.Section);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.offset :%x", sFlash2xRead.offset);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.numOfBytes :%x", sFlash2xRead.numOfBytes);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.bVerify :%x\n", sFlash2xRead.bVerify);
/* This was internal to driver for raw read. now it has ben exposed to user space app. */
if (validateFlash2xReadWrite(Adapter, &sFlash2xRead) == FALSE)
return STATUS_FAILURE;
NOB = sFlash2xRead.numOfBytes;
if (NOB > Adapter->uiSectorSize)
BuffSize = Adapter->uiSectorSize;
else
BuffSize = NOB;
ReadOffset = sFlash2xRead.offset ;
OutPutBuff = IoBuffer.OutputBuffer;
pReadBuff = (PCHAR)kzalloc(BuffSize , GFP_KERNEL);
if (pReadBuff == NULL) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory allocation failed for Flash 2.x Read Structure");
return -ENOMEM;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
return -EACCES;
}
while (NOB) {
if (NOB > Adapter->uiSectorSize)
ReadBytes = Adapter->uiSectorSize;
else
ReadBytes = NOB;
/* Reading the data from Flash 2.x */
Status = BcmFlash2xBulkRead(Adapter, (PUINT)pReadBuff, sFlash2xRead.Section, ReadOffset, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Flash 2x read err with Status :%d", Status);
break;
}
BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes);
Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Copy to use failed with status :%d", Status);
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
return -EFAULT;
}
NOB = NOB - ReadBytes;
if (NOB) {
ReadOffset = ReadOffset + ReadBytes;
OutPutBuff = OutPutBuff + ReadBytes ;
}
}
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
}
break;
case IOCTL_BCM_FLASH2X_SECTION_WRITE: {
struct bcm_flash2x_readwrite sFlash2xWrite = {0};
PUCHAR pWriteBuff;
void __user *InputAddr;
UINT NOB = 0;
UINT BuffSize = 0;
UINT WriteOffset = 0;
UINT WriteBytes = 0;
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
/* First make this False so that we can enable the Sector Permission Check in BeceemFlashBulkWrite */
Adapter->bAllDSDWriteAllow = FALSE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_FLASH2X_SECTION_WRITE Called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
/* Reading FLASH 2.x READ structure */
if (copy_from_user(&sFlash2xWrite, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite)))
return -EFAULT;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.Section :%x", sFlash2xWrite.Section);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.offset :%d", sFlash2xWrite.offset);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.numOfBytes :%x", sFlash2xWrite.numOfBytes);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.bVerify :%x\n", sFlash2xWrite.bVerify);
if ((sFlash2xWrite.Section != VSA0) && (sFlash2xWrite.Section != VSA1) && (sFlash2xWrite.Section != VSA2)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Only VSA write is allowed");
return -EINVAL;
}
if (validateFlash2xReadWrite(Adapter, &sFlash2xWrite) == FALSE)
return STATUS_FAILURE;
InputAddr = sFlash2xWrite.pDataBuff;
WriteOffset = sFlash2xWrite.offset;
NOB = sFlash2xWrite.numOfBytes;
if (NOB > Adapter->uiSectorSize)
BuffSize = Adapter->uiSectorSize;
else
BuffSize = NOB ;
pWriteBuff = kmalloc(BuffSize, GFP_KERNEL);
if (pWriteBuff == NULL)
return -ENOMEM;
/* extracting the remainder of the given offset. */
WriteBytes = Adapter->uiSectorSize;
if (WriteOffset % Adapter->uiSectorSize)
WriteBytes = Adapter->uiSectorSize - (WriteOffset % Adapter->uiSectorSize);
if (NOB < WriteBytes)
WriteBytes = NOB;
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pWriteBuff);
return -EACCES;
}
BcmFlash2xCorruptSig(Adapter, sFlash2xWrite.Section);
do {
Status = copy_from_user(pWriteBuff, InputAddr, WriteBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy to user failed with status :%d", Status);
up(&Adapter->NVMRdmWrmLock);
kfree(pWriteBuff);
return -EFAULT;
}
BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pWriteBuff, WriteBytes);
/* Writing the data from Flash 2.x */
Status = BcmFlash2xBulkWrite(Adapter, (PUINT)pWriteBuff, sFlash2xWrite.Section, WriteOffset, WriteBytes, sFlash2xWrite.bVerify);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash 2x read err with Status :%d", Status);
break;
}
NOB = NOB - WriteBytes;
if (NOB) {
WriteOffset = WriteOffset + WriteBytes;
InputAddr = InputAddr + WriteBytes;
if (NOB > Adapter->uiSectorSize)
WriteBytes = Adapter->uiSectorSize;
else
WriteBytes = NOB;
}
} while (NOB > 0);
BcmFlash2xWriteSig(Adapter, sFlash2xWrite.Section);
up(&Adapter->NVMRdmWrmLock);
kfree(pWriteBuff);
}
break;
case IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP: {
struct bcm_flash2x_bitmap *psFlash2xBitMap;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP Called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength != sizeof(struct bcm_flash2x_bitmap))
return -EINVAL;
psFlash2xBitMap = kzalloc(sizeof(struct bcm_flash2x_bitmap), GFP_KERNEL);
if (psFlash2xBitMap == NULL) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory is not available");
return -ENOMEM;
}
/* Reading the Flash Sectio Bit map */
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(psFlash2xBitMap);
return -EACCES;
}
BcmGetFlash2xSectionalBitMap(Adapter, psFlash2xBitMap);
up(&Adapter->NVMRdmWrmLock);
if (copy_to_user(IoBuffer.OutputBuffer, psFlash2xBitMap, sizeof(struct bcm_flash2x_bitmap))) {
kfree(psFlash2xBitMap);
return -EFAULT;
}
kfree(psFlash2xBitMap);
}
break;
case IOCTL_BCM_SET_ACTIVE_SECTION: {
enum bcm_flash2x_section_val eFlash2xSectionVal = 0;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SET_ACTIVE_SECTION Called");
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed");
return -EFAULT;
}
Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of flash section val failed");
return -EFAULT;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
return -EACCES;
}
Status = BcmSetActiveSection(Adapter, eFlash2xSectionVal);
if (Status)
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Failed to make it's priority Highest. Status %d", Status);
up(&Adapter->NVMRdmWrmLock);
}
break;
case IOCTL_BCM_IDENTIFY_ACTIVE_SECTION: {
/* Right Now we are taking care of only DSD */
Adapter->bAllDSDWriteAllow = FALSE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_IDENTIFY_ACTIVE_SECTION called");
Status = STATUS_SUCCESS;
}
break;
case IOCTL_BCM_COPY_SECTION: {
struct bcm_flash2x_copy_section sCopySectStrut = {0};
Status = STATUS_SUCCESS;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_COPY_SECTION Called");
Adapter->bAllDSDWriteAllow = FALSE;
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed Status :%d", Status);
return -EFAULT;
}
Status = copy_from_user(&sCopySectStrut, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_copy_section));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of Copy_Section_Struct failed with Status :%d", Status);
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Source SEction :%x", sCopySectStrut.SrcSection);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Destination SEction :%x", sCopySectStrut.DstSection);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "offset :%x", sCopySectStrut.offset);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "NOB :%x", sCopySectStrut.numOfBytes);
if (IsSectionExistInFlash(Adapter, sCopySectStrut.SrcSection) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Source Section<%x> does not exixt in Flash ", sCopySectStrut.SrcSection);
return -EINVAL;
}
if (IsSectionExistInFlash(Adapter, sCopySectStrut.DstSection) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Destinatio Section<%x> does not exixt in Flash ", sCopySectStrut.DstSection);
return -EINVAL;
}
if (sCopySectStrut.SrcSection == sCopySectStrut.DstSection) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Source and Destination section should be different");
return -EINVAL;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
return -EACCES;
}
if (sCopySectStrut.SrcSection == ISO_IMAGE1 || sCopySectStrut.SrcSection == ISO_IMAGE2) {
if (IsNonCDLessDevice(Adapter)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device is Non-CDLess hence won't have ISO !!");
Status = -EINVAL;
} else if (sCopySectStrut.numOfBytes == 0) {
Status = BcmCopyISO(Adapter, sCopySectStrut);
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Partial Copy of ISO section is not Allowed..");
Status = STATUS_FAILURE;
}
up(&Adapter->NVMRdmWrmLock);
return Status;
}
Status = BcmCopySection(Adapter, sCopySectStrut.SrcSection,
sCopySectStrut.DstSection, sCopySectStrut.offset, sCopySectStrut.numOfBytes);
up(&Adapter->NVMRdmWrmLock);
}
break;
case IOCTL_BCM_GET_FLASH_CS_INFO: {
Status = STATUS_SUCCESS;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, " IOCTL_BCM_GET_FLASH_CS_INFO Called");
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed");
return -EFAULT;
}
if (Adapter->eNVMType != NVM_FLASH) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Connected device does not have flash");
Status = -EINVAL;
break;
}
if (IsFlash2x(Adapter) == TRUE) {
if (IoBuffer.OutputLength < sizeof(struct bcm_flash2x_cs_info))
return -EINVAL;
if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlash2xCSInfo, sizeof(struct bcm_flash2x_cs_info)))
return -EFAULT;
} else {
if (IoBuffer.OutputLength < sizeof(struct bcm_flash_cs_info))
return -EINVAL;
if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlashCSInfo, sizeof(struct bcm_flash_cs_info)))
return -EFAULT;
}
}
break;
case IOCTL_BCM_SELECT_DSD: {
UINT SectOfset = 0;
enum bcm_flash2x_section_val eFlash2xSectionVal;
eFlash2xSectionVal = NO_SECTION_VAL;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SELECT_DSD Called");
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed");
return -EFAULT;
}
Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of flash section val failed");
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Read Section :%d", eFlash2xSectionVal);
if ((eFlash2xSectionVal != DSD0) &&
(eFlash2xSectionVal != DSD1) &&
(eFlash2xSectionVal != DSD2)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Passed section<%x> is not DSD section", eFlash2xSectionVal);
return STATUS_FAILURE;
}
SectOfset = BcmGetSectionValStartOffset(Adapter, eFlash2xSectionVal);
if (SectOfset == INVALID_OFFSET) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Provided Section val <%d> does not exixt in Flash 2.x", eFlash2xSectionVal);
return -EINVAL;
}
Adapter->bAllDSDWriteAllow = TRUE;
Adapter->ulFlashCalStart = SectOfset;
Adapter->eActiveDSD = eFlash2xSectionVal;
}
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_NVM_RAW_READ: {
struct bcm_nvm_readwrite stNVMRead;
INT NOB ;
INT BuffSize ;
INT ReadOffset = 0;
UINT ReadBytes = 0 ;
PUCHAR pReadBuff;
void __user *OutPutBuff;
if (Adapter->eNVMType != NVM_FLASH) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "NVM TYPE is not Flash");
return -EINVAL;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "copy_from_user 1 failed\n");
return -EFAULT;
}
if (copy_from_user(&stNVMRead, IoBuffer.OutputBuffer, sizeof(struct bcm_nvm_readwrite)))
return -EFAULT;
NOB = stNVMRead.uiNumBytes;
/* In Raw-Read max Buff size : 64MB */
if (NOB > DEFAULT_BUFF_SIZE)
BuffSize = DEFAULT_BUFF_SIZE;
else
BuffSize = NOB;
ReadOffset = stNVMRead.uiOffset;
OutPutBuff = stNVMRead.pBuffer;
pReadBuff = kzalloc(BuffSize , GFP_KERNEL);
if (pReadBuff == NULL) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory allocation failed for Flash 2.x Read Structure");
Status = -ENOMEM;
break;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
kfree(pReadBuff);
up(&Adapter->NVMRdmWrmLock);
return -EACCES;
}
Adapter->bFlashRawRead = TRUE;
while (NOB) {
if (NOB > DEFAULT_BUFF_SIZE)
ReadBytes = DEFAULT_BUFF_SIZE;
else
ReadBytes = NOB;
/* Reading the data from Flash 2.x */
Status = BeceemNVMRead(Adapter, (PUINT)pReadBuff, ReadOffset, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash 2x read err with Status :%d", Status);
break;
}
BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes);
Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy to use failed with status :%d", Status);
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
return -EFAULT;
}
NOB = NOB - ReadBytes;
if (NOB) {
ReadOffset = ReadOffset + ReadBytes;
OutPutBuff = OutPutBuff + ReadBytes;
}
}
Adapter->bFlashRawRead = FALSE;
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
break;
}
case IOCTL_BCM_CNTRLMSG_MASK: {
ULONG RxCntrlMsgBitMask = 0;
/* Copy Ioctl Buffer structure */
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "copy of Ioctl buffer is failed from user space");
return -EFAULT;
}
if (IoBuffer.InputLength != sizeof(unsigned long)) {
Status = -EINVAL;
break;
}
Status = copy_from_user(&RxCntrlMsgBitMask, IoBuffer.InputBuffer, IoBuffer.InputLength);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "copy of control bit mask failed from user space");
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\n Got user defined cntrl msg bit mask :%lx", RxCntrlMsgBitMask);
pTarang->RxCntrlMsgBitMask = RxCntrlMsgBitMask;
}
break;
case IOCTL_BCM_GET_DEVICE_DRIVER_INFO: {
struct bcm_driver_info DevInfo;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Called IOCTL_BCM_GET_DEVICE_DRIVER_INFO\n");
DevInfo.MaxRDMBufferSize = BUFFER_4K;
DevInfo.u32DSDStartOffset = EEPROM_CALPARAM_START;
DevInfo.u32RxAlignmentCorrection = 0;
DevInfo.u32NVMType = Adapter->eNVMType;
DevInfo.u32InterfaceType = BCM_USB;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength < sizeof(DevInfo))
return -EINVAL;
if (copy_to_user(IoBuffer.OutputBuffer, &DevInfo, sizeof(DevInfo)))
return -EFAULT;
}
break;
case IOCTL_BCM_TIME_SINCE_NET_ENTRY: {
struct bcm_time_elapsed stTimeElapsedSinceNetEntry = {0};
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_TIME_SINCE_NET_ENTRY called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength < sizeof(struct bcm_time_elapsed))
return -EINVAL;
stTimeElapsedSinceNetEntry.ul64TimeElapsedSinceNetEntry = get_seconds() - Adapter->liTimeSinceLastNetEntry;
if (copy_to_user(IoBuffer.OutputBuffer, &stTimeElapsedSinceNetEntry, sizeof(struct bcm_time_elapsed)))
return -EFAULT;
}
break;
case IOCTL_CLOSE_NOTIFICATION:
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_CLOSE_NOTIFICATION");
break;
default:
pr_info(DRV_NAME ": unknown ioctl cmd=%#x\n", cmd);
Status = STATUS_FAILURE;
break;
}
return Status;
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: The bcm_char_ioctl function in drivers/staging/bcm/Bcmchar.c in the Linux kernel before 3.12 does not initialize a certain data structure, which allows local users to obtain sensitive information from kernel memory via an IOCTL_BCM_GET_DEVICE_DRIVER_INFO ioctl call.
Commit Message: Staging: bcm: info leak in ioctl
The DevInfo.u32Reserved[] array isn't initialized so it leaks kernel
information to user space.
Reported-by: Nico Golde <[email protected]>
Reported-by: Fabian Yamaguchi <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]> | Low | 165,962 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static int __perf_event_overflow(struct perf_event *event, int nmi,
int throttle, struct perf_sample_data *data,
struct pt_regs *regs)
{
int events = atomic_read(&event->event_limit);
struct hw_perf_event *hwc = &event->hw;
int ret = 0;
/*
* Non-sampling counters might still use the PMI to fold short
* hardware counters, ignore those.
*/
if (unlikely(!is_sampling_event(event)))
return 0;
if (unlikely(hwc->interrupts >= max_samples_per_tick)) {
if (throttle) {
hwc->interrupts = MAX_INTERRUPTS;
perf_log_throttle(event, 0);
ret = 1;
}
} else
hwc->interrupts++;
if (event->attr.freq) {
u64 now = perf_clock();
s64 delta = now - hwc->freq_time_stamp;
hwc->freq_time_stamp = now;
if (delta > 0 && delta < 2*TICK_NSEC)
perf_adjust_period(event, delta, hwc->last_period);
}
/*
* XXX event_limit might not quite work as expected on inherited
* events
*/
event->pending_kill = POLL_IN;
if (events && atomic_dec_and_test(&event->event_limit)) {
ret = 1;
event->pending_kill = POLL_HUP;
if (nmi) {
event->pending_disable = 1;
irq_work_queue(&event->pending);
} else
perf_event_disable(event);
}
if (event->overflow_handler)
event->overflow_handler(event, nmi, data, regs);
else
perf_event_output(event, nmi, data, regs);
if (event->fasync && event->pending_kill) {
if (nmi) {
event->pending_wakeup = 1;
irq_work_queue(&event->pending);
} else
perf_event_wakeup(event);
}
return ret;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-399
Summary: The Performance Events subsystem in the Linux kernel before 3.1 does not properly handle event overflows associated with PERF_COUNT_SW_CPU_CLOCK events, which allows local users to cause a denial of service (system hang) via a crafted application.
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]> | Low | 165,826 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: CompositorFrameMetadata LayerTreeHostImpl::MakeCompositorFrameMetadata() const {
CompositorFrameMetadata metadata;
metadata.device_scale_factor = active_tree_->painted_device_scale_factor() *
active_tree_->device_scale_factor();
metadata.page_scale_factor = active_tree_->current_page_scale_factor();
metadata.scrollable_viewport_size = active_tree_->ScrollableViewportSize();
metadata.root_layer_size = active_tree_->ScrollableSize();
metadata.min_page_scale_factor = active_tree_->min_page_scale_factor();
metadata.max_page_scale_factor = active_tree_->max_page_scale_factor();
metadata.top_controls_height =
browser_controls_offset_manager_->TopControlsHeight();
metadata.top_controls_shown_ratio =
browser_controls_offset_manager_->TopControlsShownRatio();
metadata.bottom_controls_height =
browser_controls_offset_manager_->BottomControlsHeight();
metadata.bottom_controls_shown_ratio =
browser_controls_offset_manager_->BottomControlsShownRatio();
metadata.root_background_color = active_tree_->background_color();
active_tree_->GetViewportSelection(&metadata.selection);
if (OuterViewportScrollLayer()) {
metadata.root_overflow_x_hidden =
!OuterViewportScrollLayer()->user_scrollable_horizontal();
metadata.root_overflow_y_hidden =
!OuterViewportScrollLayer()->user_scrollable_vertical();
}
if (GetDrawMode() == DRAW_MODE_RESOURCELESS_SOFTWARE) {
metadata.is_resourceless_software_draw_with_scroll_or_animation =
IsActivelyScrolling() || mutator_host_->NeedsTickAnimations();
}
for (LayerImpl* surface_layer : active_tree_->SurfaceLayers()) {
SurfaceLayerImpl* surface_layer_impl =
static_cast<SurfaceLayerImpl*>(surface_layer);
metadata.referenced_surfaces.push_back(
surface_layer_impl->primary_surface_info().id());
if (surface_layer_impl->fallback_surface_info().is_valid()) {
metadata.referenced_surfaces.push_back(
surface_layer_impl->fallback_surface_info().id());
}
}
if (!InnerViewportScrollLayer())
return metadata;
metadata.root_overflow_x_hidden |=
!InnerViewportScrollLayer()->user_scrollable_horizontal();
metadata.root_overflow_y_hidden |=
!InnerViewportScrollLayer()->user_scrollable_vertical();
metadata.root_scroll_offset =
gfx::ScrollOffsetToVector2dF(active_tree_->TotalScrollOffset());
return metadata;
}
Vulnerability Type:
CWE ID: CWE-362
Summary: A race condition in navigation in Google Chrome prior to 58.0.3029.81 for Linux, Windows, and Mac allowed a remote attacker to spoof the contents of the Omnibox (URL bar) via a crafted HTML page.
Commit Message: (Reland) Discard compositor frames from unloaded web content
This is a reland of https://codereview.chromium.org/2707243005/ with a
small change to fix an uninitialized memory error that fails on MSAN
bots.
BUG=672847
[email protected], [email protected]
CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2731283003
Cr-Commit-Position: refs/heads/master@{#454954} | High | 172,396 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: base::SharedMemoryHandle CreateMSKPInSharedMemory() {
SkDynamicMemoryWStream stream;
sk_sp<SkDocument> doc = SkMakeMultiPictureDocument(&stream);
cc::SkiaPaintCanvas canvas(doc->beginPage(800, 600));
SkRect rect = SkRect::MakeXYWH(10, 10, 250, 250);
cc::PaintFlags flags;
flags.setAntiAlias(false);
flags.setColor(SK_ColorRED);
flags.setStyle(cc::PaintFlags::kFill_Style);
canvas.drawRect(rect, flags);
doc->endPage();
doc->close();
size_t len = stream.bytesWritten();
base::SharedMemoryCreateOptions options;
options.size = len;
options.share_read_only = true;
base::SharedMemory shared_memory;
if (shared_memory.Create(options) && shared_memory.Map(len)) {
stream.copyTo(shared_memory.memory());
return base::SharedMemory::DuplicateHandle(shared_memory.handle());
}
return base::SharedMemoryHandle();
}
Vulnerability Type:
CWE ID: CWE-787
Summary: Incorrect use of mojo::WrapSharedMemoryHandle in Mojo in Google Chrome prior to 65.0.3325.146 allowed a remote attacker who had compromised the renderer process to perform an out of bounds memory write via a crafted HTML page.
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
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: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268} | Medium | 172,857 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void PrintViewManager::PrintPreviewDone() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_NE(NOT_PREVIEWING, print_preview_state_);
if (print_preview_state_ == SCRIPTED_PREVIEW) {
auto& map = g_scripted_print_preview_closure_map.Get();
auto it = map.find(scripted_print_preview_rph_);
CHECK(it != map.end());
it->second.Run();
map.erase(it);
scripted_print_preview_rph_ = nullptr;
}
print_preview_state_ = NOT_PREVIEWING;
print_preview_rfh_ = nullptr;
}
Vulnerability Type:
CWE ID: CWE-125
Summary: A use after free in printing in Google Chrome prior to 57.0.2987.133 for Linux and Windows allowed a remote attacker to perform an out of bounds memory read via a crafted HTML page.
Commit Message: Properly clean up in PrintViewManager::RenderFrameCreated().
BUG=694382,698622
Review-Url: https://codereview.chromium.org/2742853003
Cr-Commit-Position: refs/heads/master@{#457363} | Medium | 172,404 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: void HTMLMediaElement::NoneSupported(const String& message) {
BLINK_MEDIA_LOG << "NoneSupported(" << (void*)this << ", message='" << message
<< "')";
StopPeriodicTimers();
load_state_ = kWaitingForSource;
current_source_node_ = nullptr;
error_ = MediaError::Create(MediaError::kMediaErrSrcNotSupported, message);
ForgetResourceSpecificTracks();
SetNetworkState(kNetworkNoSource);
UpdateDisplayState();
ScheduleEvent(EventTypeNames::error);
ScheduleRejectPlayPromises(kNotSupportedError);
CloseMediaSource();
SetShouldDelayLoadEvent(false);
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
}
Vulnerability Type: +Info
CWE ID: CWE-200
Summary: Information leak in media engine in Google Chrome prior to 68.0.3440.75 allowed a remote attacker to leak cross-origin data via a crafted HTML page.
Commit Message: defeat cors attacks on audio/video tags
Neutralize error messages and fire no progress events
until media metadata has been loaded for media loaded
from cross-origin locations.
Bug: 828265, 826187
Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6
Reviewed-on: https://chromium-review.googlesource.com/1015794
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Dale Curtis <[email protected]>
Commit-Queue: Fredrik Hubinette <[email protected]>
Cr-Commit-Position: refs/heads/master@{#557312} | Medium | 173,163 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static void snd_timer_check_master(struct snd_timer_instance *master)
{
struct snd_timer_instance *slave, *tmp;
/* check all pending slaves */
list_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) {
if (slave->slave_class == master->slave_class &&
slave->slave_id == master->slave_id) {
list_move_tail(&slave->open_list, &master->slave_list_head);
spin_lock_irq(&slave_active_lock);
slave->master = master;
slave->timer = master->timer;
if (slave->flags & SNDRV_TIMER_IFLG_RUNNING)
list_add_tail(&slave->active_list,
&master->slave_active_head);
spin_unlock_irq(&slave_active_lock);
}
}
}
Vulnerability Type: DoS
CWE ID: CWE-20
Summary: sound/core/timer.c in the Linux kernel before 4.4.1 retains certain linked lists after a close or stop action, which allows local users to cause a denial of service (system crash) via a crafted ioctl call, related to the (1) snd_timer_close and (2) _snd_timer_stop functions.
Commit Message: ALSA: timer: Harden slave timer list handling
A slave timer instance might be still accessible in a racy way while
operating the master instance as it lacks of locking. Since the
master operation is mostly protected with timer->lock, we should cope
with it while changing the slave instance, too. Also, some linked
lists (active_list and ack_list) of slave instances aren't unlinked
immediately at stopping or closing, and this may lead to unexpected
accesses.
This patch tries to address these issues. It adds spin lock of
timer->lock (either from master or slave, which is equivalent) in a
few places. For avoiding a deadlock, we ensure that the global
slave_active_lock is always locked at first before each timer lock.
Also, ack and active_list of slave instances are properly unlinked at
snd_timer_stop() and snd_timer_close().
Last but not least, remove the superfluous call of _snd_timer_stop()
at removing slave links. This is a noop, and calling it may confuse
readers wrt locking. Further cleanup will follow in a later patch.
Actually we've got reports of use-after-free by syzkaller fuzzer, and
this hopefully fixes these issues.
Reported-by: Dmitry Vyukov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]> | Low | 167,401 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: nfssvc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readlinkargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
args->buffer = page_address(*(rqstp->rq_next_page++));
return xdr_argsize_check(rqstp, p);
}
Vulnerability Type: DoS
CWE ID: CWE-404
Summary: The NFSv4 implementation in the Linux kernel through 4.11.1 allows local users to cause a denial of service (resource consumption) by leveraging improper channel callback shutdown when unmounting an NFSv4 filesystem, aka a *module reference and kernel daemon* leak.
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
... | Low | 168,152 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: monitor_apply_keystate(struct monitor *pmonitor)
{
struct ssh *ssh = active_state; /* XXX */
struct kex *kex;
int r;
debug3("%s: packet_set_state", __func__);
if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
fatal("%s: packet_set_state: %s", __func__, ssh_err(r));
sshbuf_free(child_state);
child_state = NULL;
if ((kex = ssh->kex) != NULL) {
/* XXX set callbacks */
#ifdef WITH_OPENSSL
kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
#endif
kex->kex[KEX_C25519_SHA256] = kexc25519_server;
kex->load_host_public_key=&get_hostkey_public_by_type;
kex->load_host_private_key=&get_hostkey_private_by_type;
kex->host_key_index=&get_hostkey_index;
kex->sign = sshd_hostkey_sign;
}
/* Update with new address */
if (options.compression) {
ssh_packet_set_compress_hooks(ssh, pmonitor->m_zlib,
(ssh_packet_comp_alloc_func *)mm_zalloc,
(ssh_packet_comp_free_func *)mm_zfree);
}
}
Vulnerability Type: Overflow +Priv
CWE ID: CWE-119
Summary: The shared memory manager (associated with pre-authentication compression) in sshd in OpenSSH before 7.4 does not ensure that a bounds check is enforced by all compilers, which might allows local users to gain privileges by leveraging access to a sandboxed privilege-separation process, related to the m_zback and m_zlib data structures.
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years. | Low | 168,648 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: char* _single_string_alloc_and_copy( LPCWSTR in )
{
char *chr;
int len = 0;
if ( !in )
{
return in;
}
while ( in[ len ] != 0 )
{
len ++;
}
chr = malloc( len + 1 );
len = 0;
while ( in[ len ] != 0 )
{
chr[ len ] = 0xFF & in[ len ];
len ++;
}
chr[ len ++ ] = '\0';
return chr;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The SQLWriteFileDSN function in odbcinst/SQLWriteFileDSN.c in unixODBC 2.3.5 has strncpy arguments in the wrong order, which allows attackers to cause a denial of service or possibly have unspecified other impact.
Commit Message: New Pre Source | Low | 169,315 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static int enum_dir(sc_path_t path, int depth)
{
sc_file_t *file;
int r, file_type;
u8 files[SC_MAX_APDU_BUFFER_SIZE];
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_select_file(card, &path, &file);
sc_unlock(card);
if (r) {
fprintf(stderr, "SELECT FILE failed: %s\n", sc_strerror(r));
return 1;
}
print_file(card, file, &path, depth);
file_type = file->type;
sc_file_free(file);
if (file_type == SC_FILE_TYPE_DF) {
int i;
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_list_files(card, files, sizeof(files));
sc_unlock(card);
if (r < 0) {
fprintf(stderr, "sc_list_files() failed: %s\n", sc_strerror(r));
return 1;
}
if (r == 0) {
printf("Empty directory\n");
} else
for (i = 0; i < r/2; i++) {
sc_path_t tmppath;
memset(&tmppath, 0, sizeof(tmppath));
memcpy(&tmppath, &path, sizeof(path));
memcpy(tmppath.value + tmppath.len, files + 2*i, 2);
tmppath.len += 2;
enum_dir(tmppath, depth + 1);
}
}
return 0;
}
Vulnerability Type:
CWE ID: CWE-125
Summary: Various out of bounds reads when handling responses in OpenSC before 0.19.0-rc1 could be used by attackers able to supply crafted smartcards to potentially crash the opensc library using programs.
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes. | Low | 169,069 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */
{
/*
This is how the time string is formatted:
snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100,
ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec);
*/
time_t ret;
struct tm thetime;
char * strbuf;
char * thestr;
long gmadjust = 0;
if (timestr->length < 13) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "extension author too lazy to parse %s correctly", timestr->data);
return (time_t)-1;
}
strbuf = estrdup((char *)timestr->data);
memset(&thetime, 0, sizeof(thetime));
/* we work backwards so that we can use atoi more easily */
thestr = strbuf + timestr->length - 3;
thetime.tm_sec = atoi(thestr);
*thestr = '\0';
thetime.tm_mon = atoi(thestr)-1;
*thestr = '\0';
thestr -= 2;
thetime.tm_year = atoi(thestr);
if (thetime.tm_year < 68) {
thetime.tm_year += 100;
}
thetime.tm_isdst = -1;
ret = mktime(&thetime);
#if HAVE_TM_GMTOFF
gmadjust = thetime.tm_gmtoff;
#else
/*
** If correcting for daylight savings time, we set the adjustment to
** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and
** set the adjustment to the main timezone + 3600 seconds.
*/
gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone + 3600);
#endif
ret += gmadjust;
efree(strbuf);
return ret;
}
/* }}} */
Vulnerability Type: DoS Exec Code Overflow Mem. Corr.
CWE ID: CWE-119
Summary: The asn1_time_to_time_t function in ext/openssl/openssl.c in PHP before 5.3.28, 5.4.x before 5.4.23, and 5.5.x before 5.5.7 does not properly parse (1) notBefore and (2) notAfter timestamps in X.509 certificates, which allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted certificate that is not properly handled by the openssl_x509_parse function.
Commit Message: | Low | 164,568 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: PepperDeviceEnumerationHostHelper::PepperDeviceEnumerationHostHelper(
ppapi::host::ResourceHost* resource_host,
Delegate* delegate,
PP_DeviceType_Dev device_type,
const GURL& document_url)
: resource_host_(resource_host),
delegate_(delegate),
device_type_(device_type),
document_url_(document_url) {}
Vulnerability Type: DoS
CWE ID: CWE-399
Summary: Use-after-free vulnerability in the Pepper plugins in Google Chrome before 39.0.2171.65 allows remote attackers to cause a denial of service or possibly have unspecified other impact via crafted Flash content that triggers an attempted PepperMediaDeviceManager access outside of the object's lifetime.
Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr
Its lifetime is scoped to the RenderFrame, and it might go away before the
hosts that refer to it.
BUG=423030
Review URL: https://codereview.chromium.org/653243003
Cr-Commit-Position: refs/heads/master@{#299897} | Low | 171,604 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static v8::Handle<v8::Value> convert2Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.convert2");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(b*, , V8b::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8b::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->convert2();
return v8::Handle<v8::Value>();
}
Vulnerability Type:
CWE ID:
Summary: The browser native UI in Google Chrome before 17.0.963.83 does not require user confirmation before an unpacked extension installation, which allows user-assisted remote attackers to have an unspecified impact via a crafted 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 | Medium | 171,078 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static struct ucma_multicast* ucma_alloc_multicast(struct ucma_context *ctx)
{
struct ucma_multicast *mc;
mc = kzalloc(sizeof(*mc), GFP_KERNEL);
if (!mc)
return NULL;
mutex_lock(&mut);
mc->id = idr_alloc(&multicast_idr, mc, 0, 0, GFP_KERNEL);
mutex_unlock(&mut);
if (mc->id < 0)
goto error;
mc->ctx = ctx;
list_add_tail(&mc->list, &ctx->mc_list);
return mc;
error:
kfree(mc);
return NULL;
}
Vulnerability Type: DoS
CWE ID: CWE-416
Summary: drivers/infiniband/core/ucma.c in the Linux kernel through 4.17.11 allows ucma_leave_multicast to access a certain data structure after a cleanup step in ucma_process_join, which allows attackers to cause a denial of service (use-after-free).
Commit Message: infiniband: fix a possible use-after-free bug
ucma_process_join() will free the new allocated "mc" struct,
if there is any error after that, especially the copy_to_user().
But in parallel, ucma_leave_multicast() could find this "mc"
through idr_find() before ucma_process_join() frees it, since it
is already published.
So "mc" could be used in ucma_leave_multicast() after it is been
allocated and freed in ucma_process_join(), since we don't refcnt
it.
Fix this by separating "publish" from ID allocation, so that we
can get an ID first and publish it later after copy_to_user().
Fixes: c8f6a362bf3e ("RDMA/cma: Add multicast communication support")
Reported-by: Noam Rathaus <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]> | Low | 169,109 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: static void ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase,
unsigned ExifLength, int NestingLevel)
{
int de;
int a;
int NumDirEntries;
unsigned ThumbnailOffset = 0;
unsigned ThumbnailSize = 0;
char IndentString[25];
printf("ProcessExifDir");
if (NestingLevel > 4){
ErrNonfatal("Maximum directory nesting exceeded (corrupt exif header)", 0,0);
return;
}
memset(IndentString, ' ', 25);
IndentString[NestingLevel * 4] = '\0';
NumDirEntries = Get16u(DirStart);
#define DIR_ENTRY_ADDR(Start, Entry) (Start+2+12*(Entry))
{
unsigned char * DirEnd;
DirEnd = DIR_ENTRY_ADDR(DirStart, NumDirEntries);
if (DirEnd+4 > (OffsetBase+ExifLength)){
if (DirEnd+2 == OffsetBase+ExifLength || DirEnd == OffsetBase+ExifLength){
}else{
ErrNonfatal("Illegally sized exif subdirectory (%d entries)",NumDirEntries,0);
return;
}
}
if (DumpExifMap){
printf("Map: %05d-%05d: Directory\n",(int)(DirStart-OffsetBase), (int)(DirEnd+4-OffsetBase));
}
}
if (ShowTags){
printf("(dir has %d entries)\n",NumDirEntries);
}
for (de=0;de<NumDirEntries;de++){
int Tag, Format, Components;
unsigned char * ValuePtr;
int ByteCount;
unsigned char * DirEntry;
DirEntry = DIR_ENTRY_ADDR(DirStart, de);
Tag = Get16u(DirEntry);
Format = Get16u(DirEntry+2);
Components = Get32u(DirEntry+4);
if ((Format-1) >= NUM_FORMATS) {
ErrNonfatal("Illegal number format %d for tag %04x", Format, Tag);
continue;
}
if ((unsigned)Components > 0x10000){
ErrNonfatal("Illegal number of components %d for tag %04x", Components, Tag);
continue;
}
ByteCount = Components * BytesPerFormat[Format];
if (ByteCount > 4){
unsigned OffsetVal;
OffsetVal = Get32u(DirEntry+8);
if (OffsetVal+ByteCount > ExifLength){
ErrNonfatal("Illegal value pointer for tag %04x", Tag,0);
continue;
}
ValuePtr = OffsetBase+OffsetVal;
if (OffsetVal > ImageInfo.LargestExifOffset){
ImageInfo.LargestExifOffset = OffsetVal;
}
if (DumpExifMap){
printf("Map: %05d-%05d: Data for tag %04x\n",OffsetVal, OffsetVal+ByteCount, Tag);
}
}else{
ValuePtr = DirEntry+8;
}
if (Tag == TAG_MAKER_NOTE){
if (ShowTags){
printf("%s Maker note: ",IndentString);
}
ProcessMakerNote(ValuePtr, ByteCount, OffsetBase, ExifLength);
continue;
}
if (ShowTags){
for (a=0;;a++){
if (a >= (int)TAG_TABLE_SIZE){
printf("%s", IndentString);
printf(" Unknown Tag %04x Value = ", Tag);
break;
}
if (TagTable[a].Tag == Tag){
printf("%s", IndentString);
printf(" %s = ",TagTable[a].Desc);
break;
}
}
switch(Format){
case FMT_BYTE:
if(ByteCount>1){
printf("%.*ls\n", ByteCount/2, (wchar_t *)ValuePtr);
}else{
PrintFormatNumber(ValuePtr, Format, ByteCount);
printf("\n");
}
break;
case FMT_UNDEFINED:
case FMT_STRING:
{
printf("\"%s\"", ValuePtr);
}
break;
default:
PrintFormatNumber(ValuePtr, Format, ByteCount);
printf("\n");
}
}
switch(Tag){
case TAG_MAKE:
strncpy(ImageInfo.CameraMake, (char *)ValuePtr, ByteCount < 31 ? ByteCount : 31);
break;
case TAG_MODEL:
strncpy(ImageInfo.CameraModel, (char *)ValuePtr, ByteCount < 39 ? ByteCount : 39);
break;
case TAG_SUBSEC_TIME:
strlcpy(ImageInfo.SubSecTime, (char *)ValuePtr, sizeof(ImageInfo.SubSecTime));
break;
case TAG_SUBSEC_TIME_ORIG:
strlcpy(ImageInfo.SubSecTimeOrig, (char *)ValuePtr,
sizeof(ImageInfo.SubSecTimeOrig));
break;
case TAG_SUBSEC_TIME_DIG:
strlcpy(ImageInfo.SubSecTimeDig, (char *)ValuePtr,
sizeof(ImageInfo.SubSecTimeDig));
break;
case TAG_DATETIME_DIGITIZED:
strlcpy(ImageInfo.DigitizedTime, (char *)ValuePtr,
sizeof(ImageInfo.DigitizedTime));
if (ImageInfo.numDateTimeTags >= MAX_DATE_COPIES){
ErrNonfatal("More than %d date fields! This is nuts", MAX_DATE_COPIES, 0);
break;
}
ImageInfo.DateTimeOffsets[ImageInfo.numDateTimeTags++] =
(char *)ValuePtr - (char *)OffsetBase;
break;
case TAG_DATETIME_ORIGINAL:
strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19);
case TAG_DATETIME:
if (!isdigit(ImageInfo.DateTime[0])){
strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19);
}
if (ImageInfo.numDateTimeTags >= MAX_DATE_COPIES){
ErrNonfatal("More than %d date fields! This is nuts", MAX_DATE_COPIES, 0);
break;
}
ImageInfo.DateTimeOffsets[ImageInfo.numDateTimeTags++] =
(char *)ValuePtr - (char *)OffsetBase;
break;
case TAG_WINXP_COMMENT:
if (ImageInfo.Comments[0]){ // We already have a jpeg comment.
if (ShowTags) printf("Windows XP commend and other comment in header\n");
break; // Already have a windows comment, skip this one.
}
if (ByteCount > 1){
if (ByteCount > MAX_COMMENT_SIZE) ByteCount = MAX_COMMENT_SIZE;
memcpy(ImageInfo.Comments, ValuePtr, ByteCount);
ImageInfo.CommentWidchars = ByteCount/2;
}
break;
case TAG_USERCOMMENT:
if (ImageInfo.Comments[0]){ // We already have a jpeg comment.
if (ShowTags) printf("Multiple comments in exif header\n");
break; // Already have a windows comment, skip this one.
}
for (a=ByteCount;;){
a--;
if ((ValuePtr)[a] == ' '){
(ValuePtr)[a] = '\0';
}else{
break;
}
if (a == 0) break;
}
{
int msiz = ExifLength - (ValuePtr-OffsetBase);
if (msiz > ByteCount) msiz = ByteCount;
if (msiz > MAX_COMMENT_SIZE - 1) msiz = MAX_COMMENT_SIZE - 1;
if (msiz > 5 && memcmp(ValuePtr, "ASCII", 5) == 0) {
for (a = 5; a < 10 && a < msiz; a++) {
int c = (ValuePtr)[a];
if (c != '\0' && c != ' ') {
strncpy(ImageInfo.Comments,
(char *)ValuePtr + a, msiz - a);
break;
}
}
} else {
strncpy(ImageInfo.Comments, (char *)ValuePtr, msiz);
}
}
break;
case TAG_FNUMBER:
ImageInfo.ApertureFNumber = (float)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_APERTURE:
case TAG_MAXAPERTURE:
if (ImageInfo.ApertureFNumber == 0){
ImageInfo.ApertureFNumber
= (float)exp(ConvertAnyFormat(ValuePtr, Format)*log(2)*0.5);
}
break;
case TAG_FOCALLENGTH:
ImageInfo.FocalLength.num = Get32u(ValuePtr);
ImageInfo.FocalLength.denom = Get32u(4+(char *)ValuePtr);
break;
case TAG_SUBJECT_DISTANCE:
ImageInfo.Distance = (float)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_EXPOSURETIME:
ImageInfo.ExposureTime = (float)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_SHUTTERSPEED:
if (ImageInfo.ExposureTime == 0){
ImageInfo.ExposureTime
= (float)(1/exp(ConvertAnyFormat(ValuePtr, Format)*log(2)));
}
break;
case TAG_FLASH:
ImageInfo.FlashUsed=(int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_ORIENTATION:
if (NumOrientations >= 2){
ErrNonfatal("More than two orientation tags!",0,0);
break;
}
OrientationPtr[NumOrientations] = ValuePtr;
OrientationNumFormat[NumOrientations] = Format;
if (NumOrientations == 0){
ImageInfo.Orientation = (int)ConvertAnyFormat(ValuePtr, Format);
}
if (ImageInfo.Orientation < 0 || ImageInfo.Orientation > 8){
ErrNonfatal("Undefined rotation value %d", ImageInfo.Orientation, 0);
ImageInfo.Orientation = 0;
}
NumOrientations += 1;
break;
case TAG_EXIF_IMAGELENGTH:
case TAG_EXIF_IMAGEWIDTH:
a = (int)ConvertAnyFormat(ValuePtr, Format);
if (ExifImageWidth < a) ExifImageWidth = a;
break;
case TAG_FOCAL_PLANE_XRES:
FocalplaneXRes = ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_FOCAL_PLANE_UNITS:
switch((int)ConvertAnyFormat(ValuePtr, Format)){
case 1: FocalplaneUnits = 25.4; break; // inch
case 2:
FocalplaneUnits = 25.4;
break;
case 3: FocalplaneUnits = 10; break; // centimeter
case 4: FocalplaneUnits = 1; break; // millimeter
case 5: FocalplaneUnits = .001; break; // micrometer
}
break;
case TAG_EXPOSURE_BIAS:
ImageInfo.ExposureBias = (float)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_WHITEBALANCE:
ImageInfo.Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_LIGHT_SOURCE:
ImageInfo.LightSource = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_METERING_MODE:
ImageInfo.MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_EXPOSURE_PROGRAM:
ImageInfo.ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_EXPOSURE_INDEX:
if (ImageInfo.ISOequivalent == 0){
ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
}
break;
case TAG_EXPOSURE_MODE:
ImageInfo.ExposureMode = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_ISO_EQUIVALENT:
ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_DIGITALZOOMRATIO:
ImageInfo.DigitalZoomRatio = (float)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_THUMBNAIL_OFFSET:
ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format);
DirWithThumbnailPtrs = DirStart;
break;
case TAG_THUMBNAIL_LENGTH:
ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format);
ImageInfo.ThumbnailSizeOffset = ValuePtr-OffsetBase;
break;
case TAG_EXIF_OFFSET:
if (ShowTags) printf("%s Exif Dir:",IndentString);
case TAG_INTEROP_OFFSET:
if (Tag == TAG_INTEROP_OFFSET && ShowTags) printf("%s Interop Dir:",IndentString);
{
unsigned char * SubdirStart;
SubdirStart = OffsetBase + Get32u(ValuePtr);
if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){
ErrNonfatal("Illegal exif or interop ofset directory link",0,0);
}else{
ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1);
}
continue;
}
break;
case TAG_GPSINFO:
if (ShowTags) printf("%s GPS info dir:",IndentString);
{
unsigned char * SubdirStart;
SubdirStart = OffsetBase + Get32u(ValuePtr);
if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){
ErrNonfatal("Illegal GPS directory link",0,0);
}else{
ProcessGpsInfo(SubdirStart, ByteCount, OffsetBase, ExifLength);
}
continue;
}
break;
case TAG_FOCALLENGTH_35MM:
ImageInfo.FocalLength35mmEquiv = (unsigned)ConvertAnyFormat(ValuePtr, Format);
break;
case TAG_DISTANCE_RANGE:
ImageInfo.DistanceRange = (int)ConvertAnyFormat(ValuePtr, Format);
break;
}
}
{
unsigned char * SubdirStart;
unsigned Offset;
if (DIR_ENTRY_ADDR(DirStart, NumDirEntries) + 4 <= OffsetBase+ExifLength){
printf("DirStart %p offset from dirstart %d", DirStart, 2+12*NumDirEntries);
Offset = Get32u(DirStart+2+12*NumDirEntries);
if (Offset){
SubdirStart = OffsetBase + Offset;
if (SubdirStart > OffsetBase+ExifLength || SubdirStart < OffsetBase){
printf("SubdirStart %p OffsetBase %p ExifLength %d Offset %d",
SubdirStart, OffsetBase, ExifLength, Offset);
if (SubdirStart > OffsetBase && SubdirStart < OffsetBase+ExifLength+20){
if (ShowTags) printf("Thumbnail removed with Jhead 1.3 or earlier\n");
}else{
ErrNonfatal("Illegal subdirectory link",0,0);
}
}else{
if (SubdirStart <= OffsetBase+ExifLength){
if (ShowTags) printf("%s Continued directory ",IndentString);
ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1);
}
}
if (Offset > ImageInfo.LargestExifOffset){
ImageInfo.LargestExifOffset = Offset;
}
}
}else{
}
}
if (ThumbnailOffset){
ImageInfo.ThumbnailAtEnd = FALSE;
if (DumpExifMap){
printf("Map: %05d-%05d: Thumbnail\n",ThumbnailOffset, ThumbnailOffset+ThumbnailSize);
}
if (ThumbnailOffset <= ExifLength){
if (ThumbnailSize > ExifLength-ThumbnailOffset){
ThumbnailSize = ExifLength-ThumbnailOffset;
if (ShowTags) printf("Thumbnail incorrectly placed in header\n");
}
ImageInfo.ThumbnailOffset = ThumbnailOffset;
ImageInfo.ThumbnailSize = ThumbnailSize;
if (ShowTags){
printf("Thumbnail size: %d bytes\n",ThumbnailSize);
}
}
}
printf("returning from ProcessExifDir");
}
Vulnerability Type: DoS Exec Code Overflow
CWE ID: CWE-119
Summary: exif.c in Matthias Wandel jhead 2.87, as used in libjhead in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-08-01, allows remote attackers to execute arbitrary code or cause a denial of service (out-of-bounds access) via crafted EXIF data, aka internal bug 28868315.
Commit Message: Fix possible out of bounds access
Bug: 28868315
Change-Id: I2b416c662f9ad7f9b3c6cf973a39c6693c66775a
| Medium | 173,536 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: getHTTPResponse(int s, int * size)
{
char buf[2048];
int n;
int endofheaders = 0;
int chunked = 0;
int content_length = -1;
unsigned int chunksize = 0;
unsigned int bytestocopy = 0;
/* buffers : */
char * header_buf;
unsigned int header_buf_len = 2048;
unsigned int header_buf_used = 0;
char * content_buf;
unsigned int content_buf_len = 2048;
unsigned int content_buf_used = 0;
char chunksize_buf[32];
unsigned int chunksize_buf_index;
header_buf = malloc(header_buf_len);
content_buf = malloc(content_buf_len);
chunksize_buf[0] = '\0';
chunksize_buf_index = 0;
while((n = receivedata(s, buf, 2048, 5000, NULL)) > 0)
{
if(endofheaders == 0)
{
int i;
int linestart=0;
int colon=0;
int valuestart=0;
if(header_buf_used + n > header_buf_len) {
header_buf = realloc(header_buf, header_buf_used + n);
header_buf_len = header_buf_used + n;
}
memcpy(header_buf + header_buf_used, buf, n);
header_buf_used += n;
/* search for CR LF CR LF (end of headers)
* recognize also LF LF */
i = 0;
while(i < ((int)header_buf_used-1) && (endofheaders == 0)) {
if(header_buf[i] == '\r') {
i++;
if(header_buf[i] == '\n') {
i++;
if(i < (int)header_buf_used && header_buf[i] == '\r') {
i++;
if(i < (int)header_buf_used && header_buf[i] == '\n') {
endofheaders = i+1;
}
}
}
} else if(header_buf[i] == '\n') {
i++;
if(header_buf[i] == '\n') {
endofheaders = i+1;
}
}
i++;
}
if(endofheaders == 0)
continue;
/* parse header lines */
for(i = 0; i < endofheaders - 1; i++) {
if(colon <= linestart && header_buf[i]==':')
{
colon = i;
while(i < (endofheaders-1)
&& (header_buf[i+1] == ' ' || header_buf[i+1] == '\t'))
i++;
valuestart = i + 1;
}
/* detecting end of line */
else if(header_buf[i]=='\r' || header_buf[i]=='\n')
{
if(colon > linestart && valuestart > colon)
{
#ifdef DEBUG
printf("header='%.*s', value='%.*s'\n",
colon-linestart, header_buf+linestart,
i-valuestart, header_buf+valuestart);
#endif
if(0==strncasecmp(header_buf+linestart, "content-length", colon-linestart))
{
content_length = atoi(header_buf+valuestart);
#ifdef DEBUG
printf("Content-Length: %d\n", content_length);
#endif
}
else if(0==strncasecmp(header_buf+linestart, "transfer-encoding", colon-linestart)
&& 0==strncasecmp(header_buf+valuestart, "chunked", 7))
{
#ifdef DEBUG
printf("chunked transfer-encoding!\n");
#endif
chunked = 1;
}
}
while(header_buf[i]=='\r' || header_buf[i] == '\n')
i++;
linestart = i;
colon = linestart;
valuestart = 0;
}
}
/* copy the remaining of the received data back to buf */
n = header_buf_used - endofheaders;
memcpy(buf, header_buf + endofheaders, n);
/* if(headers) */
}
if(endofheaders)
{
/* content */
if(chunked)
{
int i = 0;
while(i < n)
{
if(chunksize == 0)
{
/* reading chunk size */
if(chunksize_buf_index == 0) {
/* skipping any leading CR LF */
if(i<n && buf[i] == '\r') i++;
if(i<n && buf[i] == '\n') i++;
}
while(i<n && isxdigit(buf[i])
&& chunksize_buf_index < (sizeof(chunksize_buf)-1))
{
chunksize_buf[chunksize_buf_index++] = buf[i];
chunksize_buf[chunksize_buf_index] = '\0';
i++;
}
while(i<n && buf[i] != '\r' && buf[i] != '\n')
i++; /* discarding chunk-extension */
if(i<n && buf[i] == '\r') i++;
if(i<n && buf[i] == '\n') {
unsigned int j;
for(j = 0; j < chunksize_buf_index; j++) {
if(chunksize_buf[j] >= '0'
&& chunksize_buf[j] <= '9')
chunksize = (chunksize << 4) + (chunksize_buf[j] - '0');
else
chunksize = (chunksize << 4) + ((chunksize_buf[j] | 32) - 'a' + 10);
}
chunksize_buf[0] = '\0';
chunksize_buf_index = 0;
i++;
} else {
/* not finished to get chunksize */
continue;
}
#ifdef DEBUG
printf("chunksize = %u (%x)\n", chunksize, chunksize);
#endif
if(chunksize == 0)
{
#ifdef DEBUG
printf("end of HTTP content - %d %d\n", i, n);
/*printf("'%.*s'\n", n-i, buf+i);*/
#endif
goto end_of_stream;
}
}
bytestocopy = ((int)chunksize < (n - i))?chunksize:(unsigned int)(n - i);
if((content_buf_used + bytestocopy) > content_buf_len)
{
if(content_length >= (int)(content_buf_used + bytestocopy)) {
content_buf_len = content_length;
} else {
content_buf_len = content_buf_used + bytestocopy;
}
content_buf = (char *)realloc((void *)content_buf,
content_buf_len);
}
memcpy(content_buf + content_buf_used, buf + i, bytestocopy);
content_buf_used += bytestocopy;
i += bytestocopy;
chunksize -= bytestocopy;
}
}
else
{
/* not chunked */
if(content_length > 0
&& (int)(content_buf_used + n) > content_length) {
/* skipping additional bytes */
n = content_length - content_buf_used;
}
if(content_buf_used + n > content_buf_len)
{
if(content_length >= (int)(content_buf_used + n)) {
content_buf_len = content_length;
} else {
content_buf_len = content_buf_used + n;
}
content_buf = (char *)realloc((void *)content_buf,
content_buf_len);
}
memcpy(content_buf + content_buf_used, buf, n);
content_buf_used += n;
}
}
/* use the Content-Length header value if available */
if(content_length > 0 && (int)content_buf_used >= content_length)
{
#ifdef DEBUG
printf("End of HTTP content\n");
#endif
break;
}
}
end_of_stream:
free(header_buf); header_buf = NULL;
*size = content_buf_used;
if(content_buf_used == 0)
{
free(content_buf);
content_buf = NULL;
}
return content_buf;
}
Vulnerability Type: DoS Overflow
CWE ID: CWE-119
Summary: The getHTTPResponse function in miniwget.c in MiniUPnP 1.9 allows remote attackers to cause a denial of service (crash) via crafted headers that trigger an out-of-bounds read.
Commit Message: miniwget.c: fixed potential buffer overrun | Low | 166,324 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: int read_escaped_char(
yyscan_t yyscanner,
uint8_t* escaped_char)
{
char text[4] = {0, 0, 0, 0};
text[0] = '\\';
text[1] = RE_YY_INPUT(yyscanner);
if (text[1] == EOF)
return 0;
if (text[1] == 'x')
{
text[2] = RE_YY_INPUT(yyscanner);
if (text[2] == EOF)
return 0;
text[3] = RE_YY_INPUT(yyscanner);
if (text[3] == EOF)
return 0;
}
*escaped_char = escaped_char_value(text);
return 1;
}
Vulnerability Type: DoS
CWE ID: CWE-476
Summary: libyara/lexer.l in YARA 3.5.0 allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted rule that is mishandled in the yy_get_next_buffer function.
Commit Message: re_lexer: Make reading escape sequences more robust (#586)
* Add test for issue #503
* re_lexer: Make reading escape sequences more robust
This commit fixes parsing incomplete escape sequences at the end of a
regular expression and parsing things like \xxy (invalid hex digits)
which before were silently turned into (char)255.
Close #503
* Update re_lexer.c | Low | 168,486 |
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only. | Code: int dtls1_get_record(SSL *s)
{
int ssl_major,ssl_minor;
int i,n;
SSL3_RECORD *rr;
unsigned char *p = NULL;
unsigned short version;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
rr= &(s->s3->rrec);
/* The epoch may have changed. If so, process all the
* pending records. This is a non-blocking operation. */
dtls1_process_buffered_records(s);
/* if we're renegotiating, then there may be buffered records */
if (dtls1_get_processed_record(s))
return 1;
/* get something from the wire */
again:
/* check if we have the header */
if ( (s->rstate != SSL_ST_READ_BODY) ||
(s->packet_length < DTLS1_RT_HEADER_LENGTH))
{
n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
/* read timeout is handled by dtls1_read_bytes */
if (n <= 0) return(n); /* error or non-blocking */
/* this packet contained a partial record, dump it */
if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
{
s->packet_length = 0;
goto again;
}
s->rstate=SSL_ST_READ_BODY;
p=s->packet;
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
/* Pull apart the header into the DTLS1_RECORD */
rr->type= *(p++);
ssl_major= *(p++);
ssl_minor= *(p++);
version=(ssl_major<<8)|ssl_minor;
/* sequence number is 64 bits, with top 2 bytes = epoch */
n2s(p,rr->epoch);
memcpy(&(s->s3->read_sequence[2]), p, 6);
p+=6;
n2s(p,rr->length);
/* Lets check version */
if (!s->first_packet)
{
if (version != s->version)
{
/* unexpected version, silently discard */
rr->length = 0;
s->packet_length = 0;
goto again;
}
}
if ((version & 0xff00) != (s->version & 0xff00))
{
/* wrong version, silently discard record */
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
{
/* record too long, silently discard it */
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now s->rstate == SSL_ST_READ_BODY */
}
/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
{
/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
i=rr->length;
n=ssl3_read_n(s,i,i,1);
if (n <= 0) return(n); /* error or non-blocking io */
/* this packet contained a partial record, dump it */
if ( n != i)
{
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now n == rr->length,
* and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
}
s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
/* match epochs. NULL means the packet is dropped on the floor */
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if ( bitmap == NULL)
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
{
#endif
/* Check whether this is a repeat, or aged record.
* Don't check if we're listening and this message is
* a ClientHello. They can look as if they're replayed,
* since they arrive from different connections and
* would be dropped unnecessarily.
*/
if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
*p == SSL3_MT_CLIENT_HELLO) &&
!dtls1_record_replay_check(s, bitmap))
{
rr->length = 0;
s->packet_length=0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
}
#endif
/* just read a 0 length packet */
if (rr->length == 0) goto again;
/* If this record is from the next epoch (either HM or ALERT),
* and a handshake is currently in progress, buffer it since it
* cannot be processed at this time. However, do not buffer
* anything while listening.
*/
if (is_next_epoch)
{
if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen)
{
dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
}
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (!dtls1_process_record(s))
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
return(1);
}
Vulnerability Type: DoS
CWE ID:
Summary: OpenSSL before 0.9.8zd, 1.0.0 before 1.0.0p, and 1.0.1 before 1.0.1k allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via a crafted DTLS message that is processed with a different read operation for the handshake header than for the handshake body, related to the dtls1_get_record function in d1_pkt.c and the ssl3_read_n function in s3_pkt.c.
Commit Message: Fix crash in dtls1_get_record whilst in the listen state where you get two
separate reads performed - one for the header and one for the body of the
handshake record.
CVE-2014-3571
Reviewed-by: Matt Caswell <[email protected]> | Low | 169,935 |