project
stringclasses 765
values | commit_id
stringlengths 6
81
| func
stringlengths 19
482k
| vul
int64 0
1
| CVE ID
stringlengths 13
16
| CWE ID
stringclasses 13
values | CWE Name
stringclasses 13
values | CWE Description
stringclasses 13
values | Potential Mitigation
stringclasses 11
values | __index_level_0__
int64 0
23.9k
|
---|---|---|---|---|---|---|---|---|---|
ImageMagick | c4e63ad30bc42da691f2b5f82a24516dd6b4dc70 | MagickExport void SetQuantumPack(QuantumInfo *quantum_info,
const MagickBooleanType pack)
{
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
quantum_info->pack=pack;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,779 |
ImageMagick | c1cf4802653970c050d175a6496fa1f11b7c089e | static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
format;
double
quantum_scale;
Image
*image;
MagickBooleanType
status;
QuantumAny
max_value;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
depth,
extent,
packet_size;
ssize_t
count,
row,
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read PNM image.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
do
{
/*
Initialize image structure.
*/
if ((count != 1) || (format != 'P'))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=1;
quantum_type=RGBQuantum;
quantum_scale=1.0;
format=(char) ReadBlobByte(image);
if (format != '7')
{
/*
PBM, PGM, PPM, and PNM.
*/
image->columns=(size_t) PNMInteger(image,10,exception);
image->rows=(size_t) PNMInteger(image,10,exception);
if ((format == 'f') || (format == 'F'))
{
char
scale[MagickPathExtent];
(void) ReadBlobString(image,scale);
quantum_scale=StringToDouble(scale,(char **) NULL);
}
else
{
if ((format == '1') || (format == '4'))
max_value=1; /* bitmap */
else
max_value=(QuantumAny) PNMInteger(image,10,exception);
}
}
else
{
char
keyword[MagickPathExtent],
value[MagickPathExtent];
int
c;
register char
*p;
/*
PAM.
*/
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
if (c == '#')
{
/*
Comment.
*/
c=PNMComment(image,exception);
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
p=keyword;
do
{
if ((size_t) (p-keyword) < (MagickPathExtent-1))
*p++=c;
c=ReadBlobByte(image);
} while (isalnum(c));
*p='\0';
if (LocaleCompare(keyword,"endhdr") == 0)
break;
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
p=value;
while (isalnum(c) || (c == '_'))
{
if ((size_t) (p-value) < (MagickPathExtent-1))
*p++=c;
c=ReadBlobByte(image);
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
if (LocaleCompare(keyword,"depth") == 0)
packet_size=StringToUnsignedLong(value);
(void) packet_size;
if (LocaleCompare(keyword,"height") == 0)
image->rows=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"maxval") == 0)
max_value=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"TUPLTYPE") == 0)
{
if (LocaleCompare(value,"BLACKANDWHITE") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=GrayQuantum;
}
if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=BlendPixelTrait;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"GRAYSCALE") == 0)
{
quantum_type=GrayQuantum;
(void) SetImageColorspace(image,GRAYColorspace,exception);
}
if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=BlendPixelTrait;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"RGB_ALPHA") == 0)
{
image->alpha_trait=BlendPixelTrait;
quantum_type=RGBAQuantum;
}
if (LocaleCompare(value,"CMYK") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace,exception);
quantum_type=CMYKQuantum;
}
if (LocaleCompare(value,"CMYK_ALPHA") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace,exception);
image->alpha_trait=BlendPixelTrait;
quantum_type=CMYKAQuantum;
}
}
if (LocaleCompare(keyword,"width") == 0)
image->columns=StringToUnsignedLong(value);
}
}
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
if ((max_value == 0) || (max_value > 4294967295))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
for (depth=1; GetQuantumRange(depth) < max_value; depth++) ;
image->depth=depth;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Convert PNM pixels to runextent-encoded MIFF packets.
*/
row=0;
switch (format)
{
case '1':
{
/*
Convert PBM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelGray(image,PNMInteger(image,2,exception) == 0 ?
QuantumRange : 0,q);
if (EOFBlob(image) != MagickFalse)
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;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=BilevelType;
break;
}
case '2':
{
Quantum
intensity;
/*
Convert PGM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
intensity=ScaleAnyToQuantum(PNMInteger(image,10,exception),
max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelGray(image,intensity,q);
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;
}
if (EOFBlob(image) != MagickFalse)
break;
}
image->type=GrayscaleType;
break;
}
case '3':
{
/*
Convert PNM image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Quantum
pixel;
pixel=ScaleAnyToQuantum(PNMInteger(image,10,exception),max_value);
if (EOFBlob(image) != MagickFalse)
break;
SetPixelRed(image,pixel,q);
pixel=ScaleAnyToQuantum(PNMInteger(image,10,exception),max_value);
SetPixelGreen(image,pixel,q);
pixel=ScaleAnyToQuantum(PNMInteger(image,10,exception),max_value);
SetPixelBlue(image,pixel,q);
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;
}
if (EOFBlob(image) != MagickFalse)
break;
}
break;
}
case '4':
{
/*
Convert PBM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=GrayQuantum;
if (image->storage_class == PseudoClass)
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumMinIsWhite(quantum_info,MagickTrue);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
ssize_t
count,
offset;
size_t
length;
if (status == MagickFalse)
continue;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
status=MagickFalse;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
status=MagickFalse;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
SetQuantumImageType(image,quantum_type);
break;
}
case '5':
{
/*
Convert PGM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=GrayQuantum;
if (image->depth <= 8)
extent=image->columns;
else
if (image->depth <= 16)
extent=2*image->columns;
else
extent=4*image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
count,
offset;
if (status == MagickFalse)
continue;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
status=MagickFalse;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
q+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
q+=GetPixelChannels(image);
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
SetQuantumImageType(image,quantum_type);
break;
}
case '6':
{
/*
Convert PNM raster image to pixel packets.
*/
quantum_type=RGBQuantum;
extent=3*(image->depth <= 8 ? 1 : 2)*image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
count,
offset;
if (status == MagickFalse)
continue;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
status=MagickFalse;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
p=pixels;
switch (image->depth)
{
case 8:
{
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
break;
}
case '7':
{
size_t
channels;
/*
Convert PAM raster image to pixel packets.
*/
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
channels=1;
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
channels=4;
break;
}
default:
{
channels=3;
break;
}
}
if (image->alpha_trait != UndefinedPixelTrait)
channels++;
if (image->depth <= 8)
extent=channels*image->columns;
else
if (image->depth <= 16)
extent=2*channels*image->columns;
else
extent=4*channels*image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
count,
offset;
if (status == MagickFalse)
continue;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
status=MagickFalse;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushCharPixel(p,&pixel);
if (image->depth != 1)
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
else
SetPixelAlpha(image,QuantumRange-
ScaleAnyToQuantum(pixel,max_value),q);
}
q+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,max_value),
q);
}
q+=GetPixelChannels(image);
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushCharPixel(p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,max_value),
q);
}
q+=GetPixelChannels(image);
}
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,max_value),
q);
}
q+=GetPixelChannels(image);
}
break;
}
}
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
SetQuantumImageType(image,quantum_type);
break;
}
case 'F':
case 'f':
{
/*
Convert PFM raster image to pixel packets.
*/
if (format == 'f')
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian;
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumDepth(image,quantum_info,32);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumScale(quantum_info,(double) QuantumRange*fabs(quantum_scale));
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
ssize_t
count,
offset;
size_t
length;
if (status == MagickFalse)
continue;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if ((size_t) count != extent)
status=MagickFalse;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
row,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
offset=row++;
q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1),
image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
status=MagickFalse;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
SetQuantumImageType(image,quantum_type);
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (EOFBlob(image) != MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"UnexpectedEndOfFile","`%s'",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 ((format == '1') || (format == '2') || (format == '3'))
do
{
/*
Skip to end of line.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
if (count != 1)
break;
if (format == 'P')
break;
} while (format != '\n');
count=ReadBlob(image,1,(unsigned char *) &format);
if ((count == 1) && (format == 'P'))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count == 1) && (format == 'P'));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,978 |
ImageMagick6 | f1e68d22d1b35459421710587a0dcbab6900b51f | MagickExport Image *SteganoImage(const Image *image,const Image *watermark,
ExceptionInfo *exception)
{
#define GetBit(alpha,i) ((((size_t) (alpha) >> (size_t) (i)) & 0x01) != 0)
#define SetBit(alpha,i,set) (alpha)=(Quantum) ((set) != 0 ? (size_t) (alpha) \
| (one << (size_t) (i)) : (size_t) (alpha) & ~(one << (size_t) (i)))
#define SteganoImageTag "Stegano/Image"
CacheView
*stegano_view,
*watermark_view;
Image
*stegano_image;
int
c;
MagickBooleanType
status;
PixelPacket
pixel;
PixelPacket
*q;
ssize_t
x;
size_t
depth,
one;
ssize_t
i,
j,
k,
y;
/*
Initialize steganographic image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(watermark != (const Image *) NULL);
assert(watermark->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1UL;
stegano_image=CloneImage(image,0,0,MagickTrue,exception);
if (stegano_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(stegano_image,DirectClass) == MagickFalse)
{
InheritException(exception,&stegano_image->exception);
stegano_image=DestroyImage(stegano_image);
return((Image *) NULL);
}
stegano_image->depth=MAGICKCORE_QUANTUM_DEPTH;
/*
Hide watermark in low-order bits of image.
*/
c=0;
i=0;
j=0;
depth=stegano_image->depth;
k=image->offset;
status=MagickTrue;
watermark_view=AcquireVirtualCacheView(watermark,exception);
stegano_view=AcquireAuthenticCacheView(stegano_image,exception);
for (i=(ssize_t) depth-1; (i >= 0) && (j < (ssize_t) depth); i--)
{
for (y=0; (y < (ssize_t) watermark->rows) && (j < (ssize_t) depth); y++)
{
for (x=0; (x < (ssize_t) watermark->columns) && (j < (ssize_t) depth); x++)
{
(void) GetOneCacheViewVirtualPixel(watermark_view,x,y,&pixel,exception);
if ((k/(ssize_t) stegano_image->columns) >= (ssize_t) stegano_image->rows)
break;
q=GetCacheViewAuthenticPixels(stegano_view,k % (ssize_t)
stegano_image->columns,k/(ssize_t) stegano_image->columns,1,1,
exception);
if (q == (PixelPacket *) NULL)
break;
switch (c)
{
case 0:
{
SetBit(GetPixelRed(q),j,GetBit(ClampToQuantum(GetPixelIntensity(
image,&pixel)),i));
break;
}
case 1:
{
SetBit(GetPixelGreen(q),j,GetBit(ClampToQuantum(GetPixelIntensity(
image,&pixel)),i));
break;
}
case 2:
{
SetBit(GetPixelBlue(q),j,GetBit(ClampToQuantum(GetPixelIntensity(
image,&pixel)),i));
break;
}
}
if (SyncCacheViewAuthenticPixels(stegano_view,exception) == MagickFalse)
break;
c++;
if (c == 3)
c=0;
k++;
if (k == (ssize_t) (stegano_image->columns*stegano_image->columns))
k=0;
if (k == image->offset)
j++;
}
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,SteganoImageTag,(MagickOffsetType)
(depth-i),depth);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
stegano_view=DestroyCacheView(stegano_view);
watermark_view=DestroyCacheView(watermark_view);
if (stegano_image->storage_class == PseudoClass)
(void) SyncImage(stegano_image);
if (status == MagickFalse)
stegano_image=DestroyImage(stegano_image);
return(stegano_image);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,492 |
Chrome | 514f93279494ec4448b34a7aeeff27eccaae983f | bool DebugOnStart::FindArgument(wchar_t* command_line, const char* argument_c) {
wchar_t argument[50] = {};
for (int i = 0; argument_c[i]; ++i)
argument[i] = argument_c[i];
int argument_len = lstrlen(argument);
int command_line_len = lstrlen(command_line);
while (command_line_len > argument_len) {
wchar_t first_char = command_line[0];
wchar_t last_char = command_line[argument_len+1];
if ((first_char == L'-' || first_char == L'/') &&
(last_char == L' ' || last_char == 0 || last_char == L'=')) {
command_line[argument_len+1] = 0;
if (lstrcmpi(command_line+1, argument) == 0) {
command_line[argument_len+1] = last_char;
return true;
}
command_line[argument_len+1] = last_char;
}
++command_line;
--command_line_len;
}
return false;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,543 |
samba | 31f1a36901b5b8959dc51401c09c114829b50392 | static int _pam_delete_cred(pam_handle_t *pamh, int flags,
int argc, const char **argv)
{
int retval = PAM_SUCCESS;
struct pwb_context *ctx = NULL;
struct wbcLogoffUserParams logoff;
struct wbcAuthErrorInfo *error = NULL;
const char *user;
wbcErr wbc_status = WBC_ERR_SUCCESS;
ZERO_STRUCT(logoff);
retval = _pam_winbind_init_context(pamh, flags, argc, argv, &ctx);
if (retval) {
goto out;
}
_PAM_LOG_FUNCTION_ENTER("_pam_delete_cred", ctx);
if (ctx->ctrl & WINBIND_KRB5_AUTH) {
/* destroy the ccache here */
uint32_t wbc_flags = 0;
const char *ccname = NULL;
struct passwd *pwd = NULL;
retval = pam_get_user(pamh, &user, _("Username: "));
if (retval) {
_pam_log(ctx, LOG_ERR,
"could not identify user");
goto out;
}
if (user == NULL) {
_pam_log(ctx, LOG_ERR,
"username was NULL!");
retval = PAM_USER_UNKNOWN;
goto out;
}
_pam_log_debug(ctx, LOG_DEBUG,
"username [%s] obtained", user);
ccname = pam_getenv(pamh, "KRB5CCNAME");
if (ccname == NULL) {
_pam_log_debug(ctx, LOG_DEBUG,
"user has no KRB5CCNAME environment");
}
pwd = getpwnam(user);
if (pwd == NULL) {
retval = PAM_USER_UNKNOWN;
goto out;
}
wbc_flags = WBFLAG_PAM_KRB5 |
WBFLAG_PAM_CONTACT_TRUSTDOM;
logoff.username = user;
if (ccname) {
wbc_status = wbcAddNamedBlob(&logoff.num_blobs,
&logoff.blobs,
"ccfilename",
0,
(uint8_t *)ccname,
strlen(ccname)+1);
if (!WBC_ERROR_IS_OK(wbc_status)) {
goto out;
}
}
wbc_status = wbcAddNamedBlob(&logoff.num_blobs,
&logoff.blobs,
"flags",
0,
(uint8_t *)&wbc_flags,
sizeof(wbc_flags));
if (!WBC_ERROR_IS_OK(wbc_status)) {
goto out;
}
wbc_status = wbcAddNamedBlob(&logoff.num_blobs,
&logoff.blobs,
"user_uid",
0,
(uint8_t *)&pwd->pw_uid,
sizeof(pwd->pw_uid));
if (!WBC_ERROR_IS_OK(wbc_status)) {
goto out;
}
wbc_status = wbcLogoffUserEx(&logoff, &error);
retval = wbc_auth_error_to_pam_error(ctx, error, wbc_status,
user, "wbcLogoffUser");
wbcFreeMemory(error);
wbcFreeMemory(logoff.blobs);
logoff.blobs = NULL;
if (!WBC_ERROR_IS_OK(wbc_status)) {
_pam_log(ctx, LOG_INFO,
"failed to logoff user %s: %s\n",
user, wbcErrorString(wbc_status));
}
}
out:
if (logoff.blobs) {
wbcFreeMemory(logoff.blobs);
}
if (!WBC_ERROR_IS_OK(wbc_status)) {
retval = wbc_auth_error_to_pam_error(ctx, error, wbc_status,
user, "wbcLogoffUser");
}
/*
* Delete the krb5 ccname variable from the PAM environment
* if it was set by winbind.
*/
if ((ctx->ctrl & WINBIND_KRB5_AUTH) && pam_getenv(pamh, "KRB5CCNAME")) {
pam_putenv(pamh, "KRB5CCNAME");
}
_PAM_LOG_FUNCTION_LEAVE("_pam_delete_cred", ctx, retval);
TALLOC_FREE(ctx);
return retval;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,150 |
jasper | d42b2388f7f8e0332c846675133acea151fc557a | static inline ulong encode_twos_comp(long n, int prec)
{
ulong result;
assert(prec >= 2);
jas_eprintf("warning: support for signed data is untested\n");
if (n < 0) {
result = -n;
result = (result ^ 0xffffffffUL) + 1;
result &= (1 << prec) - 1;
} else {
result = n;
}
return result;
}
| 1 | CVE-2016-9557 | CWE-190 | Integer Overflow or Wraparound | The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number. | Phase: Requirements
Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol.
Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
If possible, choose a language or compiler that performs automatic bounds checking.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Use libraries or frameworks that make it easier to handle numbers without unexpected consequences.
Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106]
Phase: Implementation
Strategy: Input Validation
Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.
Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values.
Phase: Implementation
Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7]
Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Phase: Implementation
Strategy: Compilation or Build Hardening
Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system. | 124 |
linux | 8176cced706b5e5d15887584150764894e94e02f | static int perf_swevent_init(struct perf_event *event)
{
int event_id = event->attr.config;
if (event->attr.type != PERF_TYPE_SOFTWARE)
return -ENOENT;
/*
* no branch sampling for software events
*/
if (has_branch_stack(event))
return -EOPNOTSUPP;
switch (event_id) {
case PERF_COUNT_SW_CPU_CLOCK:
case PERF_COUNT_SW_TASK_CLOCK:
return -ENOENT;
default:
break;
}
if (event_id >= PERF_COUNT_SW_MAX)
return -ENOENT;
if (!event->parent) {
int err;
err = swevent_hlist_get(event);
if (err)
return err;
static_key_slow_inc(&perf_swevent_enabled[event_id]);
event->destroy = sw_perf_event_destroy;
}
return 0;
}
| 1 | CVE-2013-2094 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 3,001 |
Android | 04839626ed859623901ebd3a5fd483982186b59d | long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const
{
return GetTime(pChapters, m_start_timecode);
}
| 1 | CVE-2016-1621 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 8,649 |
Chrome | 3514a77e7fa2e5b8bfe5d98af22964bbd69d680f | void ProcessStateChangesUnifiedPlan(
WebRtcSetDescriptionObserver::States states) {
DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kUnifiedPlan);
handler_->OnModifyTransceivers(
std::move(states.transceiver_states),
action_ == PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION);
}
| 1 | CVE-2019-5760 | CWE-416 | Use After Free | The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
Phase: Architecture and Design
Strategy: Language Selection
Choose a language that provides automatic memory management.
Phase: Implementation
Strategy: Attack Surface Reduction
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.
Effectiveness: Defense in Depth
Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution. | 780 |
qemu | 5193be3be35f29a35bc465036cd64ad60d43385f | static void tsc210x_i2s_set_rate(TSC210xState *s, int in, int out)
{
s->i2s_tx_rate = out;
s->i2s_rx_rate = in;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,278 |
linux | 4ab42d78e37a294ac7bc56901d563c642e03c4ae | slhc_remember(struct slcompress *comp, unsigned char *icp, int isize)
{
printk(KERN_DEBUG "Called IP function on non IP-system: slhc_remember");
return -EINVAL;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,003 |
suricata | b9579fbe7dd408200ef03cbe20efddb624b73885 | int DetectEngineContentInspection(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
const Signature *s, const SigMatchData *smd,
Flow *f,
uint8_t *buffer, uint32_t buffer_len,
uint32_t stream_start_offset,
uint8_t inspection_mode, void *data)
{
SCEnter();
KEYWORD_PROFILING_START;
det_ctx->inspection_recursion_counter++;
if (det_ctx->inspection_recursion_counter == de_ctx->inspection_recursion_limit) {
det_ctx->discontinue_matching = 1;
KEYWORD_PROFILING_END(det_ctx, smd->type, 0);
SCReturnInt(0);
}
if (smd == NULL || buffer_len == 0) {
KEYWORD_PROFILING_END(det_ctx, smd->type, 0);
SCReturnInt(0);
}
/* \todo unify this which is phase 2 of payload inspection unification */
if (smd->type == DETECT_CONTENT) {
DetectContentData *cd = (DetectContentData *)smd->ctx;
SCLogDebug("inspecting content %"PRIu32" buffer_len %"PRIu32, cd->id, buffer_len);
/* we might have already have this content matched by the mpm.
* (if there is any other reason why we'd want to avoid checking
* it here, please fill it in) */
//if (cd->flags & DETECT_CONTENT_NO_DOUBLE_INSPECTION_REQUIRED) {
// goto match;
//}
/* rule parsers should take care of this */
#ifdef DEBUG
BUG_ON(cd->depth != 0 && cd->depth <= cd->offset);
#endif
/* search for our pattern, checking the matches recursively.
* if we match we look for the next SigMatch as well */
uint8_t *found = NULL;
uint32_t offset = 0;
uint32_t depth = buffer_len;
uint32_t prev_offset = 0; /**< used in recursive searching */
uint32_t prev_buffer_offset = det_ctx->buffer_offset;
do {
if ((cd->flags & DETECT_CONTENT_DISTANCE) ||
(cd->flags & DETECT_CONTENT_WITHIN)) {
SCLogDebug("det_ctx->buffer_offset %"PRIu32, det_ctx->buffer_offset);
offset = prev_buffer_offset;
depth = buffer_len;
int distance = cd->distance;
if (cd->flags & DETECT_CONTENT_DISTANCE) {
if (cd->flags & DETECT_CONTENT_DISTANCE_BE) {
distance = det_ctx->bj_values[cd->distance];
}
if (distance < 0 && (uint32_t)(abs(distance)) > offset)
offset = 0;
else
offset += distance;
SCLogDebug("cd->distance %"PRIi32", offset %"PRIu32", depth %"PRIu32,
distance, offset, depth);
}
if (cd->flags & DETECT_CONTENT_WITHIN) {
if (cd->flags & DETECT_CONTENT_WITHIN_BE) {
if ((int32_t)depth > (int32_t)(prev_buffer_offset + det_ctx->bj_values[cd->within] + distance)) {
depth = prev_buffer_offset + det_ctx->bj_values[cd->within] + distance;
}
} else {
if ((int32_t)depth > (int32_t)(prev_buffer_offset + cd->within + distance)) {
depth = prev_buffer_offset + cd->within + distance;
}
SCLogDebug("cd->within %"PRIi32", det_ctx->buffer_offset %"PRIu32", depth %"PRIu32,
cd->within, prev_buffer_offset, depth);
}
if (stream_start_offset != 0 && prev_buffer_offset == 0) {
if (depth <= stream_start_offset) {
goto no_match;
} else if (depth >= (stream_start_offset + buffer_len)) {
;
} else {
depth = depth - stream_start_offset;
}
}
}
if (cd->flags & DETECT_CONTENT_DEPTH_BE) {
if ((det_ctx->bj_values[cd->depth] + prev_buffer_offset) < depth) {
depth = prev_buffer_offset + det_ctx->bj_values[cd->depth];
}
} else {
if (cd->depth != 0) {
if ((cd->depth + prev_buffer_offset) < depth) {
depth = prev_buffer_offset + cd->depth;
}
SCLogDebug("cd->depth %"PRIu32", depth %"PRIu32, cd->depth, depth);
}
}
if (cd->flags & DETECT_CONTENT_OFFSET_BE) {
if (det_ctx->bj_values[cd->offset] > offset)
offset = det_ctx->bj_values[cd->offset];
} else {
if (cd->offset > offset) {
offset = cd->offset;
SCLogDebug("setting offset %"PRIu32, offset);
}
}
} else { /* implied no relative matches */
/* set depth */
if (cd->flags & DETECT_CONTENT_DEPTH_BE) {
depth = det_ctx->bj_values[cd->depth];
} else {
if (cd->depth != 0) {
depth = cd->depth;
}
}
if (stream_start_offset != 0 && cd->flags & DETECT_CONTENT_DEPTH) {
if (depth <= stream_start_offset) {
goto no_match;
} else if (depth >= (stream_start_offset + buffer_len)) {
;
} else {
depth = depth - stream_start_offset;
}
}
/* set offset */
if (cd->flags & DETECT_CONTENT_OFFSET_BE)
offset = det_ctx->bj_values[cd->offset];
else
offset = cd->offset;
prev_buffer_offset = 0;
}
/* update offset with prev_offset if we're searching for
* matches after the first occurence. */
SCLogDebug("offset %"PRIu32", prev_offset %"PRIu32, offset, prev_offset);
if (prev_offset != 0)
offset = prev_offset;
SCLogDebug("offset %"PRIu32", depth %"PRIu32, offset, depth);
if (depth > buffer_len)
depth = buffer_len;
/* if offset is bigger than depth we can never match on a pattern.
* We can however, "match" on a negated pattern. */
if (offset > depth || depth == 0) {
if (cd->flags & DETECT_CONTENT_NEGATED) {
goto match;
} else {
goto no_match;
}
}
uint8_t *sbuffer = buffer + offset;
uint32_t sbuffer_len = depth - offset;
uint32_t match_offset = 0;
SCLogDebug("sbuffer_len %"PRIu32, sbuffer_len);
#ifdef DEBUG
BUG_ON(sbuffer_len > buffer_len);
#endif
/* \todo Add another optimization here. If cd->content_len is
* greater than sbuffer_len found is anyways NULL */
/* do the actual search */
found = SpmScan(cd->spm_ctx, det_ctx->spm_thread_ctx, sbuffer,
sbuffer_len);
/* next we evaluate the result in combination with the
* negation flag. */
SCLogDebug("found %p cd negated %s", found, cd->flags & DETECT_CONTENT_NEGATED ? "true" : "false");
if (found == NULL && !(cd->flags & DETECT_CONTENT_NEGATED)) {
if ((cd->flags & (DETECT_CONTENT_DISTANCE|DETECT_CONTENT_WITHIN)) == 0) {
/* independent match from previous matches, so failure is fatal */
det_ctx->discontinue_matching = 1;
}
goto no_match;
} else if (found == NULL && (cd->flags & DETECT_CONTENT_NEGATED)) {
goto match;
} else if (found != NULL && (cd->flags & DETECT_CONTENT_NEGATED)) {
SCLogDebug("content %"PRIu32" matched at offset %"PRIu32", but negated so no match", cd->id, match_offset);
/* don't bother carrying recursive matches now, for preceding
* relative keywords */
if (DETECT_CONTENT_IS_SINGLE(cd))
det_ctx->discontinue_matching = 1;
goto no_match;
} else {
match_offset = (uint32_t)((found - buffer) + cd->content_len);
SCLogDebug("content %"PRIu32" matched at offset %"PRIu32"", cd->id, match_offset);
det_ctx->buffer_offset = match_offset;
/* Match branch, add replace to the list if needed */
if (cd->flags & DETECT_CONTENT_REPLACE) {
if (inspection_mode == DETECT_ENGINE_CONTENT_INSPECTION_MODE_PAYLOAD) {
/* we will need to replace content if match is confirmed */
det_ctx->replist = DetectReplaceAddToList(det_ctx->replist, found, cd);
} else {
SCLogWarning(SC_ERR_INVALID_VALUE, "Can't modify payload without packet");
}
}
/* if this is the last match we're done */
if (smd->is_last) {
goto match;
}
SCLogDebug("content %"PRIu32, cd->id);
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
/* see if the next buffer keywords match. If not, we will
* search for another occurence of this content and see
* if the others match then until we run out of matches */
int r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1,
f, buffer, buffer_len, stream_start_offset, inspection_mode, data);
if (r == 1) {
SCReturnInt(1);
}
SCLogDebug("no match for 'next sm'");
if (det_ctx->discontinue_matching) {
SCLogDebug("'next sm' said to discontinue this right now");
goto no_match;
}
/* no match and no reason to look for another instance */
if ((cd->flags & DETECT_CONTENT_RELATIVE_NEXT) == 0) {
SCLogDebug("'next sm' does not depend on me, so we can give up");
det_ctx->discontinue_matching = 1;
goto no_match;
}
SCLogDebug("'next sm' depends on me %p, lets see what we can do (flags %u)", cd, cd->flags);
/* set the previous match offset to the start of this match + 1 */
prev_offset = (match_offset - (cd->content_len - 1));
SCLogDebug("trying to see if there is another match after prev_offset %"PRIu32, prev_offset);
}
} while(1);
} else if (smd->type == DETECT_ISDATAAT) {
SCLogDebug("inspecting isdataat");
DetectIsdataatData *id = (DetectIsdataatData *)smd->ctx;
if (id->flags & ISDATAAT_RELATIVE) {
if (det_ctx->buffer_offset + id->dataat > buffer_len) {
SCLogDebug("det_ctx->buffer_offset + id->dataat %"PRIu32" > %"PRIu32, det_ctx->buffer_offset + id->dataat, buffer_len);
if (id->flags & ISDATAAT_NEGATED)
goto match;
goto no_match;
} else {
SCLogDebug("relative isdataat match");
if (id->flags & ISDATAAT_NEGATED)
goto no_match;
goto match;
}
} else {
if (id->dataat < buffer_len) {
SCLogDebug("absolute isdataat match");
if (id->flags & ISDATAAT_NEGATED)
goto no_match;
goto match;
} else {
SCLogDebug("absolute isdataat mismatch, id->isdataat %"PRIu32", buffer_len %"PRIu32"", id->dataat, buffer_len);
if (id->flags & ISDATAAT_NEGATED)
goto match;
goto no_match;
}
}
} else if (smd->type == DETECT_PCRE) {
SCLogDebug("inspecting pcre");
DetectPcreData *pe = (DetectPcreData *)smd->ctx;
uint32_t prev_buffer_offset = det_ctx->buffer_offset;
uint32_t prev_offset = 0;
int r = 0;
det_ctx->pcre_match_start_offset = 0;
do {
Packet *p = NULL;
if (inspection_mode == DETECT_ENGINE_CONTENT_INSPECTION_MODE_PAYLOAD)
p = (Packet *)data;
r = DetectPcrePayloadMatch(det_ctx, s, smd, p, f,
buffer, buffer_len);
if (r == 0) {
goto no_match;
}
if (!(pe->flags & DETECT_PCRE_RELATIVE_NEXT)) {
SCLogDebug("no relative match coming up, so this is a match");
goto match;
}
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
/* save it, in case we need to do a pcre match once again */
prev_offset = det_ctx->pcre_match_start_offset;
/* see if the next payload keywords match. If not, we will
* search for another occurence of this pcre and see
* if the others match, until we run out of matches */
r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1,
f, buffer, buffer_len, stream_start_offset, inspection_mode, data);
if (r == 1) {
SCReturnInt(1);
}
if (det_ctx->discontinue_matching)
goto no_match;
det_ctx->buffer_offset = prev_buffer_offset;
det_ctx->pcre_match_start_offset = prev_offset;
} while (1);
} else if (smd->type == DETECT_BYTETEST) {
DetectBytetestData *btd = (DetectBytetestData *)smd->ctx;
uint8_t flags = btd->flags;
int32_t offset = btd->offset;
uint64_t value = btd->value;
if (flags & DETECT_BYTETEST_OFFSET_BE) {
offset = det_ctx->bj_values[offset];
}
if (flags & DETECT_BYTETEST_VALUE_BE) {
value = det_ctx->bj_values[value];
}
/* if we have dce enabled we will have to use the endianness
* specified by the dce header */
if (flags & DETECT_BYTETEST_DCE && data != NULL) {
DCERPCState *dcerpc_state = (DCERPCState *)data;
/* enable the endianness flag temporarily. once we are done
* processing we reset the flags to the original value*/
flags |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] & 0x10) ?
DETECT_BYTETEST_LITTLE: 0);
}
if (DetectBytetestDoMatch(det_ctx, s, smd->ctx, buffer, buffer_len, flags,
offset, value) != 1) {
goto no_match;
}
goto match;
} else if (smd->type == DETECT_BYTEJUMP) {
DetectBytejumpData *bjd = (DetectBytejumpData *)smd->ctx;
uint8_t flags = bjd->flags;
int32_t offset = bjd->offset;
if (flags & DETECT_BYTEJUMP_OFFSET_BE) {
offset = det_ctx->bj_values[offset];
}
/* if we have dce enabled we will have to use the endianness
* specified by the dce header */
if (flags & DETECT_BYTEJUMP_DCE && data != NULL) {
DCERPCState *dcerpc_state = (DCERPCState *)data;
/* enable the endianness flag temporarily. once we are done
* processing we reset the flags to the original value*/
flags |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] & 0x10) ?
DETECT_BYTEJUMP_LITTLE: 0);
}
if (DetectBytejumpDoMatch(det_ctx, s, smd->ctx, buffer, buffer_len,
flags, offset) != 1) {
goto no_match;
}
goto match;
} else if (smd->type == DETECT_BYTE_EXTRACT) {
DetectByteExtractData *bed = (DetectByteExtractData *)smd->ctx;
uint8_t endian = bed->endian;
/* if we have dce enabled we will have to use the endianness
* specified by the dce header */
if ((bed->flags & DETECT_BYTE_EXTRACT_FLAG_ENDIAN) &&
endian == DETECT_BYTE_EXTRACT_ENDIAN_DCE && data != NULL) {
DCERPCState *dcerpc_state = (DCERPCState *)data;
/* enable the endianness flag temporarily. once we are done
* processing we reset the flags to the original value*/
endian |= ((dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] == 0x10) ?
DETECT_BYTE_EXTRACT_ENDIAN_LITTLE : DETECT_BYTE_EXTRACT_ENDIAN_BIG);
}
if (DetectByteExtractDoMatch(det_ctx, smd, s, buffer,
buffer_len,
&det_ctx->bj_values[bed->local_id],
endian) != 1) {
goto no_match;
}
goto match;
/* we should never get here, but bail out just in case */
} else if (smd->type == DETECT_AL_URILEN) {
SCLogDebug("inspecting uri len");
int r = 0;
DetectUrilenData *urilend = (DetectUrilenData *) smd->ctx;
switch (urilend->mode) {
case DETECT_URILEN_EQ:
if (buffer_len == urilend->urilen1)
r = 1;
break;
case DETECT_URILEN_LT:
if (buffer_len < urilend->urilen1)
r = 1;
break;
case DETECT_URILEN_GT:
if (buffer_len > urilend->urilen1)
r = 1;
break;
case DETECT_URILEN_RA:
if (buffer_len > urilend->urilen1 &&
buffer_len < urilend->urilen2) {
r = 1;
}
break;
}
if (r == 1) {
goto match;
}
det_ctx->discontinue_matching = 0;
goto no_match;
#ifdef HAVE_LUA
}
else if (smd->type == DETECT_LUA) {
SCLogDebug("lua starting");
if (DetectLuaMatchBuffer(det_ctx, s, smd, buffer, buffer_len,
det_ctx->buffer_offset, f) != 1)
{
SCLogDebug("lua no_match");
goto no_match;
}
SCLogDebug("lua match");
goto match;
#endif /* HAVE_LUA */
} else if (smd->type == DETECT_BASE64_DECODE) {
if (DetectBase64DecodeDoMatch(det_ctx, s, smd, buffer, buffer_len)) {
if (s->sm_arrays[DETECT_SM_LIST_BASE64_DATA] != NULL) {
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
if (DetectBase64DataDoMatch(de_ctx, det_ctx, s, f)) {
/* Base64 is a terminal list. */
goto final_match;
}
}
}
} else {
SCLogDebug("sm->type %u", smd->type);
#ifdef DEBUG
BUG_ON(1);
#endif
}
no_match:
KEYWORD_PROFILING_END(det_ctx, smd->type, 0);
SCReturnInt(0);
match:
/* this sigmatch matched, inspect the next one. If it was the last,
* the buffer portion of the signature matched. */
if (!smd->is_last) {
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
int r = DetectEngineContentInspection(de_ctx, det_ctx, s, smd+1,
f, buffer, buffer_len, stream_start_offset, inspection_mode, data);
SCReturnInt(r);
}
final_match:
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
SCReturnInt(1);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,898 |
php-src | a793b709086eed655bc98f933d838b8679b28920 | static char *ps_files_path_create(char *buf, size_t buflen, ps_files *data, const char *key)
{
size_t key_len;
const char *p;
int i;
int n;
key_len = strlen(key);
if (key_len <= data->dirdepth ||
buflen < (strlen(data->basedir) + 2 * data->dirdepth + key_len + 5 + sizeof(FILE_PREFIX))) {
return NULL;
}
p = key;
memcpy(buf, data->basedir, data->basedir_len);
n = data->basedir_len;
buf[n++] = PHP_DIR_SEPARATOR;
for (i = 0; i < (int)data->dirdepth; i++) {
buf[n++] = *p++;
buf[n++] = PHP_DIR_SEPARATOR;
}
memcpy(buf + n, FILE_PREFIX, sizeof(FILE_PREFIX) - 1);
n += sizeof(FILE_PREFIX) - 1;
memcpy(buf + n, key, key_len);
n += key_len;
buf[n] = '\0';
return buf;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,058 |
httpd | 29c63b786ae028d82405421585e91283c8fa0da3 | apr_status_t h2_stream_add_header(h2_stream *stream,
const char *name, size_t nlen,
const char *value, size_t vlen)
{
ap_assert(stream);
if (!stream->has_response) {
if (name[0] == ':') {
if ((vlen) > stream->session->s->limit_req_line) {
/* pseudo header: approximation of request line size check */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): pseudo header %s too long",
stream->session->id, stream->id, name);
return h2_stream_set_error(stream,
HTTP_REQUEST_URI_TOO_LARGE);
}
}
else if ((nlen + 2 + vlen) > stream->session->s->limit_req_fieldsize) {
/* header too long */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): header %s too long",
stream->session->id, stream->id, name);
return h2_stream_set_error(stream,
HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE);
}
if (name[0] != ':') {
++stream->request_headers_added;
if (stream->request_headers_added
> stream->session->s->limit_req_fields) {
/* too many header lines */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): too many header lines",
stream->session->id, stream->id);
return h2_stream_set_error(stream,
HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE);
}
}
}
if (h2_stream_is_scheduled(stream)) {
return add_trailer(stream, name, nlen, value, vlen);
}
else {
if (!stream->rtmp) {
stream->rtmp = h2_req_create(stream->id, stream->pool,
NULL, NULL, NULL, NULL, NULL, 0);
}
if (stream->state != H2_STREAM_ST_OPEN) {
return APR_ECONNRESET;
}
return h2_request_add_header(stream->rtmp, stream->pool,
name, nlen, value, vlen);
}
}
| 1 | CVE-2016-8740 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 3,829 |
ImageMagick | 33d1b9590c401d4aee666ffd10b16868a38cf705 | static int formatIPTCfromBuffer(Image *ofile, char *s, ssize_t len)
{
char
temp[MagickPathExtent];
unsigned int
foundiptc,
tagsfound;
unsigned char
recnum,
dataset;
unsigned char
*readable,
*str;
ssize_t
tagindx,
taglen;
int
i,
tagcount = (int) (sizeof(tags) / sizeof(tag_spec));
int
c;
foundiptc = 0; /* found the IPTC-Header */
tagsfound = 0; /* number of tags found */
while (len > 0)
{
c = *s++; len--;
if (c == 0x1c)
foundiptc = 1;
else
{
if (foundiptc)
return -1;
else
continue;
}
/*
We found the 0x1c tag and now grab the dataset and record number tags.
*/
c = *s++; len--;
if (len < 0) return -1;
dataset = (unsigned char) c;
c = *s++; len--;
if (len < 0) return -1;
recnum = (unsigned char) c;
/* try to match this record to one of the ones in our named table */
for (i=0; i< tagcount; i++)
if (tags[i].id == (short) recnum)
break;
if (i < tagcount)
readable=(unsigned char *) tags[i].name;
else
readable=(unsigned char *) "";
/*
We decode the length of the block that follows - ssize_t or short fmt.
*/
c=(*s++);
len--;
if (len < 0)
return(-1);
if (c & (unsigned char) 0x80)
return(0);
else
{
s--;
len++;
taglen=readWordFromBuffer(&s, &len);
}
if (taglen < 0)
return(-1);
if (taglen > 65535)
return(-1);
/* make a buffer to hold the tag datand snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) (taglen+
MagickPathExtent),sizeof(*str));
if (str == (unsigned char *) NULL)
{
(void) printf("MemoryAllocationFailed");
return 0;
}
for (tagindx=0; tagindx<taglen; tagindx++)
{
c = *s++; len--;
if (len < 0)
{
str=(unsigned char *) RelinquishMagickMemory(str);
return(-1);
}
str[tagindx]=(unsigned char) c;
}
str[taglen]=0;
/* now finish up by formatting this binary data into ASCII equivalent */
if (strlen((char *)readable) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d#%s=",
(unsigned int) dataset,(unsigned int) recnum, readable);
else
(void) FormatLocaleString(temp,MagickPathExtent,"%d#%d=",
(unsigned int) dataset,(unsigned int) recnum);
(void) WriteBlobString(ofile,temp);
formatString( ofile, (char *)str, taglen );
str=(unsigned char *) RelinquishMagickMemory(str);
tagsfound++;
}
return ((int) tagsfound);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,732 |
avahi | e111def44a7df4624a4aa3f85fe98054bffb6b4f | void avahi_server_generate_response(AvahiServer *s, AvahiInterface *i, AvahiDnsPacket *p, const AvahiAddress *a, uint16_t port, int legacy_unicast, int immediately) {
assert(s);
assert(i);
assert(!legacy_unicast || (a && port > 0 && p));
if (legacy_unicast) {
AvahiDnsPacket *reply;
AvahiRecord *r;
if (!(reply = avahi_dns_packet_new_reply(p, 512 + AVAHI_DNS_PACKET_EXTRA_SIZE /* unicast DNS maximum packet size is 512 */ , 1, 1)))
return; /* OOM */
while ((r = avahi_record_list_next(s->record_list, NULL, NULL, NULL))) {
append_aux_records_to_list(s, i, r, 0);
if (avahi_dns_packet_append_record(reply, r, 0, 10))
avahi_dns_packet_inc_field(reply, AVAHI_DNS_FIELD_ANCOUNT);
else {
char *t = avahi_record_to_string(r);
avahi_log_warn("Record [%s] not fitting in legacy unicast packet, dropping.", t);
avahi_free(t);
}
avahi_record_unref(r);
}
if (avahi_dns_packet_get_field(reply, AVAHI_DNS_FIELD_ANCOUNT) != 0)
avahi_interface_send_packet_unicast(i, reply, a, port);
avahi_dns_packet_free(reply);
} else {
int unicast_response, flush_cache, auxiliary;
AvahiDnsPacket *reply = NULL;
AvahiRecord *r;
/* In case the query packet was truncated never respond
immediately, because known answer suppression records might be
contained in later packets */
int tc = p && !!(avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_FLAGS) & AVAHI_DNS_FLAG_TC);
while ((r = avahi_record_list_next(s->record_list, &flush_cache, &unicast_response, &auxiliary))) {
int im = immediately;
/* Only send the response immediately if it contains a
* unique entry AND it is not in reply to a truncated
* packet AND it is not an auxiliary record AND all other
* responses for this record are unique too. */
if (flush_cache && !tc && !auxiliary && avahi_record_list_all_flush_cache(s->record_list))
im = 1;
if (!avahi_interface_post_response(i, r, flush_cache, a, im) && unicast_response) {
/* Due to some reasons the record has not been scheduled.
* The client requested an unicast response in that
* case. Therefore we prepare such a response */
append_aux_records_to_list(s, i, r, unicast_response);
for (;;) {
if (!reply) {
assert(p);
if (!(reply = avahi_dns_packet_new_reply(p, i->hardware->mtu, 0, 0)))
break; /* OOM */
}
if (avahi_dns_packet_append_record(reply, r, flush_cache, 0)) {
/* Appending this record succeeded, so incremeant
* the specific header field, and return to the caller */
avahi_dns_packet_inc_field(reply, AVAHI_DNS_FIELD_ANCOUNT);
break;
}
if (avahi_dns_packet_get_field(reply, AVAHI_DNS_FIELD_ANCOUNT) == 0) {
size_t size;
/* The record is too large for one packet, so create a larger packet */
avahi_dns_packet_free(reply);
size = avahi_record_get_estimate_size(r) + AVAHI_DNS_PACKET_HEADER_SIZE;
if (!(reply = avahi_dns_packet_new_reply(p, size + AVAHI_DNS_PACKET_EXTRA_SIZE, 0, 1)))
break; /* OOM */
if (avahi_dns_packet_append_record(reply, r, flush_cache, 0)) {
/* Appending this record succeeded, so incremeant
* the specific header field, and return to the caller */
avahi_dns_packet_inc_field(reply, AVAHI_DNS_FIELD_ANCOUNT);
break;
} else {
/* We completely fucked up, there's
* nothing we can do. The RR just doesn't
* fit in. Let's ignore it. */
char *t;
avahi_dns_packet_free(reply);
reply = NULL;
t = avahi_record_to_string(r);
avahi_log_warn("Record [%s] too large, doesn't fit in any packet!", t);
avahi_free(t);
break;
}
}
/* Appending the record didn't succeeed, so let's send this packet, and create a new one */
avahi_interface_send_packet_unicast(i, reply, a, port);
avahi_dns_packet_free(reply);
reply = NULL;
}
}
avahi_record_unref(r);
}
if (reply) {
if (avahi_dns_packet_get_field(reply, AVAHI_DNS_FIELD_ANCOUNT) != 0)
avahi_interface_send_packet_unicast(i, reply, a, port);
avahi_dns_packet_free(reply);
}
}
avahi_record_list_flush(s->record_list);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,272 |
Android | e7142a0703bc93f75e213e96ebc19000022afed9 | status_t MPEG4Extractor::parseQTMetaKey(off64_t offset, size_t size) {
if (size < 8) {
return ERROR_MALFORMED;
}
uint32_t count;
if (!mDataSource->getUInt32(offset + 4, &count)) {
return ERROR_MALFORMED;
}
if (mMetaKeyMap.size() > 0) {
ALOGW("'keys' atom seen again, discarding existing entries");
mMetaKeyMap.clear();
}
off64_t keyOffset = offset + 8;
off64_t stopOffset = offset + size;
for (size_t i = 1; i <= count; i++) {
if (keyOffset + 8 > stopOffset) {
return ERROR_MALFORMED;
}
uint32_t keySize;
if (!mDataSource->getUInt32(keyOffset, &keySize)
|| keySize < 8
|| keyOffset + keySize > stopOffset) {
return ERROR_MALFORMED;
}
uint32_t type;
if (!mDataSource->getUInt32(keyOffset + 4, &type)
|| type != FOURCC('m', 'd', 't', 'a')) {
return ERROR_MALFORMED;
}
keySize -= 8;
keyOffset += 8;
sp<ABuffer> keyData = new ABuffer(keySize);
if (keyData->data() == NULL) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
keyOffset, keyData->data(), keySize) < (ssize_t) keySize) {
return ERROR_MALFORMED;
}
AString key((const char *)keyData->data(), keySize);
mMetaKeyMap.add(i, key);
keyOffset += keySize;
}
return OK;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,345 |
bootstrap-dht | e809ea80e3527e32c40756eddd8b2ae44bc3af1a | int lazy_bdecode(char const* start, char const* end, lazy_entry& ret
, error_code& ec, int* error_pos, int depth_limit, int item_limit)
{
char const* const orig_start = start;
ret.clear();
if (start == end) return 0;
std::vector<lazy_entry*> stack;
stack.push_back(&ret);
while (start <= end)
{
if (stack.empty()) break; // done!
lazy_entry* top = stack.back();
if (int(stack.size()) > depth_limit) TORRENT_FAIL_BDECODE(bdecode_errors::depth_exceeded);
if (start >= end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
char t = *start;
++start;
if (start >= end && t != 'e') TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
switch (top->type())
{
case lazy_entry::dict_t:
{
if (t == 'e')
{
top->set_end(start);
stack.pop_back();
continue;
}
if (!numeric(t)) TORRENT_FAIL_BDECODE(bdecode_errors::expected_string);
boost::int64_t len = t - '0';
bdecode_errors::error_code_enum e = bdecode_errors::no_error;
start = parse_int(start, end, ':', len, e);
if (e)
TORRENT_FAIL_BDECODE(e);
// remaining buffer size excluding ':'
const ptrdiff_t buff_size = end - start - 1;
if (len > buff_size)
TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
if (len < 0)
TORRENT_FAIL_BDECODE(bdecode_errors::overflow);
++start;
if (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
lazy_entry* ent = top->dict_append(start);
if (ent == 0) TORRENT_FAIL_BDECODE(boost::system::errc::not_enough_memory);
start += len;
if (start >= end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
stack.push_back(ent);
t = *start;
++start;
break;
}
case lazy_entry::list_t:
{
if (t == 'e')
{
top->set_end(start);
stack.pop_back();
continue;
}
lazy_entry* ent = top->list_append();
if (ent == 0) TORRENT_FAIL_BDECODE(boost::system::errc::not_enough_memory);
stack.push_back(ent);
break;
}
default: break;
}
--item_limit;
if (item_limit <= 0) TORRENT_FAIL_BDECODE(bdecode_errors::limit_exceeded);
top = stack.back();
switch (t)
{
case 'd':
top->construct_dict(start - 1);
continue;
case 'l':
top->construct_list(start - 1);
continue;
case 'i':
{
char const* int_start = start;
start = find_char(start, end, 'e');
top->construct_int(int_start, start - int_start);
if (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
TORRENT_ASSERT(*start == 'e');
++start;
stack.pop_back();
continue;
}
default:
{
if (!numeric(t))
TORRENT_FAIL_BDECODE(bdecode_errors::expected_value);
boost::int64_t len = t - '0';
bdecode_errors::error_code_enum e = bdecode_errors::no_error;
start = parse_int(start, end, ':', len, e);
if (e)
TORRENT_FAIL_BDECODE(e);
// remaining buffer size excluding ':'
const ptrdiff_t buff_size = end - start - 1;
if (len > buff_size)
TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
if (len < 0)
TORRENT_FAIL_BDECODE(bdecode_errors::overflow);
++start;
if (start == end) TORRENT_FAIL_BDECODE(bdecode_errors::unexpected_eof);
top->construct_string(start, int(len));
stack.pop_back();
start += len;
continue;
}
}
return 0;
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,705 |
jerryscript | efe63a5bbc5106164a08ee2eb415a7a701f5311f | parser_parse_for_statement_start (parser_context_t *context_p) /**< context */
{
parser_loop_statement_t loop;
JERRY_ASSERT (context_p->token.type == LEXER_KEYW_FOR);
lexer_next_token (context_p);
#if JERRY_ESNEXT
bool is_for_await = false;
if (context_p->token.type == LEXER_KEYW_AWAIT)
{
if (JERRY_UNLIKELY (context_p->token.lit_location.status_flags & LEXER_LIT_LOCATION_HAS_ESCAPE))
{
parser_raise_error (context_p, PARSER_ERR_INVALID_KEYWORD);
}
lexer_next_token (context_p);
is_for_await = true;
}
#endif /* JERRY_ESNEXT */
if (context_p->token.type != LEXER_LEFT_PAREN)
{
#if JERRY_ESNEXT
if (context_p->token.type == LEXER_LITERAL
&& context_p->token.keyword_type == LEXER_KEYW_AWAIT
&& !(context_p->token.lit_location.status_flags & LEXER_LIT_LOCATION_HAS_ESCAPE))
{
parser_raise_error (context_p, PARSER_ERR_FOR_AWAIT_NO_ASYNC);
}
#endif /* JERRY_ESNEXT */
parser_raise_error (context_p, PARSER_ERR_LEFT_PAREN_EXPECTED);
}
if (context_p->next_scanner_info_p->source_p == context_p->source_p)
{
parser_for_in_of_statement_t for_in_of_statement;
scanner_location_t start_location, end_location;
#if JERRY_ESNEXT
JERRY_ASSERT (context_p->next_scanner_info_p->type == SCANNER_TYPE_FOR_IN
|| context_p->next_scanner_info_p->type == SCANNER_TYPE_FOR_OF);
bool is_for_in = (context_p->next_scanner_info_p->type == SCANNER_TYPE_FOR_IN);
end_location = ((scanner_location_info_t *) context_p->next_scanner_info_p)->location;
scanner_release_next (context_p, sizeof (scanner_location_info_t));
scanner_get_location (&start_location, context_p);
lexer_next_token (context_p);
uint8_t token_type = LEXER_EOS;
bool has_context = false;
if (context_p->token.type == LEXER_KEYW_VAR
|| context_p->token.type == LEXER_KEYW_LET
|| context_p->token.type == LEXER_KEYW_CONST)
{
token_type = context_p->token.type;
has_context = context_p->next_scanner_info_p->source_p == context_p->source_p;
JERRY_ASSERT (!has_context || context_p->next_scanner_info_p->type == SCANNER_TYPE_BLOCK);
scanner_get_location (&start_location, context_p);
/* TODO: remove this after the pre-scanner supports strict mode detection. */
if (context_p->next_scanner_info_p->source_p == context_p->source_p
&& context_p->next_scanner_info_p->type == SCANNER_TYPE_LET_EXPRESSION)
{
scanner_release_next (context_p, sizeof (scanner_info_t));
}
}
else if (context_p->token.type == LEXER_LITERAL && lexer_token_is_let (context_p))
{
if (context_p->next_scanner_info_p->source_p == context_p->source_p
&& context_p->next_scanner_info_p->type == SCANNER_TYPE_LET_EXPRESSION)
{
scanner_release_next (context_p, sizeof (scanner_info_t));
}
else
{
token_type = LEXER_KEYW_LET;
has_context = (context_p->next_scanner_info_p->source_p == context_p->source_p);
scanner_get_location (&start_location, context_p);
}
}
if (has_context)
{
has_context = parser_push_block_context (context_p, true);
}
scanner_set_location (context_p, &end_location);
#else /* !JERRY_ESNEXT */
JERRY_ASSERT (context_p->next_scanner_info_p->type == SCANNER_TYPE_FOR_IN);
bool is_for_in = true;
scanner_get_location (&start_location, context_p);
scanner_set_location (context_p, &((scanner_location_info_t *) context_p->next_scanner_info_p)->location);
scanner_release_next (context_p, sizeof (scanner_location_info_t));
#endif /* JERRY_ESNEXT */
/* The length of both 'in' and 'of' is two. */
const uint8_t *source_end_p = context_p->source_p - 2;
scanner_seek (context_p);
#if JERRY_ESNEXT
if (is_for_in && is_for_await)
{
context_p->token.line = context_p->line;
context_p->token.column = context_p->column - 2;
parser_raise_error (context_p, PARSER_ERR_FOR_AWAIT_NO_OF);
}
#endif /* JERRY_ESNEXT */
lexer_next_token (context_p);
int options = is_for_in ? PARSE_EXPR : PARSE_EXPR_LEFT_HAND_SIDE;
parser_parse_expression (context_p, options);
if (context_p->token.type != LEXER_RIGHT_PAREN)
{
parser_raise_error (context_p, PARSER_ERR_RIGHT_PAREN_EXPECTED);
}
#ifndef JERRY_NDEBUG
PARSER_PLUS_EQUAL_U16 (context_p->context_stack_depth,
is_for_in ? PARSER_FOR_IN_CONTEXT_STACK_ALLOCATION
: PARSER_FOR_OF_CONTEXT_STACK_ALLOCATION);
#endif /* !JERRY_NDEBUG */
cbc_ext_opcode_t init_opcode = CBC_EXT_FOR_IN_INIT;
#if JERRY_ESNEXT
if (!is_for_in)
{
init_opcode = is_for_await ? CBC_EXT_FOR_AWAIT_OF_INIT : CBC_EXT_FOR_OF_INIT;
}
#endif /* JERRY_ESNEXT */
parser_emit_cbc_ext_forward_branch (context_p, init_opcode, &for_in_of_statement.branch);
JERRY_ASSERT (context_p->last_cbc_opcode == PARSER_CBC_UNAVAILABLE);
for_in_of_statement.start_offset = context_p->byte_code_size;
#if JERRY_ESNEXT
if (has_context)
{
parser_emit_cbc_ext (context_p, CBC_EXT_CLONE_CONTEXT);
}
#endif /* JERRY_ESNEXT */
/* The expression parser must not read the 'in' or 'of' tokens. */
scanner_get_location (&end_location, context_p);
scanner_set_location (context_p, &start_location);
const uint8_t *original_source_end_p = context_p->source_end_p;
context_p->source_end_p = source_end_p;
scanner_seek (context_p);
#if JERRY_ESNEXT
if (token_type == LEXER_EOS)
{
lexer_next_token (context_p);
if (context_p->token.type == LEXER_LEFT_SQUARE || context_p->token.type == LEXER_LEFT_BRACE)
{
token_type = context_p->token.type;
}
}
#else /* !JERRY_ESNEXT */
lexer_next_token (context_p);
uint8_t token_type = context_p->token.type;
#endif /* JERRY_ESNEXT */
switch (token_type)
{
#if JERRY_ESNEXT
case LEXER_KEYW_LET:
case LEXER_KEYW_CONST:
#endif /* JERRY_ESNEXT */
case LEXER_KEYW_VAR:
{
#if JERRY_ESNEXT
if (lexer_check_next_characters (context_p, LIT_CHAR_LEFT_SQUARE, LIT_CHAR_LEFT_BRACE))
{
parser_emit_cbc_ext (context_p, is_for_in ? CBC_EXT_FOR_IN_GET_NEXT
: CBC_EXT_FOR_OF_GET_NEXT);
parser_pattern_flags_t flags = (PARSER_PATTERN_BINDING | PARSER_PATTERN_TARGET_ON_STACK);
if (context_p->next_scanner_info_p->source_p == (context_p->source_p + 1))
{
if (context_p->next_scanner_info_p->type == SCANNER_TYPE_INITIALIZER)
{
scanner_release_next (context_p, sizeof (scanner_location_info_t));
}
else
{
JERRY_ASSERT (context_p->next_scanner_info_p->type == SCANNER_TYPE_LITERAL_FLAGS);
if (context_p->next_scanner_info_p->u8_arg & SCANNER_LITERAL_OBJECT_HAS_REST)
{
flags |= PARSER_PATTERN_HAS_REST_ELEMENT;
}
scanner_release_next (context_p, sizeof (scanner_info_t));
}
}
if (token_type == LEXER_KEYW_LET)
{
flags |= PARSER_PATTERN_LET;
}
else if (token_type == LEXER_KEYW_CONST)
{
flags |= PARSER_PATTERN_CONST;
}
parser_parse_initializer_by_next_char (context_p, flags);
break;
}
#endif /* JERRY_ESNEXT */
lexer_expect_identifier (context_p, LEXER_IDENT_LITERAL);
#if JERRY_ESNEXT
if (context_p->token.keyword_type == LEXER_KEYW_LET
&& token_type != LEXER_KEYW_VAR)
{
parser_raise_error (context_p, PARSER_ERR_LEXICAL_LET_BINDING);
}
#endif /* JERRY_ESNEXT */
JERRY_ASSERT (context_p->token.type == LEXER_LITERAL
&& context_p->token.lit_location.type == LEXER_IDENT_LITERAL);
uint16_t literal_index = context_p->lit_object.index;
lexer_next_token (context_p);
if (context_p->token.type == LEXER_ASSIGN)
{
#if JERRY_ESNEXT
if ((context_p->status_flags & PARSER_IS_STRICT) || !is_for_in)
{
parser_raise_error (context_p, PARSER_ERR_FOR_IN_OF_DECLARATION);
}
#endif /* JERRY_ESNEXT */
parser_branch_t branch;
/* Initialiser is never executed. */
parser_emit_cbc_forward_branch (context_p, CBC_JUMP_FORWARD, &branch);
lexer_next_token (context_p);
parser_parse_expression_statement (context_p, PARSE_EXPR_NO_COMMA);
parser_set_branch_to_current_position (context_p, &branch);
}
parser_emit_cbc_ext (context_p, is_for_in ? CBC_EXT_FOR_IN_GET_NEXT
: CBC_EXT_FOR_OF_GET_NEXT);
#if JERRY_ESNEXT
#ifndef JERRY_NDEBUG
if (literal_index < PARSER_REGISTER_START
&& has_context
&& !scanner_literal_is_created (context_p, literal_index))
{
context_p->global_status_flags |= ECMA_PARSE_INTERNAL_FOR_IN_OFF_CONTEXT_ERROR;
}
#endif /* !JERRY_NDEBUG */
uint16_t opcode = (has_context ? CBC_ASSIGN_LET_CONST : CBC_ASSIGN_SET_IDENT);
parser_emit_cbc_literal (context_p, opcode, literal_index);
#else /* !JERRY_ESNEXT */
parser_emit_cbc_literal (context_p, CBC_ASSIGN_SET_IDENT, literal_index);
#endif /* JERRY_ESNEXT */
break;
}
#if JERRY_ESNEXT
case LEXER_LEFT_BRACE:
case LEXER_LEFT_SQUARE:
{
if (context_p->next_scanner_info_p->source_p == context_p->source_p
&& context_p->next_scanner_info_p->type == SCANNER_TYPE_LITERAL_FLAGS
&& (context_p->next_scanner_info_p->u8_arg & SCANNER_LITERAL_DESTRUCTURING_FOR))
{
parser_emit_cbc_ext (context_p, is_for_in ? CBC_EXT_FOR_IN_GET_NEXT
: CBC_EXT_FOR_OF_GET_NEXT);
uint32_t flags = PARSER_PATTERN_TARGET_ON_STACK;
if (context_p->next_scanner_info_p->u8_arg & SCANNER_LITERAL_OBJECT_HAS_REST)
{
flags |= PARSER_PATTERN_HAS_REST_ELEMENT;
}
scanner_release_next (context_p, sizeof (scanner_info_t));
parser_parse_initializer (context_p, flags);
/* Pop the value returned by GET_NEXT. */
parser_emit_cbc (context_p, CBC_POP);
break;
}
/* FALLTHRU */
}
#endif /* JERRY_ESNEXT */
default:
{
uint16_t opcode;
parser_parse_expression (context_p, PARSE_EXPR_LEFT_HAND_SIDE);
opcode = context_p->last_cbc_opcode;
/* The CBC_EXT_FOR_IN_CREATE_CONTEXT flushed the opcode combiner. */
JERRY_ASSERT (opcode != CBC_PUSH_TWO_LITERALS
&& opcode != CBC_PUSH_THREE_LITERALS);
opcode = parser_check_left_hand_side_expression (context_p, opcode);
parser_emit_cbc_ext (context_p, is_for_in ? CBC_EXT_FOR_IN_GET_NEXT
: CBC_EXT_FOR_OF_GET_NEXT);
parser_flush_cbc (context_p);
context_p->last_cbc_opcode = opcode;
break;
}
}
if (context_p->token.type != LEXER_EOS)
{
#if JERRY_ESNEXT
parser_raise_error (context_p, is_for_in ? PARSER_ERR_IN_EXPECTED : PARSER_ERR_OF_EXPECTED);
#else /* !JERRY_ESNEXT */
parser_raise_error (context_p, PARSER_ERR_IN_EXPECTED);
#endif /* JERRY_ESNEXT */
}
parser_flush_cbc (context_p);
scanner_set_location (context_p, &end_location);
context_p->source_end_p = original_source_end_p;
lexer_next_token (context_p);
loop.branch_list_p = NULL;
parser_stack_push (context_p, &for_in_of_statement, sizeof (parser_for_in_of_statement_t));
parser_stack_push (context_p, &loop, sizeof (parser_loop_statement_t));
uint8_t for_type = PARSER_STATEMENT_FOR_IN;
#if JERRY_ESNEXT
if (!is_for_in)
{
for_type = is_for_await ? PARSER_STATEMENT_FOR_AWAIT_OF : PARSER_STATEMENT_FOR_OF;
}
#endif /* JERRY_ESNEXT */
parser_stack_push_uint8 (context_p, for_type);
parser_stack_iterator_init (context_p, &context_p->last_statement);
return;
}
lexer_next_token (context_p);
if (context_p->token.type != LEXER_SEMICOLON)
{
#if JERRY_ESNEXT
const uint8_t *source_p = context_p->source_p;
#endif /* JERRY_ESNEXT */
switch (context_p->token.type)
{
#if JERRY_ESNEXT
case LEXER_LITERAL:
{
if (!lexer_token_is_let (context_p))
{
parser_parse_expression_statement (context_p, PARSE_EXPR);
break;
}
/* FALLTHRU */
}
case LEXER_KEYW_LET:
{
if (context_p->next_scanner_info_p->source_p == context_p->source_p
&& context_p->next_scanner_info_p->type != SCANNER_TYPE_BLOCK)
{
if (context_p->next_scanner_info_p->type == SCANNER_TYPE_LET_EXPRESSION)
{
scanner_release_next (context_p, sizeof (scanner_info_t));
}
parser_parse_expression_statement (context_p, PARSE_EXPR);
break;
}
context_p->token.type = LEXER_KEYW_LET;
/* FALLTHRU */
}
case LEXER_KEYW_CONST:
{
if (context_p->next_scanner_info_p->source_p == source_p)
{
parser_push_block_context (context_p, true);
}
/* FALLTHRU */
}
#endif /* JERRY_ESNEXT */
case LEXER_KEYW_VAR:
{
parser_parse_var_statement (context_p);
break;
}
default:
{
parser_parse_expression_statement (context_p, PARSE_EXPR);
break;
}
}
if (context_p->token.type != LEXER_SEMICOLON)
{
parser_raise_error (context_p, PARSER_ERR_SEMICOLON_EXPECTED);
}
}
#if JERRY_ESNEXT
if (is_for_await)
{
parser_raise_error (context_p, PARSER_ERR_FOR_AWAIT_NO_OF);
}
#endif /* JERRY_ESNEXT */
JERRY_ASSERT (context_p->next_scanner_info_p->source_p != context_p->source_p
|| context_p->next_scanner_info_p->type == SCANNER_TYPE_FOR);
if (context_p->next_scanner_info_p->source_p != context_p->source_p
|| ((scanner_for_info_t *) context_p->next_scanner_info_p)->end_location.source_p == NULL)
{
if (context_p->next_scanner_info_p->source_p == context_p->source_p)
{
/* Even though the scanning is failed, there might be valid statements
* inside the for statement which depend on scanner info blocks. */
scanner_release_next (context_p, sizeof (scanner_for_info_t));
}
/* The prescanner couldn't find the second semicolon or the closing paranthesis. */
lexer_next_token (context_p);
parser_parse_expression (context_p, PARSE_EXPR);
if (context_p->token.type != LEXER_SEMICOLON)
{
parser_raise_error (context_p, PARSER_ERR_SEMICOLON_EXPECTED);
}
lexer_next_token (context_p);
parser_parse_expression_statement (context_p, PARSE_EXPR);
JERRY_ASSERT (context_p->token.type != LEXER_RIGHT_PAREN);
parser_raise_error (context_p, PARSER_ERR_RIGHT_PAREN_EXPECTED);
}
parser_for_statement_t for_statement;
scanner_for_info_t *for_info_p = (scanner_for_info_t *) context_p->next_scanner_info_p;
parser_emit_cbc_forward_branch (context_p, CBC_JUMP_FORWARD, &for_statement.branch);
JERRY_ASSERT (context_p->last_cbc_opcode == PARSER_CBC_UNAVAILABLE);
for_statement.start_offset = context_p->byte_code_size;
scanner_get_location (&for_statement.condition_location, context_p);
for_statement.expression_location = for_info_p->expression_location;
scanner_set_location (context_p, &for_info_p->end_location);
scanner_release_next (context_p, sizeof (scanner_for_info_t));
scanner_seek (context_p);
lexer_next_token (context_p);
loop.branch_list_p = NULL;
parser_stack_push (context_p, &for_statement, sizeof (parser_for_statement_t));
parser_stack_push (context_p, &loop, sizeof (parser_loop_statement_t));
parser_stack_push_uint8 (context_p, PARSER_STATEMENT_FOR);
parser_stack_iterator_init (context_p, &context_p->last_statement);
} /* parser_parse_for_statement_start */ | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,526 |
Chrome | fd6a5115103b3e6a52ce15858c5ad4956df29300 | void AudioNode::Dispose() {
DCHECK(IsMainThread());
#if DEBUG_AUDIONODE_REFERENCES
fprintf(stderr, "[%16p]: %16p: %2d: AudioNode::dispose %16p\n", context(),
this, Handler().GetNodeType(), handler_.get());
#endif
BaseAudioContext::GraphAutoLocker locker(context());
Handler().Dispose();
if (context()->HasRealtimeConstraint()) {
context()->GetDeferredTaskHandler().AddRenderingOrphanHandler(
std::move(handler_));
} else {
if (context()->ContextState() == BaseAudioContext::kRunning) {
context()->GetDeferredTaskHandler().AddRenderingOrphanHandler(
std::move(handler_));
}
}
}
| 1 | CVE-2018-6060 | CWE-416 | Use After Free | The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
Phase: Architecture and Design
Strategy: Language Selection
Choose a language that provides automatic memory management.
Phase: Implementation
Strategy: Attack Surface Reduction
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.
Effectiveness: Defense in Depth
Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution. | 3,987 |
ImageMagick6 | 6ce6d25b47caf9b6b2979a510b6202ce0f3dd2d4 | MagickExport MagickBooleanType AnimateImages(const ImageInfo *image_info,
Image *image)
{
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
(void) image_info;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
(void) ThrowMagickException(&image->exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (X11)",
image->filename);
return(MagickFalse);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,580 |
vim | 60ae0e71490c97f2871a6344aca61cacf220f813 | skip_string(char_u *p)
{
int i;
// We loop, because strings may be concatenated: "date""time".
for ( ; ; ++p)
{
if (p[0] == '\'') // 'c' or '\n' or '\000'
{
if (p[1] == NUL) // ' at end of line
break;
i = 2;
if (p[1] == '\\' && p[2] != NUL) // '\n' or '\000'
{
++i;
while (vim_isdigit(p[i - 1])) // '\000'
++i;
}
if (p[i] == '\'') // check for trailing '
{
p += i;
continue;
}
}
else if (p[0] == '"') // start of string
{
for (++p; p[0]; ++p)
{
if (p[0] == '\\' && p[1] != NUL)
++p;
else if (p[0] == '"') // end of string
break;
}
if (p[0] == '"')
continue; // continue for another string
}
else if (p[0] == 'R' && p[1] == '"')
{
// Raw string: R"[delim](...)[delim]"
char_u *delim = p + 2;
char_u *paren = vim_strchr(delim, '(');
if (paren != NULL)
{
size_t delim_len = paren - delim;
for (p += 3; *p; ++p)
if (p[0] == ')' && STRNCMP(p + 1, delim, delim_len) == 0
&& p[delim_len + 1] == '"')
{
p += delim_len + 1;
break;
}
if (p[0] == '"')
continue; // continue for another string
}
}
break; // no string found
}
if (!*p)
--p; // backup from NUL
return p;
} | 1 | CVE-2022-1733 | CWE-787 | Out-of-bounds Write | The product writes data past the end, or before the beginning, of the intended buffer. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333].
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 487 |
Android | a2d1d85726aa2a3126e9c331a8e00a8c319c9e2b | void NuPlayer::NuPlayerStreamListener::issueCommand(
Command cmd, bool synchronous, const sp<AMessage> &extra) {
CHECK(!synchronous);
QueueEntry entry;
entry.mIsCommand = true;
entry.mCommand = cmd;
entry.mExtra = extra;
Mutex::Autolock autoLock(mLock);
mQueue.push_back(entry);
if (mSendDataNotification) {
mSendDataNotification = false;
if (mTargetHandler != NULL) {
(new AMessage(kWhatMoreDataQueued, mTargetHandler))->post();
}
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,402 |
linux | f3d3342602f8bcbf37d7c46641cb9bca7618eb1c | int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov,
struct sockaddr_storage *kern_address, int mode)
{
int tot_len;
if (kern_msg->msg_namelen) {
if (mode == VERIFY_READ) {
int err = move_addr_to_kernel(kern_msg->msg_name,
kern_msg->msg_namelen,
kern_address);
if (err < 0)
return err;
}
kern_msg->msg_name = kern_address;
} else
kern_msg->msg_name = NULL;
tot_len = iov_from_user_compat_to_kern(kern_iov,
(struct compat_iovec __user *)kern_msg->msg_iov,
kern_msg->msg_iovlen);
if (tot_len >= 0)
kern_msg->msg_iov = kern_iov;
return tot_len;
}
| 1 | CVE-2013-7271 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 4,215 |
Chrome | 9ce8793d2a8ca2cc0cb3c26fa1ca0eef3d9bc999 | void PPB_URLLoader_Impl::RunCallback(int32_t result) {
if (!pending_callback_.get()) {
CHECK(main_document_loader_);
return;
}
TrackedCallback::ClearAndRun(&pending_callback_, result);
}
| 1 | CVE-2012-2869 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 344 |
mutt | 3b6f6b829718ec8a7cf3eb6997d86e83e6c38567 | static void rfc2231_join_continuations (PARAMETER **head,
struct rfc2231_parameter *par)
{
struct rfc2231_parameter *q;
char attribute[STRING];
char charset[STRING];
char *value = NULL;
char *valp;
int encoded;
size_t l, vl;
while (par)
{
value = NULL; l = 0;
strfcpy (attribute, par->attribute, sizeof (attribute));
if ((encoded = par->encoded))
valp = rfc2231_get_charset (par->value, charset, sizeof (charset));
else
valp = par->value;
do
{
if (encoded && par->encoded)
rfc2231_decode_one (par->value, valp);
vl = strlen (par->value);
safe_realloc (&value, l + vl + 1);
strcpy (value + l, par->value); /* __STRCPY_CHECKED__ */
l += vl;
q = par->next;
rfc2231_free_parameter (&par);
if ((par = q))
valp = par->value;
} while (par && !strcmp (par->attribute, attribute));
if (value)
{
if (encoded)
mutt_convert_string (&value, charset, Charset, MUTT_ICONV_HOOK_FROM);
*head = mutt_new_parameter ();
(*head)->attribute = safe_strdup (attribute);
(*head)->value = value;
head = &(*head)->next;
}
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,991 |
linux | 0a9ab9bdb3e891762553f667066190c1d22ad62b | static void hidp_stop(struct hid_device *hid)
{
struct hidp_session *session = hid->driver_data;
skb_queue_purge(&session->ctrl_transmit);
skb_queue_purge(&session->intr_transmit);
hid->claimed = 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,910 |
postgres | 31400a673325147e1205326008e32135a78b4d8a | box_sub(PG_FUNCTION_ARGS)
{
BOX *box = PG_GETARG_BOX_P(0);
Point *p = PG_GETARG_POINT_P(1);
PG_RETURN_BOX_P(box_construct((box->high.x - p->x),
(box->low.x - p->x),
(box->high.y - p->y),
(box->low.y - p->y)));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,197 |
hhvm | dabd48caf74995e605f1700344f1ff4a5d83441d | bool JSON_parser(Variant &z, const char *p, int length, bool const assoc,
int depth, int64_t options) {
// No GC safepoints during JSON parsing, please. Code is not re-entrant.
NoHandleSurpriseScope no_surprise(SafepointFlags);
json_parser *json = s_json_parser.get(); /* the parser state */
// Clear and reuse the thread-local string buffers. They are only freed if
// they exceed kMaxPersistentStringBufferCapacity at exit or if the thread
// is explicitly flushed (e.g., due to being idle).
json->initSb(length);
SCOPE_EXIT {
constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024;
if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb();
};
// SimpleParser only handles the most common set of options. Also, only use it
// if its array nesting depth check is *more* restrictive than what the user
// asks for, to ensure that the precise semantics of the general case is
// applied for all nesting overflows.
if (assoc &&
options == (options & (k_JSON_FB_LOOSE |
k_JSON_FB_DARRAYS |
k_JSON_FB_DARRAYS_AND_VARRAYS |
k_JSON_FB_HACK_ARRAYS |
k_JSON_FB_THRIFT_SIMPLE_JSON |
k_JSON_FB_LEGACY_HACK_ARRAYS)) &&
depth >= SimpleParser::kMaxArrayDepth &&
length <= RuntimeOption::EvalSimpleJsonMaxLength &&
SimpleParser::TryParse(p, length, json->tl_buffer.tv, z,
get_container_type_from_options(options),
options & k_JSON_FB_THRIFT_SIMPLE_JSON)) {
return true;
}
int b; /* the next character */
int c; /* the next character class */
int s; /* the next state */
int state = 0;
/*<fb>*/
bool const loose = options & k_JSON_FB_LOOSE;
JSONContainerType const container_type =
get_container_type_from_options(options);
int qchr = 0;
int8_t const *byte_class;
int8_t const (*next_state_table)[32];
if (loose) {
byte_class = loose_ascii_class;
next_state_table = loose_state_transition_table;
} else {
byte_class = ascii_class;
next_state_table = state_transition_table;
}
/*</fb>*/
UncheckedBuffer *buf = &json->sb_buf;
UncheckedBuffer *key = &json->sb_key;
DataType type = kInvalidDataType;
unsigned short escaped_bytes = 0;
auto reset_type = [&] { type = kInvalidDataType; };
json->depth = depth;
// Since the stack is maintainined on a per request basis, for performance
// reasons, it only makes sense to expand if necessary and cycles are wasted
// contracting. Calls with a depth other than default should be rare.
if (depth > json->stack.size()) {
json->stack.resize(depth);
}
SCOPE_EXIT {
if (json->stack.empty()) return;
for (int i = 0; i <= json->mark; i++) {
json->stack[i].key.reset();
json->stack[i].val.unset();
}
json->mark = -1;
};
json->mark = json->top = -1;
push(json, Mode::DONE);
UTF8To16Decoder decoder(p, length, loose);
for (;;) {
b = decoder.decode();
// Fast-case most common transition: append a simple string character.
if (state == 3 && type == KindOfString) {
while (b != '\"' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') {
buf->append((char)b);
b = decoder.decode();
}
}
if (b == UTF8_END) break; // UTF-8 decoding finishes successfully.
if (b == UTF8_ERROR) {
s_json_parser->error_code = JSON_ERROR_UTF8;
return false;
}
assertx(b >= 0);
if ((b & 127) == b) {
/*<fb>*/
c = byte_class[b];
/*</fb>*/
if (c <= S_ERR) {
s_json_parser->error_code = JSON_ERROR_CTRL_CHAR;
return false;
}
} else {
c = S_ETC;
}
/*
Get the next state from the transition table.
*/
/*<fb>*/
s = next_state_table[state][c];
if (s == -4) {
if (b != qchr) {
s = 3;
} else {
qchr = 0;
}
}
/*</fb>*/
if (s < 0) {
/*
Perform one of the predefined actions.
*/
switch (s) {
/*
empty }
*/
case -9:
/*<fb>*/
if (json->top == 1) z = json->stack[json->top].val;
else {
/*</fb>*/
attach_zval(json, json->stack[json->top].key, assoc, container_type);
/*<fb>*/
}
/*</fb>*/
if (!pop(json, Mode::KEY)) {
return false;
}
state = 9;
break;
/*
{
*/
case -8:
if (!push(json, Mode::KEY)) {
s_json_parser->error_code = JSON_ERROR_DEPTH;
return false;
}
state = 1;
if (json->top > 0) {
Variant &top = json->stack[json->top].val;
/*<fb>*/
if (container_type == JSONContainerType::COLLECTIONS) {
// stable_maps is meaningless
top = req::make<c_Map>();
} else {
/*</fb>*/
if (!assoc) {
top = SystemLib::AllocStdClassObject();
/* <fb> */
} else if (container_type == JSONContainerType::HACK_ARRAYS) {
top = Array::CreateDict();
} else if (container_type == JSONContainerType::DARRAYS ||
container_type == JSONContainerType::DARRAYS_AND_VARRAYS)
{
top = Array::CreateDArray();
/* </fb> */
} else if (
container_type == JSONContainerType::LEGACY_HACK_ARRAYS) {
auto arr = staticEmptyDictArray()->copy();
arr->setLegacyArray(true);
top = arr;
} else {
top = Array::CreateDArray();
}
/*<fb>*/
}
/*</fb>*/
json->stack[json->top].key = copy_and_clear(*key);
reset_type();
}
break;
/*
}
*/
case -7:
/*** BEGIN Facebook: json_utf8_loose ***/
/*
If this is a trailing comma in an object definition,
we're in Mode::KEY. In that case, throw that off the
stack and restore Mode::OBJECT so that we pretend the
trailing comma just didn't happen.
*/
if (loose) {
if (pop(json, Mode::KEY)) {
push(json, Mode::OBJECT);
}
}
/*** END Facebook: json_utf8_loose ***/
if (type != kInvalidDataType &&
json->stack[json->top].mode == Mode::OBJECT) {
Variant mval;
json_create_zval(mval, *buf, type, options);
Variant &top = json->stack[json->top].val;
object_set(json, top, copy_and_clear(*key),
mval, assoc, container_type);
buf->clear();
reset_type();
}
/*<fb>*/
if (json->top == 1) z = json->stack[json->top].val;
else {
/*</fb>*/
attach_zval(json, json->stack[json->top].key,
assoc, container_type);
/*<fb>*/
}
/*</fb>*/
if (!pop(json, Mode::OBJECT)) {
s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH;
return false;
}
state = 9;
break;
/*
[
*/
case -6:
if (!push(json, Mode::ARRAY)) {
s_json_parser->error_code = JSON_ERROR_DEPTH;
return false;
}
state = 2;
if (json->top > 0) {
Variant &top = json->stack[json->top].val;
/*<fb>*/
if (container_type == JSONContainerType::COLLECTIONS) {
top = req::make<c_Vector>();
} else if (container_type == JSONContainerType::HACK_ARRAYS) {
top = Array::CreateVec();
} else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) {
top = Array::CreateVArray();
} else if (container_type == JSONContainerType::DARRAYS) {
top = Array::CreateDArray();
} else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) {
auto arr = staticEmptyVecArray()->copy();
arr->setLegacyArray(true);
top = arr;
} else {
top = Array::CreateDArray();
}
/*</fb>*/
json->stack[json->top].key = copy_and_clear(*key);
reset_type();
}
break;
/*
]
*/
case -5:
{
if (type != kInvalidDataType &&
json->stack[json->top].mode == Mode::ARRAY) {
Variant mval;
json_create_zval(mval, *buf, type, options);
auto& top = json->stack[json->top].val;
if (container_type == JSONContainerType::COLLECTIONS) {
collections::append(top.getObjectData(), mval.asTypedValue());
} else {
top.asArrRef().append(mval);
}
buf->clear();
reset_type();
}
/*<fb>*/
if (json->top == 1) z = json->stack[json->top].val;
else {
/*</fb>*/
attach_zval(json, json->stack[json->top].key, assoc,
container_type);
/*<fb>*/
}
/*</fb>*/
if (!pop(json, Mode::ARRAY)) {
s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH;
return false;
}
state = 9;
}
break;
/*
"
*/
case -4:
switch (json->stack[json->top].mode) {
case Mode::KEY:
state = 27;
std::swap(buf, key);
reset_type();
break;
case Mode::ARRAY:
case Mode::OBJECT:
state = 9;
break;
case Mode::DONE:
if (type == KindOfString) {
z = copy_and_clear(*buf);
state = 9;
break;
}
/* fall through if not KindOfString */
default:
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
break;
/*
,
*/
case -3:
{
Variant mval;
if (type != kInvalidDataType &&
(json->stack[json->top].mode == Mode::OBJECT ||
json->stack[json->top].mode == Mode::ARRAY)) {
json_create_zval(mval, *buf, type, options);
}
switch (json->stack[json->top].mode) {
case Mode::OBJECT:
if (pop(json, Mode::OBJECT) &&
push(json, Mode::KEY)) {
if (type != kInvalidDataType) {
Variant &top = json->stack[json->top].val;
object_set(
json,
top,
copy_and_clear(*key),
mval,
assoc,
container_type
);
}
state = 29;
}
break;
case Mode::ARRAY:
if (type != kInvalidDataType) {
auto& top = json->stack[json->top].val;
if (container_type == JSONContainerType::COLLECTIONS) {
collections::append(top.getObjectData(), mval.asTypedValue());
} else {
top.asArrRef().append(mval);
}
}
state = 28;
break;
default:
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
buf->clear();
reset_type();
check_non_safepoint_surprise();
}
break;
/*<fb>*/
/*
: (after unquoted string)
*/
case -10:
if (json->stack[json->top].mode == Mode::KEY) {
state = 27;
std::swap(buf, key);
reset_type();
s = -2;
} else {
s = 3;
break;
}
/*</fb>*/
/*
:
*/
case -2:
if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) {
state = 28;
break;
}
/*
syntax error
*/
case -1:
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
} else {
/*
Change the state and iterate.
*/
bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON;
if (type == KindOfString) {
if (/*<fb>*/(/*</fb>*/s == 3/*<fb>*/ || s == 30)/*</fb>*/ &&
state != 8) {
if (state != 4) {
utf16_to_utf8(*buf, b);
} else {
switch (b) {
case 'b': buf->append('\b'); break;
case 't': buf->append('\t'); break;
case 'n': buf->append('\n'); break;
case 'f': buf->append('\f'); break;
case 'r': buf->append('\r'); break;
default:
utf16_to_utf8(*buf, b);
break;
}
}
} else if (s == 6) {
if (UNLIKELY(is_tsimplejson)) {
if (UNLIKELY(b != '0')) {
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
escaped_bytes = 0;
} else {
escaped_bytes = dehexchar(b) << 12;
}
} else if (s == 7) {
if (UNLIKELY(is_tsimplejson)) {
if (UNLIKELY(b != '0')) {
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
}
} else {
escaped_bytes += dehexchar(b) << 8;
}
} else if (s == 8) {
escaped_bytes += dehexchar(b) << 4;
} else if (s == 3 && state == 8) {
escaped_bytes += dehexchar(b);
if (UNLIKELY(is_tsimplejson)) {
buf->append((char)escaped_bytes);
} else {
utf16_to_utf8(*buf, escaped_bytes);
}
}
} else if ((type == kInvalidDataType || type == KindOfNull) &&
(c == S_DIG || c == S_ZER)) {
type = KindOfInt64;
buf->append((char)b);
} else if (type == KindOfInt64 && s == 24) {
type = KindOfDouble;
buf->append((char)b);
} else if ((type == kInvalidDataType || type == KindOfNull ||
type == KindOfInt64) &&
c == S_DOT) {
type = KindOfDouble;
buf->append((char)b);
} else if (type != KindOfString && c == S_QUO) {
type = KindOfString;
/*<fb>*/qchr = b;/*</fb>*/
} else if ((type == kInvalidDataType || type == KindOfNull ||
type == KindOfInt64 || type == KindOfDouble) &&
((state == 12 && s == 9) ||
(state == 16 && s == 9))) {
type = KindOfBoolean;
} else if (type == kInvalidDataType && state == 19 && s == 9) {
type = KindOfNull;
} else if (type != KindOfString && c > S_WSP) {
utf16_to_utf8(*buf, b);
}
state = s;
}
}
if (state == 9 && pop(json, Mode::DONE)) {
s_json_parser->error_code = JSON_ERROR_NONE;
return true;
}
s_json_parser->error_code = JSON_ERROR_SYNTAX;
return false;
} | 1 | CVE-2020-1892 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 3,991 |
ImageMagick | 716496e6df0add89e9679d6da9c0afca814cfe49 | static inline void ReadTIM2ImageHeader(Image *image,TIM2ImageHeader *header)
{
header->total_size=ReadBlobLSBLong(image);
header->clut_size=ReadBlobLSBLong(image);
header->image_size=ReadBlobLSBLong(image);
header->header_size=ReadBlobLSBShort(image);
header->clut_color_count=ReadBlobLSBShort(image);
header->img_format=(unsigned char) ReadBlobByte(image);
header->mipmap_count=(unsigned char) ReadBlobByte(image);
header->clut_type=(unsigned char) ReadBlobByte(image);
header->bpp_type=(unsigned char) ReadBlobByte(image);
header->width=ReadBlobLSBShort(image);
header->height=ReadBlobLSBShort(image);
header->GsTex0=ReadBlobMSBLongLong(image);
header->GsTex1=ReadBlobMSBLongLong(image);
header->GsRegs=ReadBlobMSBLong(image);
header->GsTexClut=ReadBlobMSBLong(image);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,659 |
linux-2.6 | 6a6029b8cefe0ca7e82f27f3904dbedba3de4e06 | static int cfs_rq_best_prio(struct cfs_rq *cfs_rq)
{
struct sched_entity *curr;
struct task_struct *p;
if (!cfs_rq->nr_running || !first_fair(cfs_rq))
return MAX_PRIO;
curr = cfs_rq->curr;
if (!curr)
curr = __pick_next_entity(cfs_rq);
p = task_of(curr);
return p->prio;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,885 |
ImageMagick6 | b522d2d857d2f75b659936b59b0da9df1682c256 | static inline double MagickLog10(const double x)
{
#define Log10Epsilon (1.0e-11)
if (fabs(x) < Log10Epsilon)
return(log10(Log10Epsilon));
return(log10(fabs(x)));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,855 |
Chrome | 96dbafe288dbe2f0cc45fa3c39daf6d0c37acbab | xsltRegisterExtModuleElement(const xmlChar * name, const xmlChar * URI,
xsltPreComputeFunction precomp,
xsltTransformFunction transform)
{
int ret;
xsltExtElementPtr ext;
if ((name == NULL) || (URI == NULL) || (transform == NULL))
return (-1);
if (xsltElementsHash == NULL)
xsltElementsHash = xmlHashCreate(10);
if (xsltElementsHash == NULL)
return (-1);
xmlMutexLock(xsltExtMutex);
ext = xsltNewExtElement(precomp, transform);
if (ext == NULL) {
ret = -1;
goto done;
}
xmlHashUpdateEntry2(xsltElementsHash, name, URI, (void *) ext,
(xmlHashDeallocator) xsltFreeExtElement);
done:
xmlMutexUnlock(xsltExtMutex);
return (0);
}
| 1 | CVE-2016-1683 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 6,474 |
linux | 2690d97ade05c5325cbf7c72b94b90d265659886 | static unsigned int help(struct sk_buff *skb,
enum ip_conntrack_info ctinfo,
unsigned int protoff,
unsigned int matchoff,
unsigned int matchlen,
struct nf_conntrack_expect *exp)
{
char buffer[sizeof("4294967296 65635")];
struct nf_conn *ct = exp->master;
union nf_inet_addr newaddr;
u_int16_t port;
unsigned int ret;
/* Reply comes from server. */
newaddr = ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.u3;
exp->saved_proto.tcp.port = exp->tuple.dst.u.tcp.port;
exp->dir = IP_CT_DIR_REPLY;
exp->expectfn = nf_nat_follow_master;
/* Try to get same port: if not, try to change it. */
for (port = ntohs(exp->saved_proto.tcp.port); port != 0; port++) {
int ret;
exp->tuple.dst.u.tcp.port = htons(port);
ret = nf_ct_expect_related(exp);
if (ret == 0)
break;
else if (ret != -EBUSY) {
port = 0;
break;
}
}
if (port == 0) {
nf_ct_helper_log(skb, ct, "all ports in use");
return NF_DROP;
}
/* strlen("\1DCC CHAT chat AAAAAAAA P\1\n")=27
* strlen("\1DCC SCHAT chat AAAAAAAA P\1\n")=28
* strlen("\1DCC SEND F AAAAAAAA P S\1\n")=26
* strlen("\1DCC MOVE F AAAAAAAA P S\1\n")=26
* strlen("\1DCC TSEND F AAAAAAAA P S\1\n")=27
*
* AAAAAAAAA: bound addr (1.0.0.0==16777216, min 8 digits,
* 255.255.255.255==4294967296, 10 digits)
* P: bound port (min 1 d, max 5d (65635))
* F: filename (min 1 d )
* S: size (min 1 d )
* 0x01, \n: terminators
*/
/* AAA = "us", ie. where server normally talks to. */
snprintf(buffer, sizeof(buffer), "%u %u", ntohl(newaddr.ip), port);
pr_debug("nf_nat_irc: inserting '%s' == %pI4, port %u\n",
buffer, &newaddr.ip, port);
ret = nf_nat_mangle_tcp_packet(skb, ct, ctinfo, protoff, matchoff,
matchlen, buffer, strlen(buffer));
if (ret != NF_ACCEPT) {
nf_ct_helper_log(skb, ct, "cannot mangle packet");
nf_ct_unexpect_related(exp);
}
return ret;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,250 |
ImageMagick | d8ab7f046587f2e9f734b687ba7e6e10147c294b | static inline signed int ReadPropertySignedLong(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) |
(buffer[1] << 8 ) | (buffer[0]));
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) |
(buffer[2] << 8) | buffer[3]);
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
| 1 | CVE-2016-5842 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 4,029 |
jasper | 69a1439a5381e42b06ec6a06ed2675eb793babee | static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile)
{
jpc_dec_tcomp_t *tcomp;
int compno;
int bandno;
int rlvlno;
jpc_dec_band_t *band;
jpc_dec_rlvl_t *rlvl;
int prcno;
jpc_dec_prc_t *prc;
jpc_dec_seg_t *seg;
jpc_dec_cblk_t *cblk;
int cblkno;
if (tile->tcomps) {
for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
++compno, ++tcomp) {
for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
++rlvlno, ++rlvl) {
if (!rlvl->bands) {
continue;
}
for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
++bandno, ++band) {
if (band->prcs) {
for (prcno = 0, prc = band->prcs; prcno <
rlvl->numprcs; ++prcno, ++prc) {
if (!prc->cblks) {
continue;
}
for (cblkno = 0, cblk = prc->cblks; cblkno <
prc->numcblks; ++cblkno, ++cblk) {
while (cblk->segs.head) {
seg = cblk->segs.head;
jpc_seglist_remove(&cblk->segs, seg);
jpc_seg_destroy(seg);
}
jas_matrix_destroy(cblk->data);
if (cblk->mqdec) {
jpc_mqdec_destroy(cblk->mqdec);
}
if (cblk->nulldec) {
jpc_bitstream_close(cblk->nulldec);
}
if (cblk->flags) {
jas_matrix_destroy(cblk->flags);
}
}
if (prc->incltagtree) {
jpc_tagtree_destroy(prc->incltagtree);
}
if (prc->numimsbstagtree) {
jpc_tagtree_destroy(prc->numimsbstagtree);
}
if (prc->cblks) {
jas_free(prc->cblks);
}
}
}
if (band->data) {
jas_matrix_destroy(band->data);
}
if (band->prcs) {
jas_free(band->prcs);
}
}
if (rlvl->bands) {
jas_free(rlvl->bands);
}
}
if (tcomp->rlvls) {
jas_free(tcomp->rlvls);
}
if (tcomp->data) {
jas_matrix_destroy(tcomp->data);
}
if (tcomp->tsfb) {
jpc_tsfb_destroy(tcomp->tsfb);
}
}
}
if (tile->cp) {
jpc_dec_cp_destroy(tile->cp);
tile->cp = 0;
}
if (tile->tcomps) {
jas_free(tile->tcomps);
tile->tcomps = 0;
}
if (tile->pi) {
jpc_pi_destroy(tile->pi);
tile->pi = 0;
}
if (tile->pkthdrstream) {
jas_stream_close(tile->pkthdrstream);
tile->pkthdrstream = 0;
}
if (tile->pptstab) {
jpc_ppxstab_destroy(tile->pptstab);
tile->pptstab = 0;
}
tile->state = JPC_TILE_DONE;
return 0;
} | 1 | CVE-2016-8882 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 4,315 |
linux | d0cb50185ae942b03c4327be322055d622dc79f6 | int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry,
struct inode **delegated_inode, unsigned int flags)
{
int error;
bool is_dir = d_is_dir(old_dentry);
struct inode *source = old_dentry->d_inode;
struct inode *target = new_dentry->d_inode;
bool new_is_dir = false;
unsigned max_links = new_dir->i_sb->s_max_links;
struct name_snapshot old_name;
if (source == target)
return 0;
error = may_delete(old_dir, old_dentry, is_dir);
if (error)
return error;
if (!target) {
error = may_create(new_dir, new_dentry);
} else {
new_is_dir = d_is_dir(new_dentry);
if (!(flags & RENAME_EXCHANGE))
error = may_delete(new_dir, new_dentry, is_dir);
else
error = may_delete(new_dir, new_dentry, new_is_dir);
}
if (error)
return error;
if (!old_dir->i_op->rename)
return -EPERM;
/*
* If we are going to change the parent - check write permissions,
* we'll need to flip '..'.
*/
if (new_dir != old_dir) {
if (is_dir) {
error = inode_permission(source, MAY_WRITE);
if (error)
return error;
}
if ((flags & RENAME_EXCHANGE) && new_is_dir) {
error = inode_permission(target, MAY_WRITE);
if (error)
return error;
}
}
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
flags);
if (error)
return error;
take_dentry_name_snapshot(&old_name, old_dentry);
dget(new_dentry);
if (!is_dir || (flags & RENAME_EXCHANGE))
lock_two_nondirectories(source, target);
else if (target)
inode_lock(target);
error = -EBUSY;
if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
goto out;
if (max_links && new_dir != old_dir) {
error = -EMLINK;
if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
goto out;
if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
old_dir->i_nlink >= max_links)
goto out;
}
if (!is_dir) {
error = try_break_deleg(source, delegated_inode);
if (error)
goto out;
}
if (target && !new_is_dir) {
error = try_break_deleg(target, delegated_inode);
if (error)
goto out;
}
error = old_dir->i_op->rename(old_dir, old_dentry,
new_dir, new_dentry, flags);
if (error)
goto out;
if (!(flags & RENAME_EXCHANGE) && target) {
if (is_dir) {
shrink_dcache_parent(new_dentry);
target->i_flags |= S_DEAD;
}
dont_mount(new_dentry);
detach_mounts(new_dentry);
}
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
if (!(flags & RENAME_EXCHANGE))
d_move(old_dentry, new_dentry);
else
d_exchange(old_dentry, new_dentry);
}
out:
if (!is_dir || (flags & RENAME_EXCHANGE))
unlock_two_nondirectories(source, target);
else if (target)
inode_unlock(target);
dput(new_dentry);
if (!error) {
fsnotify_move(old_dir, new_dir, &old_name.name, is_dir,
!(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
if (flags & RENAME_EXCHANGE) {
fsnotify_move(new_dir, old_dir, &old_dentry->d_name,
new_is_dir, NULL, new_dentry);
}
}
release_dentry_name_snapshot(&old_name);
return error;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,597 |
Chrome | b8573aa643b03a59f4e2c99c72d3511a11cfb0b6 | bool GestureSequence::PinchUpdate(const TouchEvent& event,
const GesturePoint& point, Gestures* gestures) {
DCHECK(state_ == GS_PINCH);
float distance = points_[0].Distance(points_[1]);
if (abs(distance - pinch_distance_current_) < kMinimumPinchUpdateDistance) {
if (!points_[0].DidScroll(event, kMinimumDistanceForPinchScroll) ||
!points_[1].DidScroll(event, kMinimumDistanceForPinchScroll))
return false;
gfx::Point center = points_[0].last_touch_position().Middle(
points_[1].last_touch_position());
AppendScrollGestureUpdate(point, center, gestures);
} else {
AppendPinchGestureUpdate(points_[0], points_[1],
distance / pinch_distance_current_, gestures);
pinch_distance_current_ = distance;
}
return true;
}
| 1 | CVE-2011-3094 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 8,392 |
gdk-pixbuf | b7bf6fbfb310fceba2d35d4de143b8d5ffdad990 | static gboolean DecodeHeader(unsigned char *BFH, unsigned char *BIH,
struct bmp_progressive_state *State,
GError **error)
{
gint clrUsed;
/* First check for the two first bytes content. A sane
BMP file must start with bytes 0x42 0x4D. */
if (*BFH != 0x42 || *(BFH + 1) != 0x4D) {
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
_("BMP image has bogus header data"));
State->read_state = READ_STATE_ERROR;
return FALSE;
}
/* FIXME this is totally unrobust against bogus image data. */
if (State->BufferSize < lsb_32 (&BIH[0]) + 14) {
State->BufferSize = lsb_32 (&BIH[0]) + 14;
if (!grow_buffer (State, error))
return FALSE;
return TRUE;
}
#if DUMPBIH
DumpBIH(BIH);
#endif
State->Header.size = lsb_32 (&BIH[0]);
if (State->Header.size == 124) {
/* BMP v5 */
State->Header.width = lsb_32 (&BIH[4]);
State->Header.height = lsb_32 (&BIH[8]);
State->Header.depth = lsb_16 (&BIH[14]);
State->Compressed = lsb_32 (&BIH[16]);
} else if (State->Header.size == 108) {
/* BMP v4 */
State->Header.width = lsb_32 (&BIH[4]);
State->Header.height = lsb_32 (&BIH[8]);
State->Header.depth = lsb_16 (&BIH[14]);
State->Compressed = lsb_32 (&BIH[16]);
} else if (State->Header.size == 64) {
/* BMP OS/2 v2 */
State->Header.width = lsb_32 (&BIH[4]);
State->Header.height = lsb_32 (&BIH[8]);
State->Header.depth = lsb_16 (&BIH[14]);
State->Compressed = lsb_32 (&BIH[16]);
} else if (State->Header.size == 40) {
/* BMP v3 */
State->Header.width = lsb_32 (&BIH[4]);
State->Header.height = lsb_32 (&BIH[8]);
State->Header.depth = lsb_16 (&BIH[14]);
State->Compressed = lsb_32 (&BIH[16]);
} else if (State->Header.size == 12) {
/* BMP OS/2 */
State->Header.width = lsb_16 (&BIH[4]);
State->Header.height = lsb_16 (&BIH[6]);
State->Header.depth = lsb_16 (&BIH[10]);
State->Compressed = BI_RGB;
} else {
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
_("BMP image has unsupported header size"));
State->read_state = READ_STATE_ERROR;
return FALSE;
}
if (State->Header.depth > 32)
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
_("BMP image has unsupported depth"));
State->read_state = READ_STATE_ERROR;
}
if (State->Header.size == 12)
clrUsed = 1 << State->Header.depth;
else
clrUsed = (int) (BIH[35] << 24) + (BIH[34] << 16) + (BIH[33] << 8) + (BIH[32]);
if (clrUsed != 0)
State->Header.n_colors = clrUsed;
else
State->Header.n_colors = (1 << State->Header.depth);
State->Type = State->Header.depth; /* This may be less trivial someday */
/* Negative heights indicates bottom-down pixelorder */
if (State->Header.height < 0) {
State->Header.height = -State->Header.height;
State->Header.Negative = 1;
}
if (State->Header.Negative &&
(State->Compressed != BI_RGB && State->Compressed != BI_BITFIELDS))
{
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
_("Topdown BMP images cannot be compressed"));
State->read_state = READ_STATE_ERROR;
return FALSE;
}
if (State->Header.width <= 0 || State->Header.height == 0 ||
(State->Compressed == BI_RLE4 && State->Type != 4) ||
(State->Compressed == BI_RLE8 && State->Type != 8) ||
(State->Compressed == BI_BITFIELDS && !(State->Type == 16 || State->Type == 32)) ||
(State->Compressed > BI_BITFIELDS)) {
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
_("BMP image has bogus header data"));
State->read_state = READ_STATE_ERROR;
return FALSE;
}
if (State->Type == 32)
State->LineWidth = State->Header.width * 4;
else if (State->Type == 24)
State->LineWidth = State->Header.width * 3;
else if (State->Type == 16)
State->LineWidth = State->Header.width * 2;
else if (State->Type == 8)
State->LineWidth = State->Header.width * 1;
else if (State->Type == 4)
State->LineWidth = (State->Header.width + 1) / 2;
else if (State->Type == 1) {
State->LineWidth = State->Header.width / 8;
if ((State->Header.width & 7) != 0)
State->LineWidth++;
} else {
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
_("BMP image has bogus header data"));
State->read_state = READ_STATE_ERROR;
return FALSE;
}
/* Pad to a 32 bit boundary */
if (((State->LineWidth % 4) > 0)
&& (State->Compressed == BI_RGB || State->Compressed == BI_BITFIELDS))
State->LineWidth = (State->LineWidth / 4) * 4 + 4;
if (State->pixbuf == NULL) {
if (State->size_func) {
gint width = State->Header.width;
gint height = State->Header.height;
(*State->size_func) (&width, &height, State->user_data);
if (width == 0 || height == 0) {
State->read_state = READ_STATE_DONE;
State->BufferSize = 0;
return TRUE;
}
}
if (State->Type == 32 ||
State->Compressed == BI_RLE4 ||
State->Compressed == BI_RLE8)
State->pixbuf =
gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8,
(gint) State->Header.width,
(gint) State->Header.height);
else
State->pixbuf =
gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8,
(gint) State->Header.width,
(gint) State->Header.height);
if (State->pixbuf == NULL) {
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
_("Not enough memory to load bitmap image"));
State->read_state = READ_STATE_ERROR;
return FALSE;
}
if (State->prepared_func != NULL)
/* Notify the client that we are ready to go */
(*State->prepared_func) (State->pixbuf, NULL, State->user_data);
/* make all pixels initially transparent */
if (State->Compressed == BI_RLE4 || State->Compressed == BI_RLE8) {
memset (State->pixbuf->pixels, 0, State->pixbuf->rowstride * State->Header.height);
State->compr.p = State->pixbuf->pixels
+ State->pixbuf->rowstride * (State->Header.height- 1);
}
}
State->BufferDone = 0;
if (State->Type <= 8) {
gint samples;
State->read_state = READ_STATE_PALETTE;
/* Allocate enough to hold the palette */
samples = (State->Header.size == 12 ? 3 : 4);
State->BufferSize = State->Header.n_colors * samples;
/* Skip over everything between the palette and the data.
This protects us against a malicious BFH[10] value.
*/
State->BufferPadding = (lsb_32 (&BFH[10]) - 14 - State->Header.size) - State->BufferSize;
} else if (State->Compressed == BI_RGB) {
if (State->BufferSize < lsb_32 (&BFH[10]))
{
/* skip over padding between headers and image data */
State->read_state = READ_STATE_HEADERS;
State->BufferDone = State->BufferSize;
State->BufferSize = lsb_32 (&BFH[10]);
}
else
{
State->read_state = READ_STATE_DATA;
State->BufferSize = State->LineWidth;
}
} else if (State->Compressed == BI_BITFIELDS) {
if (State->Header.size == 108 || State->Header.size == 124)
{
/* v4 and v5 have the bitmasks in the header */
if (!decode_bitmasks (&BIH[40], State, error)) {
State->read_state = READ_STATE_ERROR;
return FALSE;
}
}
else
{
State->read_state = READ_STATE_BITMASKS;
State->BufferSize = 12;
}
} else {
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
_("BMP image has bogus header data"));
State->read_state = READ_STATE_ERROR;
return FALSE;
}
if (!grow_buffer (State, error))
return FALSE;
return TRUE;
} | 1 | CVE-2017-12447 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 3,572 |
php | 1e9b175204e3286d64dfd6c9f09151c31b5e099a | PHP_METHOD(Phar, delete)
{
char *fname;
size_t fname_len;
char *error;
phar_entry_info *entry;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot write out phar archive, phar is read-only");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) {
RETURN_FALSE;
}
if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) {
if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) {
if (entry->is_deleted) {
/* entry is deleted, but has not been flushed to disk yet */
RETURN_TRUE;
} else {
entry->is_deleted = 1;
entry->is_modified = 1;
phar_obj->archive->is_modified = 1;
}
}
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", fname);
RETURN_FALSE;
}
phar_flush(phar_obj->archive, NULL, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
RETURN_TRUE;
}
| 1 | CVE-2016-4072 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 9,748 |
keepalived | f28015671a4b04785859d1b4b1327b367b6a10e9 | int extract_status_code(char *buffer, size_t size)
{
char *end = buffer + size;
unsigned long code;
/* Status-Code extraction */
while (buffer < end && *buffer != ' ' && *buffer != '\r')
buffer++;
buffer++;
if (buffer + 3 >= end || *buffer == ' ' || buffer[3] != ' ')
return 0;
code = strtoul(buffer, &end, 10);
if (buffer + 3 != end)
return 0;
return code;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,813 |
linux | 722d94847de29310e8aa03fcbdb41fc92c521756 | int vfs_parse_fs_param_source(struct fs_context *fc, struct fs_parameter *param)
{
if (strcmp(param->key, "source") != 0)
return -ENOPARAM;
if (param->type != fs_value_is_string)
return invalf(fc, "Non-string source");
if (fc->source)
return invalf(fc, "Multiple sources");
fc->source = param->string;
param->string = NULL;
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,294 |
enlightment | ce94edca1ccfbe314cb7cd9453433fad404ec7ef | __imlib_DupUpdates(ImlibUpdate * u)
{
ImlibUpdate *uu, *cu, *pu, *ru;
if (!u)
return NULL;
uu = malloc(sizeof(ImlibUpdate));
memcpy(uu, u, sizeof(ImlibUpdate));
cu = u->next;
pu = u;
ru = uu;
while (cu)
{
uu = malloc(sizeof(ImlibUpdate));
memcpy(uu, u, sizeof(ImlibUpdate));
pu->next = uu;
pu = cu;
cu = cu->next;
}
return ru;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,245 |
linux | 24f6008564183aa120d07c03d9289519c2fe02af | static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
{
/*
* Initially we receive a position value that corresponds to
* one more than the last pid shown (or 0 on the first call or
* after a seek to the start). Use a binary-search to find the
* next pid to display, if any
*/
struct kernfs_open_file *of = s->private;
struct cgroup_file_ctx *ctx = of->priv;
struct cgroup *cgrp = seq_css(s)->cgroup;
struct cgroup_pidlist *l;
enum cgroup_filetype type = seq_cft(s)->private;
int index = 0, pid = *pos;
int *iter, ret;
mutex_lock(&cgrp->pidlist_mutex);
/*
* !NULL @ctx->procs1.pidlist indicates that this isn't the first
* start() after open. If the matching pidlist is around, we can use
* that. Look for it. Note that @ctx->procs1.pidlist can't be used
* directly. It could already have been destroyed.
*/
if (ctx->procs1.pidlist)
ctx->procs1.pidlist = cgroup_pidlist_find(cgrp, type);
/*
* Either this is the first start() after open or the matching
* pidlist has been destroyed inbetween. Create a new one.
*/
if (!ctx->procs1.pidlist) {
ret = pidlist_array_load(cgrp, type, &ctx->procs1.pidlist);
if (ret)
return ERR_PTR(ret);
}
l = ctx->procs1.pidlist;
if (pid) {
int end = l->length;
while (index < end) {
int mid = (index + end) / 2;
if (l->list[mid] == pid) {
index = mid;
break;
} else if (l->list[mid] <= pid)
index = mid + 1;
else
end = mid;
}
}
/* If we're off the end of the array, we're done */
if (index >= l->length)
return NULL;
/* Update the abstract position to be the actual pid that we found */
iter = l->list + index;
*pos = *iter;
return iter;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,590 |
Android | 1e9801783770917728b7edbdeff3d0ec09c621ac | void SimpleSoftOMXComponent::onPortEnable(OMX_U32 portIndex, bool enable) {
CHECK_LT(portIndex, mPorts.size());
PortInfo *port = &mPorts.editItemAt(portIndex);
CHECK_EQ((int)port->mTransition, (int)PortInfo::NONE);
CHECK(port->mDef.bEnabled == !enable);
if (!enable) {
port->mDef.bEnabled = OMX_FALSE;
port->mTransition = PortInfo::DISABLING;
for (size_t i = 0; i < port->mBuffers.size(); ++i) {
BufferInfo *buffer = &port->mBuffers.editItemAt(i);
if (buffer->mOwnedByUs) {
buffer->mOwnedByUs = false;
if (port->mDef.eDir == OMX_DirInput) {
notifyEmptyBufferDone(buffer->mHeader);
} else {
CHECK_EQ(port->mDef.eDir, OMX_DirOutput);
notifyFillBufferDone(buffer->mHeader);
}
}
}
port->mQueue.clear();
} else {
port->mTransition = PortInfo::ENABLING;
}
checkTransitions();
}
| 1 | CVE-2016-3870 | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | Not Found in CWE Page | 4,746 |
linux | 13bf9fbff0e5e099e2b6f003a0ab8ae145436309 | nfs3svc_decode_symlinkargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_symlinkargs *args)
{
unsigned int len, avail;
char *old, *new;
struct kvec *vec;
if (!(p = decode_fh(p, &args->ffh)) ||
!(p = decode_filename(p, &args->fname, &args->flen))
)
return 0;
p = decode_sattr3(p, &args->attrs);
/* now decode the pathname, which might be larger than the first page.
* As we have to check for nul's anyway, we copy it into a new page
* This page appears in the rq_res.pages list, but as pages_len is always
* 0, it won't get in the way
*/
len = ntohl(*p++);
if (len == 0 || len > NFS3_MAXPATHLEN || len >= PAGE_SIZE)
return 0;
args->tname = new = page_address(*(rqstp->rq_next_page++));
args->tlen = len;
/* first copy and check from the first page */
old = (char*)p;
vec = &rqstp->rq_arg.head[0];
avail = vec->iov_len - (old - (char*)vec->iov_base);
while (len && avail && *old) {
*new++ = *old++;
len--;
avail--;
}
/* now copy next page if there is one */
if (len && !avail && rqstp->rq_arg.page_len) {
avail = min_t(unsigned int, rqstp->rq_arg.page_len, PAGE_SIZE);
old = page_address(rqstp->rq_arg.pages[0]);
}
while (len && avail && *old) {
*new++ = *old++;
len--;
avail--;
}
*new = '\0';
if (len)
return 0;
return 1;
}
| 1 | CVE-2017-7895 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 6,350 |
php-src | 1a4722a89ee85be74af5086a7027b3ad1e0a55e8 | gdImagePtr gdImageScaleTwoPass(const gdImagePtr src, const unsigned int src_width, const unsigned int src_height, const unsigned int new_width, const unsigned int new_height)
{
gdImagePtr tmp_im;
gdImagePtr dst;
/* Convert to truecolor if it isn't; this code requires it. */
if (!src->trueColor) {
gdImagePaletteToTrueColor(src);
}
tmp_im = gdImageCreateTrueColor(new_width, src_height);
if (tmp_im == NULL) {
return NULL;
}
gdImageSetInterpolationMethod(tmp_im, src->interpolation_id);
_gdScaleHoriz(src, src_width, src_height, tmp_im, new_width, src_height);
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst == NULL) {
gdFree(tmp_im);
return NULL;
}
gdImageSetInterpolationMethod(dst, src->interpolation_id);
_gdScaleVert(tmp_im, new_width, src_height, dst, new_width, new_height);
gdFree(tmp_im);
return dst;
} | 1 | CVE-2015-8877 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 804 |
irssi-proxy | 85bbc05b21678e80423815d2ef1dfe26208491ab | void server_connect_init(SERVER_REC *server)
{
const char *str;
g_return_if_fail(server != NULL);
MODULE_DATA_INIT(server);
server->type = module_get_uniq_id("SERVER", 0);
server_ref(server);
server->nick = g_strdup(server->connrec->nick);
if (server->connrec->username == NULL || *server->connrec->username == '\0') {
g_free_not_null(server->connrec->username);
str = g_get_user_name();
if (*str == '\0') str = "unknown";
server->connrec->username = g_strdup(str);
}
if (server->connrec->realname == NULL || *server->connrec->realname == '\0') {
g_free_not_null(server->connrec->realname);
str = g_get_real_name();
if (*str == '\0') str = server->connrec->username;
server->connrec->realname = g_strdup(str);
}
server->tag = server_create_tag(server->connrec);
server->connect_tag = -1;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,705 |
libgd | 69d2fd2c597ffc0c217de1238b9bf4d4bceba8e6 | _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
int *cs, int *vers, int *fmt, int *ncx, int *ncy,
t_chunk_info ** chunkIdx)
{
int i;
int ch;
char id[5];
t_chunk_info *cidx;
int sidx;
int nc;
GD2_DBG (printf ("Reading gd2 header info\n"));
for (i = 0; i < 4; i++) {
ch = gdGetC (in);
if (ch == EOF) {
goto fail1;
};
id[i] = ch;
};
id[4] = 0;
GD2_DBG (printf ("Got file code: %s\n", id));
/* Equiv. of 'magick'. */
if (strcmp (id, GD2_ID) != 0) {
GD2_DBG (printf ("Not a valid gd2 file\n"));
goto fail1;
};
/* Version */
if (gdGetWord (vers, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Version: %d\n", *vers));
if ((*vers != 1) && (*vers != 2)) {
GD2_DBG (printf ("Bad version: %d\n", *vers));
goto fail1;
};
/* Image Size */
if (!gdGetWord (sx, in)) {
GD2_DBG (printf ("Could not get x-size\n"));
goto fail1;
}
if (!gdGetWord (sy, in)) {
GD2_DBG (printf ("Could not get y-size\n"));
goto fail1;
}
GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy));
/* Chunk Size (pixels, not bytes!) */
if (gdGetWord (cs, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("ChunkSize: %d\n", *cs));
if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
GD2_DBG (printf ("Bad chunk size: %d\n", *cs));
goto fail1;
};
/* Data Format */
if (gdGetWord (fmt, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Format: %d\n", *fmt));
if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) &&
(*fmt != GD2_FMT_TRUECOLOR_RAW) &&
(*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
GD2_DBG (printf ("Bad data format: %d\n", *fmt));
goto fail1;
};
/* # of chunks wide */
if (gdGetWord (ncx, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks Wide\n", *ncx));
/* # of chunks high */
if (gdGetWord (ncy, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks vertically\n", *ncy));
if (gd2_compressed (*fmt)) {
if (*ncx <= 0 || *ncy <= 0 || *ncx > INT_MAX / *ncy) {
GD2_DBG(printf ("Illegal chunk counts: %d * %d\n", *ncx, *ncy));
goto fail1;
}
nc = (*ncx) * (*ncy);
GD2_DBG (printf ("Reading %d chunk index entries\n", nc));
if (overflow2(sizeof(t_chunk_info), nc)) {
goto fail1;
}
sidx = sizeof (t_chunk_info) * nc;
if (sidx <= 0) {
goto fail1;
}
cidx = gdCalloc (sidx, 1);
if (cidx == NULL) {
goto fail1;
}
for (i = 0; i < nc; i++) {
if (gdGetInt (&cidx[i].offset, in) != 1) {
goto fail2;
};
if (gdGetInt (&cidx[i].size, in) != 1) {
goto fail2;
};
if (cidx[i].offset < 0 || cidx[i].size < 0)
goto fail2;
};
*chunkIdx = cidx;
};
GD2_DBG (printf ("gd2 header complete\n"));
return 1;
fail2:
gdFree(cidx);
fail1:
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,529 |
linux | 19b61392c5a852b4e8a0bf35aecb969983c5932d | static void spi_hw_init(struct device *dev, struct dw_spi *dws)
{
spi_reset_chip(dws);
/*
* Try to detect the FIFO depth if not set by interface driver,
* the depth could be from 2 to 256 from HW spec
*/
if (!dws->fifo_len) {
u32 fifo;
for (fifo = 1; fifo < 256; fifo++) {
dw_writel(dws, DW_SPI_TXFLTR, fifo);
if (fifo != dw_readl(dws, DW_SPI_TXFLTR))
break;
}
dw_writel(dws, DW_SPI_TXFLTR, 0);
dws->fifo_len = (fifo == 1) ? 0 : fifo;
dev_dbg(dev, "Detected FIFO size: %u bytes\n", dws->fifo_len);
}
/* enable HW fixup for explicit CS deselect for Amazon's alpine chip */
if (dws->cs_override)
dw_writel(dws, DW_SPI_CS_OVERRIDE, 0xF);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,613 |
hermes | b2021df620824627f5a8c96615edbd1eb7fdddfc | CallResult<HermesValue> Interpreter::interpretFunction(
Runtime *runtime,
InterpreterState &state) {
// The interepter is re-entrant and also saves/restores its IP via the runtime
// whenever a call out is made (see the CAPTURE_IP_* macros). As such, failure
// to preserve the IP across calls to interpeterFunction() disrupt interpreter
// calls further up the C++ callstack. The RAII utility class below makes sure
// we always do this correctly.
//
// TODO: The IPs stored in the C++ callstack via this holder will generally be
// the same as in the JS stack frames via the Saved IP field. We can probably
// get rid of one of these redundant stores. Doing this isn't completely
// trivial as there are currently cases where we re-enter the interpreter
// without calling Runtime::saveCallerIPInStackFrame(), and there are features
// (I think mostly the debugger + stack traces) which implicitly rely on
// this behavior. At least their tests break if this behavior is not
// preserved.
struct IPSaver {
IPSaver(Runtime *runtime)
: ip_(runtime->getCurrentIP()), runtime_(runtime) {}
~IPSaver() {
runtime_->setCurrentIP(ip_);
}
private:
const Inst *ip_;
Runtime *runtime_;
};
IPSaver ipSaver(runtime);
#ifndef HERMES_ENABLE_DEBUGGER
static_assert(!SingleStep, "can't use single-step mode without the debugger");
#endif
// Make sure that the cache can use an optimization by avoiding a branch to
// access the property storage.
static_assert(
HiddenClass::kDictionaryThreshold <=
SegmentedArray::kValueToSegmentThreshold,
"Cannot avoid branches in cache check if the dictionary "
"crossover point is larger than the inline storage");
CodeBlock *curCodeBlock = state.codeBlock;
const Inst *ip = nullptr;
// Holds runtime->currentFrame_.ptr()-1 which is the first local
// register. This eliminates the indirect load from Runtime and the -1 offset.
PinnedHermesValue *frameRegs;
// Strictness of current function.
bool strictMode;
// Default flags when accessing properties.
PropOpFlags defaultPropOpFlags;
// These CAPTURE_IP* macros should wrap around any major calls out of the
// interpeter loop. They stash and retrieve the IP via the current Runtime
// allowing the IP to be externally observed and even altered to change the flow
// of execution. Explicitly saving AND restoring the IP from the Runtime in this
// way means the C++ compiler will keep IP in a register within the rest of the
// interpeter loop.
//
// When assertions are enabled we take the extra step of "invalidating" the IP
// between captures so we can detect if it's erroneously accessed.
//
// In some cases we explicitly don't want to invalidate the IP and instead want
// it to stay set. For this we use the *NO_INVALIDATE variants. This comes up
// when we're performing a call operation which may re-enter the interpeter
// loop, and so need the IP available for the saveCallerIPInStackFrame() call
// when we next enter.
#define CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr) \
runtime->setCurrentIP(ip); \
dst = expr; \
ip = runtime->getCurrentIP();
#ifdef NDEBUG
#define CAPTURE_IP(expr) \
runtime->setCurrentIP(ip); \
(void)expr; \
ip = runtime->getCurrentIP();
#define CAPTURE_IP_ASSIGN(dst, expr) CAPTURE_IP_ASSIGN_NO_INVALIDATE(dst, expr)
#else // !NDEBUG
#define CAPTURE_IP(expr) \
runtime->setCurrentIP(ip); \
(void)expr; \
ip = runtime->getCurrentIP(); \
runtime->invalidateCurrentIP();
#define CAPTURE_IP_ASSIGN(dst, expr) \
runtime->setCurrentIP(ip); \
dst = expr; \
ip = runtime->getCurrentIP(); \
runtime->invalidateCurrentIP();
#endif // NDEBUG
/// \def DONT_CAPTURE_IP(expr)
/// \param expr A call expression to a function external to the interpreter. The
/// expression should not make any allocations and the IP should be set
/// immediately following this macro.
#define DONT_CAPTURE_IP(expr) \
do { \
NoAllocScope noAlloc(runtime); \
(void)expr; \
} while (false)
LLVM_DEBUG(dbgs() << "interpretFunction() called\n");
ScopedNativeDepthTracker depthTracker{runtime};
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
if (!SingleStep) {
if (auto jitPtr = runtime->jitContext_.compile(runtime, curCodeBlock)) {
return (*jitPtr)(runtime);
}
}
GCScope gcScope(runtime);
// Avoid allocating a handle dynamically by reusing this one.
MutableHandle<> tmpHandle(runtime);
CallResult<HermesValue> res{ExecutionStatus::EXCEPTION};
CallResult<PseudoHandle<>> resPH{ExecutionStatus::EXCEPTION};
CallResult<Handle<Arguments>> resArgs{ExecutionStatus::EXCEPTION};
CallResult<bool> boolRes{ExecutionStatus::EXCEPTION};
// Mark the gcScope so we can clear all allocated handles.
// Remember how many handles the scope has so we can clear them in the loop.
static constexpr unsigned KEEP_HANDLES = 1;
assert(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"scope has unexpected number of handles");
INIT_OPCODE_PROFILER;
#if !defined(HERMESVM_PROFILER_EXTERN)
tailCall:
#endif
PROFILER_ENTER_FUNCTION(curCodeBlock);
#ifdef HERMES_ENABLE_DEBUGGER
runtime->getDebugger().willEnterCodeBlock(curCodeBlock);
#endif
runtime->getCodeCoverageProfiler().markExecuted(runtime, curCodeBlock);
// Update function executionCount_ count
curCodeBlock->incrementExecutionCount();
if (!SingleStep) {
auto newFrame = runtime->setCurrentFrameToTopOfStack();
runtime->saveCallerIPInStackFrame();
#ifndef NDEBUG
runtime->invalidateCurrentIP();
#endif
// Point frameRegs to the first register in the new frame. Note that at this
// moment technically it points above the top of the stack, but we are never
// going to access it.
frameRegs = &newFrame.getFirstLocalRef();
#ifndef NDEBUG
LLVM_DEBUG(
dbgs() << "function entry: stackLevel=" << runtime->getStackLevel()
<< ", argCount=" << runtime->getCurrentFrame().getArgCount()
<< ", frameSize=" << curCodeBlock->getFrameSize() << "\n");
LLVM_DEBUG(
dbgs() << " callee "
<< DumpHermesValue(
runtime->getCurrentFrame().getCalleeClosureOrCBRef())
<< "\n");
LLVM_DEBUG(
dbgs() << " this "
<< DumpHermesValue(runtime->getCurrentFrame().getThisArgRef())
<< "\n");
for (uint32_t i = 0; i != runtime->getCurrentFrame()->getArgCount(); ++i) {
LLVM_DEBUG(
dbgs() << " " << llvh::format_decimal(i, 4) << " "
<< DumpHermesValue(runtime->getCurrentFrame().getArgRef(i))
<< "\n");
}
#endif
// Allocate the registers for the new frame.
if (LLVM_UNLIKELY(!runtime->checkAndAllocStack(
curCodeBlock->getFrameSize() +
StackFrameLayout::CalleeExtraRegistersAtStart,
HermesValue::encodeUndefinedValue())))
goto stackOverflow;
ip = (Inst const *)curCodeBlock->begin();
// Check for invalid invocation.
if (LLVM_UNLIKELY(curCodeBlock->getHeaderFlags().isCallProhibited(
newFrame.isConstructorCall()))) {
if (!newFrame.isConstructorCall()) {
CAPTURE_IP(
runtime->raiseTypeError("Class constructor invoked without new"));
} else {
CAPTURE_IP(runtime->raiseTypeError("Function is not a constructor"));
}
goto handleExceptionInParent;
}
} else {
// Point frameRegs to the first register in the frame.
frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();
ip = (Inst const *)(curCodeBlock->begin() + state.offset);
}
assert((const uint8_t *)ip < curCodeBlock->end() && "CodeBlock is empty");
INIT_STATE_FOR_CODEBLOCK(curCodeBlock);
#define BEFORE_OP_CODE \
{ \
UPDATE_OPCODE_TIME_SPENT; \
HERMES_SLOW_ASSERT( \
curCodeBlock->contains(ip) && "curCodeBlock must contain ip"); \
HERMES_SLOW_ASSERT((printDebugInfo(curCodeBlock, frameRegs, ip), true)); \
HERMES_SLOW_ASSERT( \
gcScope.getHandleCountDbg() == KEEP_HANDLES && \
"unaccounted handles were created"); \
HERMES_SLOW_ASSERT(tmpHandle->isUndefined() && "tmpHandle not cleared"); \
RECORD_OPCODE_START_TIME; \
INC_OPCODE_COUNT; \
}
#ifdef HERMESVM_INDIRECT_THREADING
static void *opcodeDispatch[] = {
#define DEFINE_OPCODE(name) &&case_##name,
#include "hermes/BCGen/HBC/BytecodeList.def"
&&case__last};
#define CASE(name) case_##name:
#define DISPATCH \
BEFORE_OP_CODE; \
if (SingleStep) { \
state.codeBlock = curCodeBlock; \
state.offset = CUROFFSET; \
return HermesValue::encodeUndefinedValue(); \
} \
goto *opcodeDispatch[(unsigned)ip->opCode]
#else // HERMESVM_INDIRECT_THREADING
#define CASE(name) case OpCode::name:
#define DISPATCH \
if (SingleStep) { \
state.codeBlock = curCodeBlock; \
state.offset = CUROFFSET; \
return HermesValue::encodeUndefinedValue(); \
} \
continue
#endif // HERMESVM_INDIRECT_THREADING
#define RUN_DEBUGGER_ASYNC_BREAK(flags) \
do { \
CAPTURE_IP_ASSIGN( \
auto dRes, \
runDebuggerUpdatingState( \
(uint8_t)(flags) & \
(uint8_t)Runtime::AsyncBreakReasonBits::DebuggerExplicit \
? Debugger::RunReason::AsyncBreakExplicit \
: Debugger::RunReason::AsyncBreakImplicit, \
runtime, \
curCodeBlock, \
ip, \
frameRegs)); \
if (dRes == ExecutionStatus::EXCEPTION) \
goto exception; \
} while (0)
for (;;) {
BEFORE_OP_CODE;
#ifdef HERMESVM_INDIRECT_THREADING
goto *opcodeDispatch[(unsigned)ip->opCode];
#else
switch (ip->opCode)
#endif
{
const Inst *nextIP;
uint32_t idVal;
bool tryProp;
uint32_t callArgCount;
// This is HermesValue::getRaw(), since HermesValue cannot be assigned
// to. It is meant to be used only for very short durations, in the
// dispatch of call instructions, when there is definitely no possibility
// of a GC.
HermesValue::RawType callNewTarget;
/// Handle an opcode \p name with an out-of-line implementation in a function
/// ExecutionStatus caseName(
/// Runtime *,
/// PinnedHermesValue *frameRegs,
/// Inst *ip)
#define CASE_OUTOFLINE(name) \
CASE(name) { \
CAPTURE_IP_ASSIGN(auto res, case##name(runtime, frameRegs, ip)); \
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { \
goto exception; \
} \
gcScope.flushToSmallCount(KEEP_HANDLES); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a binary arithmetic instruction with a fast path where both
/// operands are numbers.
/// \param name the name of the instruction. The fast path case will have a
/// "n" appended to the name.
/// \param oper the C++ operator to use to actually perform the arithmetic
/// operation.
#define BINOP(name, oper) \
CASE(name) { \
if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \
/* Fast-path. */ \
CASE(name##N) { \
O1REG(name) = HermesValue::encodeDoubleValue( \
oper(O2REG(name).getNumber(), O3REG(name).getNumber())); \
ip = NEXTINST(name); \
DISPATCH; \
} \
} \
CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) \
goto exception; \
double left = res->getDouble(); \
CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) \
goto exception; \
O1REG(name) = \
HermesValue::encodeDoubleValue(oper(left, res->getDouble())); \
gcScope.flushToSmallCount(KEEP_HANDLES); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a shift instruction with a fast path where both
/// operands are numbers.
/// \param name the name of the instruction.
/// \param oper the C++ operator to use to actually perform the shift
/// operation.
/// \param lConv the conversion function for the LHS of the expression.
/// \param lType the type of the LHS operand.
/// \param returnType the type of the return value.
#define SHIFTOP(name, oper, lConv, lType, returnType) \
CASE(name) { \
if (LLVM_LIKELY( \
O2REG(name).isNumber() && \
O3REG(name).isNumber())) { /* Fast-path. */ \
auto lnum = static_cast<lType>( \
hermes::truncateToInt32(O2REG(name).getNumber())); \
auto rnum = static_cast<uint32_t>( \
hermes::truncateToInt32(O3REG(name).getNumber())) & \
0x1f; \
O1REG(name) = HermesValue::encodeDoubleValue( \
static_cast<returnType>(lnum oper rnum)); \
ip = NEXTINST(name); \
DISPATCH; \
} \
CAPTURE_IP_ASSIGN(res, lConv(runtime, Handle<>(&O2REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
auto lnum = static_cast<lType>(res->getNumber()); \
CAPTURE_IP_ASSIGN(res, toUInt32_RJS(runtime, Handle<>(&O3REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
auto rnum = static_cast<uint32_t>(res->getNumber()) & 0x1f; \
gcScope.flushToSmallCount(KEEP_HANDLES); \
O1REG(name) = HermesValue::encodeDoubleValue( \
static_cast<returnType>(lnum oper rnum)); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a binary bitwise instruction with a fast path where both
/// operands are numbers.
/// \param name the name of the instruction.
/// \param oper the C++ operator to use to actually perform the bitwise
/// operation.
#define BITWISEBINOP(name, oper) \
CASE(name) { \
if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \
/* Fast-path. */ \
O1REG(name) = HermesValue::encodeDoubleValue( \
hermes::truncateToInt32(O2REG(name).getNumber()) \
oper hermes::truncateToInt32(O3REG(name).getNumber())); \
ip = NEXTINST(name); \
DISPATCH; \
} \
CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
int32_t left = res->getNumberAs<int32_t>(); \
CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O3REG(name)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
O1REG(name) = \
HermesValue::encodeNumberValue(left oper res->getNumberAs<int32_t>()); \
gcScope.flushToSmallCount(KEEP_HANDLES); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a comparison instruction.
/// \param name the name of the instruction.
/// \param oper the C++ operator to use to actually perform the fast arithmetic
/// comparison.
/// \param operFuncName function to call for the slow-path comparison.
#define CONDOP(name, oper, operFuncName) \
CASE(name) { \
if (LLVM_LIKELY(O2REG(name).isNumber() && O3REG(name).isNumber())) { \
/* Fast-path. */ \
O1REG(name) = HermesValue::encodeBoolValue( \
O2REG(name).getNumber() oper O3REG(name).getNumber()); \
ip = NEXTINST(name); \
DISPATCH; \
} \
CAPTURE_IP_ASSIGN( \
boolRes, \
operFuncName( \
runtime, Handle<>(&O2REG(name)), Handle<>(&O3REG(name)))); \
if (boolRes == ExecutionStatus::EXCEPTION) \
goto exception; \
gcScope.flushToSmallCount(KEEP_HANDLES); \
O1REG(name) = HermesValue::encodeBoolValue(boolRes.getValue()); \
ip = NEXTINST(name); \
DISPATCH; \
}
/// Implement a comparison conditional jump with a fast path where both
/// operands are numbers.
/// \param name the name of the instruction. The fast path case will have a
/// "N" appended to the name.
/// \param suffix Optional suffix to be added to the end (e.g. Long)
/// \param oper the C++ operator to use to actually perform the fast arithmetic
/// comparison.
/// \param operFuncName function to call for the slow-path comparison.
/// \param trueDest ip value if the conditional evaluates to true
/// \param falseDest ip value if the conditional evaluates to false
#define JCOND_IMPL(name, suffix, oper, operFuncName, trueDest, falseDest) \
CASE(name##suffix) { \
if (LLVM_LIKELY( \
O2REG(name##suffix).isNumber() && \
O3REG(name##suffix).isNumber())) { \
/* Fast-path. */ \
CASE(name##N##suffix) { \
if (O2REG(name##N##suffix) \
.getNumber() oper O3REG(name##N##suffix) \
.getNumber()) { \
ip = trueDest; \
DISPATCH; \
} \
ip = falseDest; \
DISPATCH; \
} \
} \
CAPTURE_IP_ASSIGN( \
boolRes, \
operFuncName( \
runtime, \
Handle<>(&O2REG(name##suffix)), \
Handle<>(&O3REG(name##suffix)))); \
if (boolRes == ExecutionStatus::EXCEPTION) \
goto exception; \
gcScope.flushToSmallCount(KEEP_HANDLES); \
if (boolRes.getValue()) { \
ip = trueDest; \
DISPATCH; \
} \
ip = falseDest; \
DISPATCH; \
}
/// Implement a strict equality conditional jump
/// \param name the name of the instruction.
/// \param suffix Optional suffix to be added to the end (e.g. Long)
/// \param trueDest ip value if the conditional evaluates to true
/// \param falseDest ip value if the conditional evaluates to false
#define JCOND_STRICT_EQ_IMPL(name, suffix, trueDest, falseDest) \
CASE(name##suffix) { \
if (strictEqualityTest(O2REG(name##suffix), O3REG(name##suffix))) { \
ip = trueDest; \
DISPATCH; \
} \
ip = falseDest; \
DISPATCH; \
}
/// Implement an equality conditional jump
/// \param name the name of the instruction.
/// \param suffix Optional suffix to be added to the end (e.g. Long)
/// \param trueDest ip value if the conditional evaluates to true
/// \param falseDest ip value if the conditional evaluates to false
#define JCOND_EQ_IMPL(name, suffix, trueDest, falseDest) \
CASE(name##suffix) { \
CAPTURE_IP_ASSIGN( \
res, \
abstractEqualityTest_RJS( \
runtime, \
Handle<>(&O2REG(name##suffix)), \
Handle<>(&O3REG(name##suffix)))); \
if (res == ExecutionStatus::EXCEPTION) { \
goto exception; \
} \
gcScope.flushToSmallCount(KEEP_HANDLES); \
if (res->getBool()) { \
ip = trueDest; \
DISPATCH; \
} \
ip = falseDest; \
DISPATCH; \
}
/// Implement the long and short forms of a conditional jump, and its negation.
#define JCOND(name, oper, operFuncName) \
JCOND_IMPL( \
J##name, \
, \
oper, \
operFuncName, \
IPADD(ip->iJ##name.op1), \
NEXTINST(J##name)); \
JCOND_IMPL( \
J##name, \
Long, \
oper, \
operFuncName, \
IPADD(ip->iJ##name##Long.op1), \
NEXTINST(J##name##Long)); \
JCOND_IMPL( \
JNot##name, \
, \
oper, \
operFuncName, \
NEXTINST(JNot##name), \
IPADD(ip->iJNot##name.op1)); \
JCOND_IMPL( \
JNot##name, \
Long, \
oper, \
operFuncName, \
NEXTINST(JNot##name##Long), \
IPADD(ip->iJNot##name##Long.op1));
/// Load a constant.
/// \param value is the value to store in the output register.
#define LOAD_CONST(name, value) \
CASE(name) { \
O1REG(name) = value; \
ip = NEXTINST(name); \
DISPATCH; \
}
#define LOAD_CONST_CAPTURE_IP(name, value) \
CASE(name) { \
CAPTURE_IP_ASSIGN(O1REG(name), value); \
ip = NEXTINST(name); \
DISPATCH; \
}
CASE(Mov) {
O1REG(Mov) = O2REG(Mov);
ip = NEXTINST(Mov);
DISPATCH;
}
CASE(MovLong) {
O1REG(MovLong) = O2REG(MovLong);
ip = NEXTINST(MovLong);
DISPATCH;
}
CASE(LoadParam) {
if (LLVM_LIKELY(ip->iLoadParam.op2 <= FRAME.getArgCount())) {
// index 0 must load 'this'. Index 1 the first argument, etc.
O1REG(LoadParam) = FRAME.getArgRef((int32_t)ip->iLoadParam.op2 - 1);
ip = NEXTINST(LoadParam);
DISPATCH;
}
O1REG(LoadParam) = HermesValue::encodeUndefinedValue();
ip = NEXTINST(LoadParam);
DISPATCH;
}
CASE(LoadParamLong) {
if (LLVM_LIKELY(ip->iLoadParamLong.op2 <= FRAME.getArgCount())) {
// index 0 must load 'this'. Index 1 the first argument, etc.
O1REG(LoadParamLong) =
FRAME.getArgRef((int32_t)ip->iLoadParamLong.op2 - 1);
ip = NEXTINST(LoadParamLong);
DISPATCH;
}
O1REG(LoadParamLong) = HermesValue::encodeUndefinedValue();
ip = NEXTINST(LoadParamLong);
DISPATCH;
}
CASE(CoerceThisNS) {
if (LLVM_LIKELY(O2REG(CoerceThisNS).isObject())) {
O1REG(CoerceThisNS) = O2REG(CoerceThisNS);
} else if (
O2REG(CoerceThisNS).isNull() || O2REG(CoerceThisNS).isUndefined()) {
O1REG(CoerceThisNS) = runtime->global_;
} else {
tmpHandle = O2REG(CoerceThisNS);
nextIP = NEXTINST(CoerceThisNS);
goto coerceThisSlowPath;
}
ip = NEXTINST(CoerceThisNS);
DISPATCH;
}
CASE(LoadThisNS) {
if (LLVM_LIKELY(FRAME.getThisArgRef().isObject())) {
O1REG(LoadThisNS) = FRAME.getThisArgRef();
} else if (
FRAME.getThisArgRef().isNull() ||
FRAME.getThisArgRef().isUndefined()) {
O1REG(LoadThisNS) = runtime->global_;
} else {
tmpHandle = FRAME.getThisArgRef();
nextIP = NEXTINST(LoadThisNS);
goto coerceThisSlowPath;
}
ip = NEXTINST(LoadThisNS);
DISPATCH;
}
coerceThisSlowPath : {
CAPTURE_IP_ASSIGN(res, toObject(runtime, tmpHandle));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CoerceThisNS) = res.getValue();
tmpHandle.clear();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(ConstructLong) {
callArgCount = (uint32_t)ip->iConstructLong.op3;
nextIP = NEXTINST(ConstructLong);
callNewTarget = O2REG(ConstructLong).getRaw();
goto doCall;
}
CASE(CallLong) {
callArgCount = (uint32_t)ip->iCallLong.op3;
nextIP = NEXTINST(CallLong);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
// Note in Call1 through Call4, the first argument is 'this' which has
// argument index -1.
// Also note that we are writing to callNewTarget last, to avoid the
// possibility of it being aliased by the arg writes.
CASE(Call1) {
callArgCount = 1;
nextIP = NEXTINST(Call1);
StackFramePtr fr{runtime->stackPointer_};
fr.getArgRefUnsafe(-1) = O3REG(Call1);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
CASE(Call2) {
callArgCount = 2;
nextIP = NEXTINST(Call2);
StackFramePtr fr{runtime->stackPointer_};
fr.getArgRefUnsafe(-1) = O3REG(Call2);
fr.getArgRefUnsafe(0) = O4REG(Call2);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
CASE(Call3) {
callArgCount = 3;
nextIP = NEXTINST(Call3);
StackFramePtr fr{runtime->stackPointer_};
fr.getArgRefUnsafe(-1) = O3REG(Call3);
fr.getArgRefUnsafe(0) = O4REG(Call3);
fr.getArgRefUnsafe(1) = O5REG(Call3);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
CASE(Call4) {
callArgCount = 4;
nextIP = NEXTINST(Call4);
StackFramePtr fr{runtime->stackPointer_};
fr.getArgRefUnsafe(-1) = O3REG(Call4);
fr.getArgRefUnsafe(0) = O4REG(Call4);
fr.getArgRefUnsafe(1) = O5REG(Call4);
fr.getArgRefUnsafe(2) = O6REG(Call4);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
goto doCall;
}
CASE(Construct) {
callArgCount = (uint32_t)ip->iConstruct.op3;
nextIP = NEXTINST(Construct);
callNewTarget = O2REG(Construct).getRaw();
goto doCall;
}
CASE(Call) {
callArgCount = (uint32_t)ip->iCall.op3;
nextIP = NEXTINST(Call);
callNewTarget = HermesValue::encodeUndefinedValue().getRaw();
// Fall through.
}
doCall : {
#ifdef HERMES_ENABLE_DEBUGGER
// Check for an async debugger request.
if (uint8_t asyncFlags =
runtime->testAndClearDebuggerAsyncBreakRequest()) {
RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);
gcScope.flushToSmallCount(KEEP_HANDLES);
DISPATCH;
}
#endif
// Subtract 1 from callArgCount as 'this' is considered an argument in the
// instruction, but not in the frame.
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
auto newFrame,
StackFramePtr::initFrame(
runtime->stackPointer_,
FRAME,
ip,
curCodeBlock,
callArgCount - 1,
O2REG(Call),
HermesValue::fromRaw(callNewTarget)));
(void)newFrame;
SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));
if (auto *func = dyn_vmcast<JSFunction>(O2REG(Call))) {
assert(!SingleStep && "can't single-step a call");
#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES
runtime->pushCallStack(curCodeBlock, ip);
#endif
CodeBlock *calleeBlock = func->getCodeBlock();
calleeBlock->lazyCompile(runtime);
#if defined(HERMESVM_PROFILER_EXTERN)
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
res, runtime->interpretFunction(calleeBlock));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(Call) = *res;
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
#else
if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {
res = (*jitPtr)(runtime);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
goto exception;
O1REG(Call) = *res;
SLOW_DEBUG(
dbgs() << "JIT return value r" << (unsigned)ip->iCall.op1 << "="
<< DumpHermesValue(O1REG(Call)) << "\n");
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
curCodeBlock = calleeBlock;
goto tailCall;
#endif
}
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
resPH, Interpreter::handleCallSlowPath(runtime, &O2REG(Call)));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(Call) = std::move(resPH->get());
SLOW_DEBUG(
dbgs() << "native return value r" << (unsigned)ip->iCall.op1 << "="
<< DumpHermesValue(O1REG(Call)) << "\n");
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(CallDirect)
CASE(CallDirectLongIndex) {
#ifdef HERMES_ENABLE_DEBUGGER
// Check for an async debugger request.
if (uint8_t asyncFlags =
runtime->testAndClearDebuggerAsyncBreakRequest()) {
RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);
gcScope.flushToSmallCount(KEEP_HANDLES);
DISPATCH;
}
#endif
CAPTURE_IP_ASSIGN(
CodeBlock * calleeBlock,
ip->opCode == OpCode::CallDirect
? curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(
ip->iCallDirect.op3)
: curCodeBlock->getRuntimeModule()->getCodeBlockMayAllocate(
ip->iCallDirectLongIndex.op3));
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
auto newFrame,
StackFramePtr::initFrame(
runtime->stackPointer_,
FRAME,
ip,
curCodeBlock,
(uint32_t)ip->iCallDirect.op2 - 1,
HermesValue::encodeNativePointer(calleeBlock),
HermesValue::encodeUndefinedValue()));
(void)newFrame;
LLVM_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));
assert(!SingleStep && "can't single-step a call");
calleeBlock->lazyCompile(runtime);
#if defined(HERMESVM_PROFILER_EXTERN)
CAPTURE_IP_ASSIGN_NO_INVALIDATE(
res, runtime->interpretFunction(calleeBlock));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CallDirect) = *res;
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)
: NEXTINST(CallDirectLongIndex);
DISPATCH;
#else
if (auto jitPtr = runtime->jitContext_.compile(runtime, calleeBlock)) {
res = (*jitPtr)(runtime);
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
goto exception;
O1REG(CallDirect) = *res;
LLVM_DEBUG(
dbgs() << "JIT return value r" << (unsigned)ip->iCallDirect.op1
<< "=" << DumpHermesValue(O1REG(Call)) << "\n");
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = ip->opCode == OpCode::CallDirect ? NEXTINST(CallDirect)
: NEXTINST(CallDirectLongIndex);
DISPATCH;
}
curCodeBlock = calleeBlock;
goto tailCall;
#endif
}
CASE(CallBuiltin) {
NativeFunction *nf =
runtime->getBuiltinNativeFunction(ip->iCallBuiltin.op2);
CAPTURE_IP_ASSIGN(
auto newFrame,
StackFramePtr::initFrame(
runtime->stackPointer_,
FRAME,
ip,
curCodeBlock,
(uint32_t)ip->iCallBuiltin.op3 - 1,
nf,
false));
// "thisArg" is implicitly assumed to "undefined".
newFrame.getThisArgRef() = HermesValue::encodeUndefinedValue();
SLOW_DEBUG(dumpCallArguments(dbgs(), runtime, newFrame));
CAPTURE_IP_ASSIGN(resPH, NativeFunction::_nativeCall(nf, runtime));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION))
goto exception;
O1REG(CallBuiltin) = std::move(resPH->get());
SLOW_DEBUG(
dbgs() << "native return value r" << (unsigned)ip->iCallBuiltin.op1
<< "=" << DumpHermesValue(O1REG(CallBuiltin)) << "\n");
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CallBuiltin);
DISPATCH;
}
CASE(CompleteGenerator) {
auto *innerFn = vmcast<GeneratorInnerFunction>(
runtime->getCurrentFrame().getCalleeClosure());
innerFn->setState(GeneratorInnerFunction::State::Completed);
ip = NEXTINST(CompleteGenerator);
DISPATCH;
}
CASE(SaveGenerator) {
DONT_CAPTURE_IP(
saveGenerator(runtime, frameRegs, IPADD(ip->iSaveGenerator.op1)));
ip = NEXTINST(SaveGenerator);
DISPATCH;
}
CASE(SaveGeneratorLong) {
DONT_CAPTURE_IP(saveGenerator(
runtime, frameRegs, IPADD(ip->iSaveGeneratorLong.op1)));
ip = NEXTINST(SaveGeneratorLong);
DISPATCH;
}
CASE(StartGenerator) {
auto *innerFn = vmcast<GeneratorInnerFunction>(
runtime->getCurrentFrame().getCalleeClosure());
if (innerFn->getState() ==
GeneratorInnerFunction::State::SuspendedStart) {
nextIP = NEXTINST(StartGenerator);
} else {
nextIP = innerFn->getNextIP();
innerFn->restoreStack(runtime);
}
innerFn->setState(GeneratorInnerFunction::State::Executing);
ip = nextIP;
DISPATCH;
}
CASE(ResumeGenerator) {
auto *innerFn = vmcast<GeneratorInnerFunction>(
runtime->getCurrentFrame().getCalleeClosure());
O1REG(ResumeGenerator) = innerFn->getResult();
O2REG(ResumeGenerator) = HermesValue::encodeBoolValue(
innerFn->getAction() == GeneratorInnerFunction::Action::Return);
innerFn->clearResult(runtime);
if (innerFn->getAction() == GeneratorInnerFunction::Action::Throw) {
runtime->setThrownValue(O1REG(ResumeGenerator));
goto exception;
}
ip = NEXTINST(ResumeGenerator);
DISPATCH;
}
CASE(Ret) {
#ifdef HERMES_ENABLE_DEBUGGER
// Check for an async debugger request.
if (uint8_t asyncFlags =
runtime->testAndClearDebuggerAsyncBreakRequest()) {
RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);
gcScope.flushToSmallCount(KEEP_HANDLES);
DISPATCH;
}
#endif
PROFILER_EXIT_FUNCTION(curCodeBlock);
#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES
runtime->popCallStack();
#endif
// Store the return value.
res = O1REG(Ret);
ip = FRAME.getSavedIP();
curCodeBlock = FRAME.getSavedCodeBlock();
frameRegs =
&runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();
SLOW_DEBUG(
dbgs() << "function exit: restored stackLevel="
<< runtime->getStackLevel() << "\n");
// Are we returning to native code?
if (!curCodeBlock) {
SLOW_DEBUG(dbgs() << "function exit: returning to native code\n");
return res;
}
// Return because of recursive calling structure
#if defined(HERMESVM_PROFILER_EXTERN)
return res;
#endif
INIT_STATE_FOR_CODEBLOCK(curCodeBlock);
O1REG(Call) = res.getValue();
ip = nextInstCall(ip);
DISPATCH;
}
CASE(Catch) {
assert(!runtime->thrownValue_.isEmpty() && "Invalid thrown value");
assert(
!isUncatchableError(runtime->thrownValue_) &&
"Uncatchable thrown value was caught");
O1REG(Catch) = runtime->thrownValue_;
runtime->clearThrownValue();
#ifdef HERMES_ENABLE_DEBUGGER
// Signal to the debugger that we're done unwinding an exception,
// and we can resume normal debugging flow.
runtime->debugger_.finishedUnwindingException();
#endif
ip = NEXTINST(Catch);
DISPATCH;
}
CASE(Throw) {
runtime->thrownValue_ = O1REG(Throw);
SLOW_DEBUG(
dbgs() << "Exception thrown: "
<< DumpHermesValue(runtime->thrownValue_) << "\n");
goto exception;
}
CASE(ThrowIfUndefinedInst) {
if (LLVM_UNLIKELY(O1REG(ThrowIfUndefinedInst).isUndefined())) {
SLOW_DEBUG(
dbgs() << "Throwing ReferenceError for undefined variable");
CAPTURE_IP(runtime->raiseReferenceError(
"accessing an uninitialized variable"));
goto exception;
}
ip = NEXTINST(ThrowIfUndefinedInst);
DISPATCH;
}
CASE(Debugger) {
SLOW_DEBUG(dbgs() << "debugger statement executed\n");
#ifdef HERMES_ENABLE_DEBUGGER
{
if (!runtime->debugger_.isDebugging()) {
// Only run the debugger if we're not already debugging.
// Don't want to call it again and mess with its state.
CAPTURE_IP_ASSIGN(
auto res,
runDebuggerUpdatingState(
Debugger::RunReason::Opcode,
runtime,
curCodeBlock,
ip,
frameRegs));
if (res == ExecutionStatus::EXCEPTION) {
// If one of the internal steps threw,
// then handle that here by jumping to where we're supposed to go.
// If we're in mid-step, the breakpoint at the catch point
// will have been set by the debugger.
// We don't want to execute this instruction because it's already
// thrown.
goto exception;
}
}
auto breakpointOpt = runtime->debugger_.getBreakpointLocation(ip);
if (breakpointOpt.hasValue()) {
// We're on a breakpoint but we're supposed to continue.
curCodeBlock->uninstallBreakpointAtOffset(
CUROFFSET, breakpointOpt->opCode);
if (ip->opCode == OpCode::Debugger) {
// Breakpointed a debugger instruction, so move past it
// since we've already called the debugger on this instruction.
ip = NEXTINST(Debugger);
} else {
InterpreterState newState{curCodeBlock, (uint32_t)CUROFFSET};
CAPTURE_IP_ASSIGN(
ExecutionStatus status, runtime->stepFunction(newState));
curCodeBlock->installBreakpointAtOffset(CUROFFSET);
if (status == ExecutionStatus::EXCEPTION) {
goto exception;
}
curCodeBlock = newState.codeBlock;
ip = newState.codeBlock->getOffsetPtr(newState.offset);
INIT_STATE_FOR_CODEBLOCK(curCodeBlock);
// Single-stepping should handle call stack management for us.
frameRegs = &runtime->getCurrentFrame().getFirstLocalRef();
}
} else if (ip->opCode == OpCode::Debugger) {
// No breakpoint here and we've already run the debugger,
// just continue on.
// If the current instruction is no longer a debugger instruction,
// we're just going to keep executing from the current IP.
ip = NEXTINST(Debugger);
}
gcScope.flushToSmallCount(KEEP_HANDLES);
}
DISPATCH;
#else
ip = NEXTINST(Debugger);
DISPATCH;
#endif
}
CASE(AsyncBreakCheck) {
if (LLVM_UNLIKELY(runtime->hasAsyncBreak())) {
#ifdef HERMES_ENABLE_DEBUGGER
if (uint8_t asyncFlags =
runtime->testAndClearDebuggerAsyncBreakRequest()) {
RUN_DEBUGGER_ASYNC_BREAK(asyncFlags);
}
#endif
if (runtime->testAndClearTimeoutAsyncBreakRequest()) {
CAPTURE_IP_ASSIGN(auto nRes, runtime->notifyTimeout());
if (nRes == ExecutionStatus::EXCEPTION) {
goto exception;
}
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(AsyncBreakCheck);
DISPATCH;
}
CASE(ProfilePoint) {
#ifdef HERMESVM_PROFILER_BB
auto pointIndex = ip->iProfilePoint.op1;
SLOW_DEBUG(llvh::dbgs() << "ProfilePoint: " << pointIndex << "\n");
CAPTURE_IP(runtime->getBasicBlockExecutionInfo().executeBlock(
curCodeBlock, pointIndex));
#endif
ip = NEXTINST(ProfilePoint);
DISPATCH;
}
CASE(Unreachable) {
llvm_unreachable("Hermes bug: unreachable instruction");
}
CASE(CreateClosure) {
idVal = ip->iCreateClosure.op3;
nextIP = NEXTINST(CreateClosure);
goto createClosure;
}
CASE(CreateClosureLongIndex) {
idVal = ip->iCreateClosureLongIndex.op3;
nextIP = NEXTINST(CreateClosureLongIndex);
goto createClosure;
}
createClosure : {
auto *runtimeModule = curCodeBlock->getRuntimeModule();
CAPTURE_IP_ASSIGN(
O1REG(CreateClosure),
JSFunction::create(
runtime,
runtimeModule->getDomain(runtime),
Handle<JSObject>::vmcast(&runtime->functionPrototype),
Handle<Environment>::vmcast(&O2REG(CreateClosure)),
runtimeModule->getCodeBlockMayAllocate(idVal))
.getHermesValue());
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(CreateGeneratorClosure) {
CAPTURE_IP_ASSIGN(
auto res,
createGeneratorClosure(
runtime,
curCodeBlock->getRuntimeModule(),
ip->iCreateClosure.op3,
Handle<Environment>::vmcast(&O2REG(CreateGeneratorClosure))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CreateGeneratorClosure) = res->getHermesValue();
res->invalidate();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateGeneratorClosure);
DISPATCH;
}
CASE(CreateGeneratorClosureLongIndex) {
CAPTURE_IP_ASSIGN(
auto res,
createGeneratorClosure(
runtime,
curCodeBlock->getRuntimeModule(),
ip->iCreateClosureLongIndex.op3,
Handle<Environment>::vmcast(
&O2REG(CreateGeneratorClosureLongIndex))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CreateGeneratorClosureLongIndex) = res->getHermesValue();
res->invalidate();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateGeneratorClosureLongIndex);
DISPATCH;
}
CASE(CreateGenerator) {
CAPTURE_IP_ASSIGN(
auto res,
createGenerator_RJS(
runtime,
curCodeBlock->getRuntimeModule(),
ip->iCreateGenerator.op3,
Handle<Environment>::vmcast(&O2REG(CreateGenerator)),
FRAME.getNativeArgs()));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CreateGenerator) = res->getHermesValue();
res->invalidate();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateGenerator);
DISPATCH;
}
CASE(CreateGeneratorLongIndex) {
CAPTURE_IP_ASSIGN(
auto res,
createGenerator_RJS(
runtime,
curCodeBlock->getRuntimeModule(),
ip->iCreateGeneratorLongIndex.op3,
Handle<Environment>::vmcast(&O2REG(CreateGeneratorLongIndex)),
FRAME.getNativeArgs()));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(CreateGeneratorLongIndex) = res->getHermesValue();
res->invalidate();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateGeneratorLongIndex);
DISPATCH;
}
CASE(GetEnvironment) {
// The currently executing function must exist, so get the environment.
Environment *curEnv =
FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime);
for (unsigned level = ip->iGetEnvironment.op2; level; --level) {
assert(curEnv && "invalid environment relative level");
curEnv = curEnv->getParentEnvironment(runtime);
}
O1REG(GetEnvironment) = HermesValue::encodeObjectValue(curEnv);
ip = NEXTINST(GetEnvironment);
DISPATCH;
}
CASE(CreateEnvironment) {
tmpHandle = HermesValue::encodeObjectValue(
FRAME.getCalleeClosureUnsafe()->getEnvironment(runtime));
CAPTURE_IP_ASSIGN(
res,
Environment::create(
runtime,
tmpHandle->getPointer() ? Handle<Environment>::vmcast(tmpHandle)
: Handle<Environment>::vmcast_or_null(
&runtime->nullPointer_),
curCodeBlock->getEnvironmentSize()));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
O1REG(CreateEnvironment) = *res;
#ifdef HERMES_ENABLE_DEBUGGER
FRAME.getDebugEnvironmentRef() = *res;
#endif
tmpHandle = HermesValue::encodeUndefinedValue();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateEnvironment);
DISPATCH;
}
CASE(StoreToEnvironment) {
vmcast<Environment>(O1REG(StoreToEnvironment))
->slot(ip->iStoreToEnvironment.op2)
.set(O3REG(StoreToEnvironment), &runtime->getHeap());
ip = NEXTINST(StoreToEnvironment);
DISPATCH;
}
CASE(StoreToEnvironmentL) {
vmcast<Environment>(O1REG(StoreToEnvironmentL))
->slot(ip->iStoreToEnvironmentL.op2)
.set(O3REG(StoreToEnvironmentL), &runtime->getHeap());
ip = NEXTINST(StoreToEnvironmentL);
DISPATCH;
}
CASE(StoreNPToEnvironment) {
vmcast<Environment>(O1REG(StoreNPToEnvironment))
->slot(ip->iStoreNPToEnvironment.op2)
.setNonPtr(O3REG(StoreNPToEnvironment), &runtime->getHeap());
ip = NEXTINST(StoreNPToEnvironment);
DISPATCH;
}
CASE(StoreNPToEnvironmentL) {
vmcast<Environment>(O1REG(StoreNPToEnvironmentL))
->slot(ip->iStoreNPToEnvironmentL.op2)
.setNonPtr(O3REG(StoreNPToEnvironmentL), &runtime->getHeap());
ip = NEXTINST(StoreNPToEnvironmentL);
DISPATCH;
}
CASE(LoadFromEnvironment) {
O1REG(LoadFromEnvironment) =
vmcast<Environment>(O2REG(LoadFromEnvironment))
->slot(ip->iLoadFromEnvironment.op3);
ip = NEXTINST(LoadFromEnvironment);
DISPATCH;
}
CASE(LoadFromEnvironmentL) {
O1REG(LoadFromEnvironmentL) =
vmcast<Environment>(O2REG(LoadFromEnvironmentL))
->slot(ip->iLoadFromEnvironmentL.op3);
ip = NEXTINST(LoadFromEnvironmentL);
DISPATCH;
}
CASE(GetGlobalObject) {
O1REG(GetGlobalObject) = runtime->global_;
ip = NEXTINST(GetGlobalObject);
DISPATCH;
}
CASE(GetNewTarget) {
O1REG(GetNewTarget) = FRAME.getNewTargetRef();
ip = NEXTINST(GetNewTarget);
DISPATCH;
}
CASE(DeclareGlobalVar) {
DefinePropertyFlags dpf =
DefinePropertyFlags::getDefaultNewPropertyFlags();
dpf.configurable = 0;
// Do not overwrite existing globals with undefined.
dpf.setValue = 0;
CAPTURE_IP_ASSIGN(
auto res,
JSObject::defineOwnProperty(
runtime->getGlobal(),
runtime,
ID(ip->iDeclareGlobalVar.op1),
dpf,
Runtime::getUndefinedValue(),
PropOpFlags().plusThrowOnError()));
if (res == ExecutionStatus::EXCEPTION) {
assert(
!runtime->getGlobal()->isProxyObject() &&
"global can't be a proxy object");
// If the property already exists, this should be a noop.
// Instead of incurring the cost to check every time, do it
// only if an exception is thrown, and swallow the exception
// if it exists, since we didn't want to make the call,
// anyway. This most likely means the property is
// non-configurable.
NamedPropertyDescriptor desc;
CAPTURE_IP_ASSIGN(
auto res,
JSObject::getOwnNamedDescriptor(
runtime->getGlobal(),
runtime,
ID(ip->iDeclareGlobalVar.op1),
desc));
if (!res) {
goto exception;
} else {
runtime->clearThrownValue();
}
// fall through
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(DeclareGlobalVar);
DISPATCH;
}
CASE(TryGetByIdLong) {
tryProp = true;
idVal = ip->iTryGetByIdLong.op4;
nextIP = NEXTINST(TryGetByIdLong);
goto getById;
}
CASE(GetByIdLong) {
tryProp = false;
idVal = ip->iGetByIdLong.op4;
nextIP = NEXTINST(GetByIdLong);
goto getById;
}
CASE(GetByIdShort) {
tryProp = false;
idVal = ip->iGetByIdShort.op4;
nextIP = NEXTINST(GetByIdShort);
goto getById;
}
CASE(TryGetById) {
tryProp = true;
idVal = ip->iTryGetById.op4;
nextIP = NEXTINST(TryGetById);
goto getById;
}
CASE(GetById) {
tryProp = false;
idVal = ip->iGetById.op4;
nextIP = NEXTINST(GetById);
}
getById : {
++NumGetById;
// NOTE: it is safe to use OnREG(GetById) here because all instructions
// have the same layout: opcode, registers, non-register operands, i.e.
// they only differ in the width of the last "identifier" field.
CallResult<HermesValue> propRes{ExecutionStatus::EXCEPTION};
if (LLVM_LIKELY(O2REG(GetById).isObject())) {
auto *obj = vmcast<JSObject>(O2REG(GetById));
auto cacheIdx = ip->iGetById.op3;
auto *cacheEntry = curCodeBlock->getReadCacheEntry(cacheIdx);
#ifdef HERMESVM_PROFILER_BB
{
HERMES_SLOW_ASSERT(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"unaccounted handles were created");
auto objHandle = runtime->makeHandle(obj);
auto cacheHCPtr = vmcast_or_null<HiddenClass>(static_cast<GCCell *>(
cacheEntry->clazz.get(runtime, &runtime->getHeap())));
CAPTURE_IP(runtime->recordHiddenClass(
curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));
// obj may be moved by GC due to recordHiddenClass
obj = objHandle.get();
}
gcScope.flushToSmallCount(KEEP_HANDLES);
#endif
auto clazzGCPtr = obj->getClassGCPtr();
#ifndef NDEBUG
if (clazzGCPtr.get(runtime)->isDictionary())
++NumGetByIdDict;
#else
(void)NumGetByIdDict;
#endif
// If we have a cache hit, reuse the cached offset and immediately
// return the property.
if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {
++NumGetByIdCacheHits;
CAPTURE_IP_ASSIGN(
O1REG(GetById),
JSObject::getNamedSlotValue<PropStorage::Inline::Yes>(
obj, runtime, cacheEntry->slot));
ip = nextIP;
DISPATCH;
}
auto id = ID(idVal);
NamedPropertyDescriptor desc;
CAPTURE_IP_ASSIGN(
OptValue<bool> fastPathResult,
JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));
if (LLVM_LIKELY(
fastPathResult.hasValue() && fastPathResult.getValue()) &&
!desc.flags.accessor) {
++NumGetByIdFastPaths;
// cacheIdx == 0 indicates no caching so don't update the cache in
// those cases.
auto *clazz = clazzGCPtr.getNonNull(runtime);
if (LLVM_LIKELY(!clazz->isDictionaryNoCache()) &&
LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {
#ifdef HERMES_SLOW_DEBUG
if (cacheEntry->clazz &&
cacheEntry->clazz != clazzGCPtr.getStorageType())
++NumGetByIdCacheEvicts;
#else
(void)NumGetByIdCacheEvicts;
#endif
// Cache the class, id and property slot.
cacheEntry->clazz = clazzGCPtr.getStorageType();
cacheEntry->slot = desc.slot;
}
CAPTURE_IP_ASSIGN(
O1REG(GetById), JSObject::getNamedSlotValue(obj, runtime, desc));
ip = nextIP;
DISPATCH;
}
// The cache may also be populated via the prototype of the object.
// This value is only reliable if the fast path was a definite
// not-found.
if (fastPathResult.hasValue() && !fastPathResult.getValue() &&
!obj->isProxyObject()) {
CAPTURE_IP_ASSIGN(JSObject * parent, obj->getParent(runtime));
// TODO: This isLazy check is because a lazy object is reported as
// having no properties and therefore cannot contain the property.
// This check does not belong here, it should be merged into
// tryGetOwnNamedDescriptorFast().
if (parent &&
cacheEntry->clazz == parent->getClassGCPtr().getStorageType() &&
LLVM_LIKELY(!obj->isLazy())) {
++NumGetByIdProtoHits;
CAPTURE_IP_ASSIGN(
O1REG(GetById),
JSObject::getNamedSlotValue(parent, runtime, cacheEntry->slot));
ip = nextIP;
DISPATCH;
}
}
#ifdef HERMES_SLOW_DEBUG
CAPTURE_IP_ASSIGN(
JSObject * propObj,
JSObject::getNamedDescriptor(
Handle<JSObject>::vmcast(&O2REG(GetById)), runtime, id, desc));
if (propObj) {
if (desc.flags.accessor)
++NumGetByIdAccessor;
else if (propObj != vmcast<JSObject>(O2REG(GetById)))
++NumGetByIdProto;
} else {
++NumGetByIdNotFound;
}
#else
(void)NumGetByIdAccessor;
(void)NumGetByIdProto;
(void)NumGetByIdNotFound;
#endif
#ifdef HERMES_SLOW_DEBUG
auto *savedClass = cacheIdx != hbc::PROPERTY_CACHING_DISABLED
? cacheEntry->clazz.get(runtime, &runtime->getHeap())
: nullptr;
#endif
++NumGetByIdSlow;
CAPTURE_IP_ASSIGN(
resPH,
JSObject::getNamed_RJS(
Handle<JSObject>::vmcast(&O2REG(GetById)),
runtime,
id,
!tryProp ? defaultPropOpFlags
: defaultPropOpFlags.plusMustExist(),
cacheIdx != hbc::PROPERTY_CACHING_DISABLED ? cacheEntry
: nullptr));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
#ifdef HERMES_SLOW_DEBUG
if (cacheIdx != hbc::PROPERTY_CACHING_DISABLED && savedClass &&
cacheEntry->clazz.get(runtime, &runtime->getHeap()) != savedClass) {
++NumGetByIdCacheEvicts;
}
#endif
} else {
++NumGetByIdTransient;
assert(!tryProp && "TryGetById can only be used on the global object");
/* Slow path. */
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::getByIdTransient_RJS(
runtime, Handle<>(&O2REG(GetById)), ID(idVal)));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
}
O1REG(GetById) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(TryPutByIdLong) {
tryProp = true;
idVal = ip->iTryPutByIdLong.op4;
nextIP = NEXTINST(TryPutByIdLong);
goto putById;
}
CASE(PutByIdLong) {
tryProp = false;
idVal = ip->iPutByIdLong.op4;
nextIP = NEXTINST(PutByIdLong);
goto putById;
}
CASE(TryPutById) {
tryProp = true;
idVal = ip->iTryPutById.op4;
nextIP = NEXTINST(TryPutById);
goto putById;
}
CASE(PutById) {
tryProp = false;
idVal = ip->iPutById.op4;
nextIP = NEXTINST(PutById);
}
putById : {
++NumPutById;
if (LLVM_LIKELY(O1REG(PutById).isObject())) {
auto *obj = vmcast<JSObject>(O1REG(PutById));
auto cacheIdx = ip->iPutById.op3;
auto *cacheEntry = curCodeBlock->getWriteCacheEntry(cacheIdx);
#ifdef HERMESVM_PROFILER_BB
{
HERMES_SLOW_ASSERT(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"unaccounted handles were created");
auto objHandle = runtime->makeHandle(obj);
auto cacheHCPtr = vmcast_or_null<HiddenClass>(static_cast<GCCell *>(
cacheEntry->clazz.get(runtime, &runtime->getHeap())));
CAPTURE_IP(runtime->recordHiddenClass(
curCodeBlock, ip, ID(idVal), obj->getClass(runtime), cacheHCPtr));
// obj may be moved by GC due to recordHiddenClass
obj = objHandle.get();
}
gcScope.flushToSmallCount(KEEP_HANDLES);
#endif
auto clazzGCPtr = obj->getClassGCPtr();
// If we have a cache hit, reuse the cached offset and immediately
// return the property.
if (LLVM_LIKELY(cacheEntry->clazz == clazzGCPtr.getStorageType())) {
++NumPutByIdCacheHits;
CAPTURE_IP(JSObject::setNamedSlotValue<PropStorage::Inline::Yes>(
obj, runtime, cacheEntry->slot, O2REG(PutById)));
ip = nextIP;
DISPATCH;
}
auto id = ID(idVal);
NamedPropertyDescriptor desc;
CAPTURE_IP_ASSIGN(
OptValue<bool> hasOwnProp,
JSObject::tryGetOwnNamedDescriptorFast(obj, runtime, id, desc));
if (LLVM_LIKELY(hasOwnProp.hasValue() && hasOwnProp.getValue()) &&
!desc.flags.accessor && desc.flags.writable &&
!desc.flags.internalSetter) {
++NumPutByIdFastPaths;
// cacheIdx == 0 indicates no caching so don't update the cache in
// those cases.
auto *clazz = clazzGCPtr.getNonNull(runtime);
if (LLVM_LIKELY(!clazz->isDictionary()) &&
LLVM_LIKELY(cacheIdx != hbc::PROPERTY_CACHING_DISABLED)) {
#ifdef HERMES_SLOW_DEBUG
if (cacheEntry->clazz &&
cacheEntry->clazz != clazzGCPtr.getStorageType())
++NumPutByIdCacheEvicts;
#else
(void)NumPutByIdCacheEvicts;
#endif
// Cache the class and property slot.
cacheEntry->clazz = clazzGCPtr.getStorageType();
cacheEntry->slot = desc.slot;
}
CAPTURE_IP(JSObject::setNamedSlotValue(
obj, runtime, desc.slot, O2REG(PutById)));
ip = nextIP;
DISPATCH;
}
CAPTURE_IP_ASSIGN(
auto putRes,
JSObject::putNamed_RJS(
Handle<JSObject>::vmcast(&O1REG(PutById)),
runtime,
id,
Handle<>(&O2REG(PutById)),
!tryProp ? defaultPropOpFlags
: defaultPropOpFlags.plusMustExist()));
if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {
goto exception;
}
} else {
++NumPutByIdTransient;
assert(!tryProp && "TryPutById can only be used on the global object");
CAPTURE_IP_ASSIGN(
auto retStatus,
Interpreter::putByIdTransient_RJS(
runtime,
Handle<>(&O1REG(PutById)),
ID(idVal),
Handle<>(&O2REG(PutById)),
strictMode));
if (retStatus == ExecutionStatus::EXCEPTION) {
goto exception;
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(GetByVal) {
CallResult<HermesValue> propRes{ExecutionStatus::EXCEPTION};
if (LLVM_LIKELY(O2REG(GetByVal).isObject())) {
CAPTURE_IP_ASSIGN(
resPH,
JSObject::getComputed_RJS(
Handle<JSObject>::vmcast(&O2REG(GetByVal)),
runtime,
Handle<>(&O3REG(GetByVal))));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
} else {
// This is the "slow path".
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::getByValTransient_RJS(
runtime,
Handle<>(&O2REG(GetByVal)),
Handle<>(&O3REG(GetByVal))));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(GetByVal) = resPH->get();
ip = NEXTINST(GetByVal);
DISPATCH;
}
CASE(PutByVal) {
if (LLVM_LIKELY(O1REG(PutByVal).isObject())) {
CAPTURE_IP_ASSIGN(
auto putRes,
JSObject::putComputed_RJS(
Handle<JSObject>::vmcast(&O1REG(PutByVal)),
runtime,
Handle<>(&O2REG(PutByVal)),
Handle<>(&O3REG(PutByVal)),
defaultPropOpFlags));
if (LLVM_UNLIKELY(putRes == ExecutionStatus::EXCEPTION)) {
goto exception;
}
} else {
// This is the "slow path".
CAPTURE_IP_ASSIGN(
auto retStatus,
Interpreter::putByValTransient_RJS(
runtime,
Handle<>(&O1REG(PutByVal)),
Handle<>(&O2REG(PutByVal)),
Handle<>(&O3REG(PutByVal)),
strictMode));
if (LLVM_UNLIKELY(retStatus == ExecutionStatus::EXCEPTION)) {
goto exception;
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(PutByVal);
DISPATCH;
}
CASE(PutOwnByIndexL) {
nextIP = NEXTINST(PutOwnByIndexL);
idVal = ip->iPutOwnByIndexL.op3;
goto putOwnByIndex;
}
CASE(PutOwnByIndex) {
nextIP = NEXTINST(PutOwnByIndex);
idVal = ip->iPutOwnByIndex.op3;
}
putOwnByIndex : {
tmpHandle = HermesValue::encodeDoubleValue(idVal);
CAPTURE_IP(JSObject::defineOwnComputedPrimitive(
Handle<JSObject>::vmcast(&O1REG(PutOwnByIndex)),
runtime,
tmpHandle,
DefinePropertyFlags::getDefaultNewPropertyFlags(),
Handle<>(&O2REG(PutOwnByIndex))));
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = nextIP;
DISPATCH;
}
CASE(GetPNameList) {
CAPTURE_IP_ASSIGN(
auto pRes, handleGetPNameList(runtime, frameRegs, ip));
if (LLVM_UNLIKELY(pRes == ExecutionStatus::EXCEPTION)) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(GetPNameList);
DISPATCH;
}
CASE(GetNextPName) {
{
assert(
vmisa<BigStorage>(O2REG(GetNextPName)) &&
"GetNextPName's second op must be BigStorage");
auto obj = Handle<JSObject>::vmcast(&O3REG(GetNextPName));
auto arr = Handle<BigStorage>::vmcast(&O2REG(GetNextPName));
uint32_t idx = O4REG(GetNextPName).getNumber();
uint32_t size = O5REG(GetNextPName).getNumber();
MutableHandle<JSObject> propObj{runtime};
// Loop until we find a property which is present.
while (idx < size) {
tmpHandle = arr->at(idx);
ComputedPropertyDescriptor desc;
CAPTURE_IP(JSObject::getComputedPrimitiveDescriptor(
obj, runtime, tmpHandle, propObj, desc));
if (LLVM_LIKELY(propObj))
break;
++idx;
}
if (idx < size) {
// We must return the property as a string
if (tmpHandle->isNumber()) {
CAPTURE_IP_ASSIGN(auto status, toString_RJS(runtime, tmpHandle));
assert(
status == ExecutionStatus::RETURNED &&
"toString on number cannot fail");
tmpHandle = status->getHermesValue();
}
O1REG(GetNextPName) = tmpHandle.get();
O4REG(GetNextPName) = HermesValue::encodeNumberValue(idx + 1);
} else {
O1REG(GetNextPName) = HermesValue::encodeUndefinedValue();
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = NEXTINST(GetNextPName);
DISPATCH;
}
CASE(ToNumber) {
if (LLVM_LIKELY(O2REG(ToNumber).isNumber())) {
O1REG(ToNumber) = O2REG(ToNumber);
ip = NEXTINST(ToNumber);
} else {
CAPTURE_IP_ASSIGN(
res, toNumber_RJS(runtime, Handle<>(&O2REG(ToNumber))));
if (res == ExecutionStatus::EXCEPTION)
goto exception;
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(ToNumber) = res.getValue();
ip = NEXTINST(ToNumber);
}
DISPATCH;
}
CASE(ToInt32) {
CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(ToInt32))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
goto exception;
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(ToInt32) = res.getValue();
ip = NEXTINST(ToInt32);
DISPATCH;
}
CASE(AddEmptyString) {
if (LLVM_LIKELY(O2REG(AddEmptyString).isString())) {
O1REG(AddEmptyString) = O2REG(AddEmptyString);
ip = NEXTINST(AddEmptyString);
} else {
CAPTURE_IP_ASSIGN(
res,
toPrimitive_RJS(
runtime,
Handle<>(&O2REG(AddEmptyString)),
PreferredType::NONE));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION))
goto exception;
tmpHandle = res.getValue();
CAPTURE_IP_ASSIGN(auto strRes, toString_RJS(runtime, tmpHandle));
if (LLVM_UNLIKELY(strRes == ExecutionStatus::EXCEPTION))
goto exception;
tmpHandle.clear();
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(AddEmptyString) = strRes->getHermesValue();
ip = NEXTINST(AddEmptyString);
}
DISPATCH;
}
CASE(Jmp) {
ip = IPADD(ip->iJmp.op1);
DISPATCH;
}
CASE(JmpLong) {
ip = IPADD(ip->iJmpLong.op1);
DISPATCH;
}
CASE(JmpTrue) {
if (toBoolean(O2REG(JmpTrue)))
ip = IPADD(ip->iJmpTrue.op1);
else
ip = NEXTINST(JmpTrue);
DISPATCH;
}
CASE(JmpTrueLong) {
if (toBoolean(O2REG(JmpTrueLong)))
ip = IPADD(ip->iJmpTrueLong.op1);
else
ip = NEXTINST(JmpTrueLong);
DISPATCH;
}
CASE(JmpFalse) {
if (!toBoolean(O2REG(JmpFalse)))
ip = IPADD(ip->iJmpFalse.op1);
else
ip = NEXTINST(JmpFalse);
DISPATCH;
}
CASE(JmpFalseLong) {
if (!toBoolean(O2REG(JmpFalseLong)))
ip = IPADD(ip->iJmpFalseLong.op1);
else
ip = NEXTINST(JmpFalseLong);
DISPATCH;
}
CASE(JmpUndefined) {
if (O2REG(JmpUndefined).isUndefined())
ip = IPADD(ip->iJmpUndefined.op1);
else
ip = NEXTINST(JmpUndefined);
DISPATCH;
}
CASE(JmpUndefinedLong) {
if (O2REG(JmpUndefinedLong).isUndefined())
ip = IPADD(ip->iJmpUndefinedLong.op1);
else
ip = NEXTINST(JmpUndefinedLong);
DISPATCH;
}
CASE(Add) {
if (LLVM_LIKELY(
O2REG(Add).isNumber() &&
O3REG(Add).isNumber())) { /* Fast-path. */
CASE(AddN) {
O1REG(Add) = HermesValue::encodeDoubleValue(
O2REG(Add).getNumber() + O3REG(Add).getNumber());
ip = NEXTINST(Add);
DISPATCH;
}
}
CAPTURE_IP_ASSIGN(
res,
addOp_RJS(runtime, Handle<>(&O2REG(Add)), Handle<>(&O3REG(Add))));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(Add) = res.getValue();
ip = NEXTINST(Add);
DISPATCH;
}
CASE(BitNot) {
if (LLVM_LIKELY(O2REG(BitNot).isNumber())) { /* Fast-path. */
O1REG(BitNot) = HermesValue::encodeDoubleValue(
~hermes::truncateToInt32(O2REG(BitNot).getNumber()));
ip = NEXTINST(BitNot);
DISPATCH;
}
CAPTURE_IP_ASSIGN(res, toInt32_RJS(runtime, Handle<>(&O2REG(BitNot))));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(BitNot) = HermesValue::encodeDoubleValue(
~static_cast<int32_t>(res->getNumber()));
ip = NEXTINST(BitNot);
DISPATCH;
}
CASE(GetArgumentsLength) {
// If the arguments object hasn't been created yet.
if (O2REG(GetArgumentsLength).isUndefined()) {
O1REG(GetArgumentsLength) =
HermesValue::encodeNumberValue(FRAME.getArgCount());
ip = NEXTINST(GetArgumentsLength);
DISPATCH;
}
// The arguments object has been created, so this is a regular property
// get.
assert(
O2REG(GetArgumentsLength).isObject() &&
"arguments lazy register is not an object");
CAPTURE_IP_ASSIGN(
resPH,
JSObject::getNamed_RJS(
Handle<JSObject>::vmcast(&O2REG(GetArgumentsLength)),
runtime,
Predefined::getSymbolID(Predefined::length)));
if (resPH == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(GetArgumentsLength) = resPH->get();
ip = NEXTINST(GetArgumentsLength);
DISPATCH;
}
CASE(GetArgumentsPropByVal) {
// If the arguments object hasn't been created yet and we have a
// valid integer index, we use the fast path.
if (O3REG(GetArgumentsPropByVal).isUndefined()) {
// If this is an integer index.
if (auto index = toArrayIndexFastPath(O2REG(GetArgumentsPropByVal))) {
// Is this an existing argument?
if (*index < FRAME.getArgCount()) {
O1REG(GetArgumentsPropByVal) = FRAME.getArgRef(*index);
ip = NEXTINST(GetArgumentsPropByVal);
DISPATCH;
}
}
}
// Slow path.
CAPTURE_IP_ASSIGN(
auto res,
getArgumentsPropByValSlowPath_RJS(
runtime,
&O3REG(GetArgumentsPropByVal),
&O2REG(GetArgumentsPropByVal),
FRAME.getCalleeClosureHandleUnsafe(),
strictMode));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(GetArgumentsPropByVal) = res->getHermesValue();
ip = NEXTINST(GetArgumentsPropByVal);
DISPATCH;
}
CASE(ReifyArguments) {
// If the arguments object was already created, do nothing.
if (!O1REG(ReifyArguments).isUndefined()) {
assert(
O1REG(ReifyArguments).isObject() &&
"arguments lazy register is not an object");
ip = NEXTINST(ReifyArguments);
DISPATCH;
}
CAPTURE_IP_ASSIGN(
resArgs,
reifyArgumentsSlowPath(
runtime, FRAME.getCalleeClosureHandleUnsafe(), strictMode));
if (LLVM_UNLIKELY(resArgs == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(ReifyArguments) = resArgs->getHermesValue();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(ReifyArguments);
DISPATCH;
}
CASE(NewObject) {
// Create a new object using the built-in constructor. Note that the
// built-in constructor is empty, so we don't actually need to call
// it.
CAPTURE_IP_ASSIGN(
O1REG(NewObject), JSObject::create(runtime).getHermesValue());
assert(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"Should not create handles.");
ip = NEXTINST(NewObject);
DISPATCH;
}
CASE(NewObjectWithParent) {
CAPTURE_IP_ASSIGN(
O1REG(NewObjectWithParent),
JSObject::create(
runtime,
O2REG(NewObjectWithParent).isObject()
? Handle<JSObject>::vmcast(&O2REG(NewObjectWithParent))
: O2REG(NewObjectWithParent).isNull()
? Runtime::makeNullHandle<JSObject>()
: Handle<JSObject>::vmcast(&runtime->objectPrototype))
.getHermesValue());
assert(
gcScope.getHandleCountDbg() == KEEP_HANDLES &&
"Should not create handles.");
ip = NEXTINST(NewObjectWithParent);
DISPATCH;
}
CASE(NewObjectWithBuffer) {
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::createObjectFromBuffer(
runtime,
curCodeBlock,
ip->iNewObjectWithBuffer.op3,
ip->iNewObjectWithBuffer.op4,
ip->iNewObjectWithBuffer.op5));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(NewObjectWithBuffer) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(NewObjectWithBuffer);
DISPATCH;
}
CASE(NewObjectWithBufferLong) {
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::createObjectFromBuffer(
runtime,
curCodeBlock,
ip->iNewObjectWithBufferLong.op3,
ip->iNewObjectWithBufferLong.op4,
ip->iNewObjectWithBufferLong.op5));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(NewObjectWithBufferLong) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(NewObjectWithBufferLong);
DISPATCH;
}
CASE(NewArray) {
// Create a new array using the built-in constructor. Note that the
// built-in constructor is empty, so we don't actually need to call
// it.
CAPTURE_IP_ASSIGN(
auto createRes,
JSArray::create(runtime, ip->iNewArray.op2, ip->iNewArray.op2));
if (createRes == ExecutionStatus::EXCEPTION) {
goto exception;
}
O1REG(NewArray) = createRes->getHermesValue();
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(NewArray);
DISPATCH;
}
CASE(NewArrayWithBuffer) {
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::createArrayFromBuffer(
runtime,
curCodeBlock,
ip->iNewArrayWithBuffer.op2,
ip->iNewArrayWithBuffer.op3,
ip->iNewArrayWithBuffer.op4));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(NewArrayWithBuffer) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = NEXTINST(NewArrayWithBuffer);
DISPATCH;
}
CASE(NewArrayWithBufferLong) {
CAPTURE_IP_ASSIGN(
resPH,
Interpreter::createArrayFromBuffer(
runtime,
curCodeBlock,
ip->iNewArrayWithBufferLong.op2,
ip->iNewArrayWithBufferLong.op3,
ip->iNewArrayWithBufferLong.op4));
if (LLVM_UNLIKELY(resPH == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(NewArrayWithBufferLong) = resPH->get();
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = NEXTINST(NewArrayWithBufferLong);
DISPATCH;
}
CASE(CreateThis) {
// Registers: output, prototype, closure.
if (LLVM_UNLIKELY(!vmisa<Callable>(O3REG(CreateThis)))) {
CAPTURE_IP(runtime->raiseTypeError("constructor is not callable"));
goto exception;
}
CAPTURE_IP_ASSIGN(
auto res,
Callable::newObject(
Handle<Callable>::vmcast(&O3REG(CreateThis)),
runtime,
Handle<JSObject>::vmcast(
O2REG(CreateThis).isObject() ? &O2REG(CreateThis)
: &runtime->objectPrototype)));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(CreateThis) = res->getHermesValue();
ip = NEXTINST(CreateThis);
DISPATCH;
}
CASE(SelectObject) {
// Registers: output, thisObject, constructorReturnValue.
O1REG(SelectObject) = O3REG(SelectObject).isObject()
? O3REG(SelectObject)
: O2REG(SelectObject);
ip = NEXTINST(SelectObject);
DISPATCH;
}
CASE(Eq)
CASE(Neq) {
CAPTURE_IP_ASSIGN(
res,
abstractEqualityTest_RJS(
runtime, Handle<>(&O2REG(Eq)), Handle<>(&O3REG(Eq))));
if (res == ExecutionStatus::EXCEPTION) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(Eq) = ip->opCode == OpCode::Eq
? res.getValue()
: HermesValue::encodeBoolValue(!res->getBool());
ip = NEXTINST(Eq);
DISPATCH;
}
CASE(StrictEq) {
O1REG(StrictEq) = HermesValue::encodeBoolValue(
strictEqualityTest(O2REG(StrictEq), O3REG(StrictEq)));
ip = NEXTINST(StrictEq);
DISPATCH;
}
CASE(StrictNeq) {
O1REG(StrictNeq) = HermesValue::encodeBoolValue(
!strictEqualityTest(O2REG(StrictNeq), O3REG(StrictNeq)));
ip = NEXTINST(StrictNeq);
DISPATCH;
}
CASE(Not) {
O1REG(Not) = HermesValue::encodeBoolValue(!toBoolean(O2REG(Not)));
ip = NEXTINST(Not);
DISPATCH;
}
CASE(Negate) {
if (LLVM_LIKELY(O2REG(Negate).isNumber())) {
O1REG(Negate) =
HermesValue::encodeDoubleValue(-O2REG(Negate).getNumber());
} else {
CAPTURE_IP_ASSIGN(
res, toNumber_RJS(runtime, Handle<>(&O2REG(Negate))));
if (res == ExecutionStatus::EXCEPTION)
goto exception;
gcScope.flushToSmallCount(KEEP_HANDLES);
O1REG(Negate) = HermesValue::encodeDoubleValue(-res->getNumber());
}
ip = NEXTINST(Negate);
DISPATCH;
}
CASE(TypeOf) {
CAPTURE_IP_ASSIGN(
O1REG(TypeOf), typeOf(runtime, Handle<>(&O2REG(TypeOf))));
ip = NEXTINST(TypeOf);
DISPATCH;
}
CASE(Mod) {
// We use fmod here for simplicity. Theoretically fmod behaves slightly
// differently than the ECMAScript Spec. fmod applies round-towards-zero
// for the remainder when it's not representable by a double; while the
// spec requires round-to-nearest. As an example, 5 % 0.7 will give
// 0.10000000000000031 using fmod, but using the rounding style
// described
// by the spec, the output should really be 0.10000000000000053.
// Such difference can be ignored in practice.
if (LLVM_LIKELY(O2REG(Mod).isNumber() && O3REG(Mod).isNumber())) {
/* Fast-path. */
O1REG(Mod) = HermesValue::encodeDoubleValue(
std::fmod(O2REG(Mod).getNumber(), O3REG(Mod).getNumber()));
ip = NEXTINST(Mod);
DISPATCH;
}
CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O2REG(Mod))));
if (res == ExecutionStatus::EXCEPTION)
goto exception;
double left = res->getDouble();
CAPTURE_IP_ASSIGN(res, toNumber_RJS(runtime, Handle<>(&O3REG(Mod))));
if (res == ExecutionStatus::EXCEPTION)
goto exception;
O1REG(Mod) =
HermesValue::encodeDoubleValue(std::fmod(left, res->getDouble()));
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(Mod);
DISPATCH;
}
CASE(InstanceOf) {
CAPTURE_IP_ASSIGN(
auto result,
instanceOfOperator_RJS(
runtime,
Handle<>(&O2REG(InstanceOf)),
Handle<>(&O3REG(InstanceOf))));
if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(InstanceOf) = HermesValue::encodeBoolValue(*result);
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(InstanceOf);
DISPATCH;
}
CASE(IsIn) {
{
if (LLVM_UNLIKELY(!O3REG(IsIn).isObject())) {
CAPTURE_IP(runtime->raiseTypeError(
"right operand of 'in' is not an object"));
goto exception;
}
CAPTURE_IP_ASSIGN(
auto cr,
JSObject::hasComputed(
Handle<JSObject>::vmcast(&O3REG(IsIn)),
runtime,
Handle<>(&O2REG(IsIn))));
if (cr == ExecutionStatus::EXCEPTION) {
goto exception;
}
O1REG(IsIn) = HermesValue::encodeBoolValue(*cr);
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(IsIn);
DISPATCH;
}
CASE(PutNewOwnByIdShort) {
nextIP = NEXTINST(PutNewOwnByIdShort);
idVal = ip->iPutNewOwnByIdShort.op3;
goto putOwnById;
}
CASE(PutNewOwnNEByIdLong)
CASE(PutNewOwnByIdLong) {
nextIP = NEXTINST(PutNewOwnByIdLong);
idVal = ip->iPutNewOwnByIdLong.op3;
goto putOwnById;
}
CASE(PutNewOwnNEById)
CASE(PutNewOwnById) {
nextIP = NEXTINST(PutNewOwnById);
idVal = ip->iPutNewOwnById.op3;
}
putOwnById : {
assert(
O1REG(PutNewOwnById).isObject() &&
"Object argument of PutNewOwnById must be an object");
CAPTURE_IP_ASSIGN(
auto res,
JSObject::defineNewOwnProperty(
Handle<JSObject>::vmcast(&O1REG(PutNewOwnById)),
runtime,
ID(idVal),
ip->opCode <= OpCode::PutNewOwnByIdLong
? PropertyFlags::defaultNewNamedPropertyFlags()
: PropertyFlags::nonEnumerablePropertyFlags(),
Handle<>(&O2REG(PutNewOwnById))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(DelByIdLong) {
idVal = ip->iDelByIdLong.op3;
nextIP = NEXTINST(DelByIdLong);
goto DelById;
}
CASE(DelById) {
idVal = ip->iDelById.op3;
nextIP = NEXTINST(DelById);
}
DelById : {
if (LLVM_LIKELY(O2REG(DelById).isObject())) {
CAPTURE_IP_ASSIGN(
auto status,
JSObject::deleteNamed(
Handle<JSObject>::vmcast(&O2REG(DelById)),
runtime,
ID(idVal),
defaultPropOpFlags));
if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());
} else {
// This is the "slow path".
CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelById))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
// If an exception is thrown, likely we are trying to convert
// undefined/null to an object. Passing over the name of the property
// so that we could emit more meaningful error messages.
CAPTURE_IP(amendPropAccessErrorMsgWithPropName(
runtime, Handle<>(&O2REG(DelById)), "delete", ID(idVal)));
goto exception;
}
tmpHandle = res.getValue();
CAPTURE_IP_ASSIGN(
auto status,
JSObject::deleteNamed(
Handle<JSObject>::vmcast(tmpHandle),
runtime,
ID(idVal),
defaultPropOpFlags));
if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(DelById) = HermesValue::encodeBoolValue(status.getValue());
tmpHandle.clear();
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = nextIP;
DISPATCH;
}
CASE(DelByVal) {
if (LLVM_LIKELY(O2REG(DelByVal).isObject())) {
CAPTURE_IP_ASSIGN(
auto status,
JSObject::deleteComputed(
Handle<JSObject>::vmcast(&O2REG(DelByVal)),
runtime,
Handle<>(&O3REG(DelByVal)),
defaultPropOpFlags));
if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());
} else {
// This is the "slow path".
CAPTURE_IP_ASSIGN(res, toObject(runtime, Handle<>(&O2REG(DelByVal))));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
goto exception;
}
tmpHandle = res.getValue();
CAPTURE_IP_ASSIGN(
auto status,
JSObject::deleteComputed(
Handle<JSObject>::vmcast(tmpHandle),
runtime,
Handle<>(&O3REG(DelByVal)),
defaultPropOpFlags));
if (LLVM_UNLIKELY(status == ExecutionStatus::EXCEPTION)) {
goto exception;
}
O1REG(DelByVal) = HermesValue::encodeBoolValue(status.getValue());
}
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
ip = NEXTINST(DelByVal);
DISPATCH;
}
CASE(CreateRegExp) {
{
// Create the RegExp object.
CAPTURE_IP_ASSIGN(auto re, JSRegExp::create(runtime));
// Initialize the regexp.
CAPTURE_IP_ASSIGN(
auto pattern,
runtime->makeHandle(curCodeBlock->getRuntimeModule()
->getStringPrimFromStringIDMayAllocate(
ip->iCreateRegExp.op2)));
CAPTURE_IP_ASSIGN(
auto flags,
runtime->makeHandle(curCodeBlock->getRuntimeModule()
->getStringPrimFromStringIDMayAllocate(
ip->iCreateRegExp.op3)));
CAPTURE_IP_ASSIGN(
auto bytecode,
curCodeBlock->getRuntimeModule()->getRegExpBytecodeFromRegExpID(
ip->iCreateRegExp.op4));
CAPTURE_IP_ASSIGN(
auto initRes,
JSRegExp::initialize(re, runtime, pattern, flags, bytecode));
if (LLVM_UNLIKELY(initRes == ExecutionStatus::EXCEPTION)) {
goto exception;
}
// Done, return the new object.
O1REG(CreateRegExp) = re.getHermesValue();
}
gcScope.flushToSmallCount(KEEP_HANDLES);
ip = NEXTINST(CreateRegExp);
DISPATCH;
}
CASE(SwitchImm) {
if (LLVM_LIKELY(O1REG(SwitchImm).isNumber())) {
double numVal = O1REG(SwitchImm).getNumber();
uint32_t uintVal = (uint32_t)numVal;
if (LLVM_LIKELY(numVal == uintVal) && // Only integers.
LLVM_LIKELY(uintVal >= ip->iSwitchImm.op4) && // Bounds checking.
LLVM_LIKELY(uintVal <= ip->iSwitchImm.op5)) // Bounds checking.
{
// Calculate the offset into the bytecode where the jump table for
// this SwitchImm starts.
const uint8_t *tablestart = (const uint8_t *)llvh::alignAddr(
(const uint8_t *)ip + ip->iSwitchImm.op2, sizeof(uint32_t));
// Read the offset from the table.
// Must be signed to account for backwards branching.
const int32_t *loc =
(const int32_t *)tablestart + uintVal - ip->iSwitchImm.op4;
ip = IPADD(*loc);
DISPATCH;
}
}
// Wrong type or out of range, jump to default.
ip = IPADD(ip->iSwitchImm.op3);
DISPATCH;
}
LOAD_CONST(
LoadConstUInt8,
HermesValue::encodeDoubleValue(ip->iLoadConstUInt8.op2));
LOAD_CONST(
LoadConstInt, HermesValue::encodeDoubleValue(ip->iLoadConstInt.op2));
LOAD_CONST(
LoadConstDouble,
HermesValue::encodeDoubleValue(ip->iLoadConstDouble.op2));
LOAD_CONST_CAPTURE_IP(
LoadConstString,
HermesValue::encodeStringValue(
curCodeBlock->getRuntimeModule()
->getStringPrimFromStringIDMayAllocate(
ip->iLoadConstString.op2)));
LOAD_CONST_CAPTURE_IP(
LoadConstStringLongIndex,
HermesValue::encodeStringValue(
curCodeBlock->getRuntimeModule()
->getStringPrimFromStringIDMayAllocate(
ip->iLoadConstStringLongIndex.op2)));
LOAD_CONST(LoadConstUndefined, HermesValue::encodeUndefinedValue());
LOAD_CONST(LoadConstNull, HermesValue::encodeNullValue());
LOAD_CONST(LoadConstTrue, HermesValue::encodeBoolValue(true));
LOAD_CONST(LoadConstFalse, HermesValue::encodeBoolValue(false));
LOAD_CONST(LoadConstZero, HermesValue::encodeDoubleValue(0));
BINOP(Sub, doSub);
BINOP(Mul, doMult);
BINOP(Div, doDiv);
BITWISEBINOP(BitAnd, &);
BITWISEBINOP(BitOr, |);
BITWISEBINOP(BitXor, ^);
// For LShift, we need to use toUInt32 first because lshift on negative
// numbers is undefined behavior in theory.
SHIFTOP(LShift, <<, toUInt32_RJS, uint32_t, int32_t);
SHIFTOP(RShift, >>, toInt32_RJS, int32_t, int32_t);
SHIFTOP(URshift, >>, toUInt32_RJS, uint32_t, uint32_t);
CONDOP(Less, <, lessOp_RJS);
CONDOP(LessEq, <=, lessEqualOp_RJS);
CONDOP(Greater, >, greaterOp_RJS);
CONDOP(GreaterEq, >=, greaterEqualOp_RJS);
JCOND(Less, <, lessOp_RJS);
JCOND(LessEqual, <=, lessEqualOp_RJS);
JCOND(Greater, >, greaterOp_RJS);
JCOND(GreaterEqual, >=, greaterEqualOp_RJS);
JCOND_STRICT_EQ_IMPL(
JStrictEqual, , IPADD(ip->iJStrictEqual.op1), NEXTINST(JStrictEqual));
JCOND_STRICT_EQ_IMPL(
JStrictEqual,
Long,
IPADD(ip->iJStrictEqualLong.op1),
NEXTINST(JStrictEqualLong));
JCOND_STRICT_EQ_IMPL(
JStrictNotEqual,
,
NEXTINST(JStrictNotEqual),
IPADD(ip->iJStrictNotEqual.op1));
JCOND_STRICT_EQ_IMPL(
JStrictNotEqual,
Long,
NEXTINST(JStrictNotEqualLong),
IPADD(ip->iJStrictNotEqualLong.op1));
JCOND_EQ_IMPL(JEqual, , IPADD(ip->iJEqual.op1), NEXTINST(JEqual));
JCOND_EQ_IMPL(
JEqual, Long, IPADD(ip->iJEqualLong.op1), NEXTINST(JEqualLong));
JCOND_EQ_IMPL(
JNotEqual, , NEXTINST(JNotEqual), IPADD(ip->iJNotEqual.op1));
JCOND_EQ_IMPL(
JNotEqual,
Long,
NEXTINST(JNotEqualLong),
IPADD(ip->iJNotEqualLong.op1));
CASE_OUTOFLINE(PutOwnByVal);
CASE_OUTOFLINE(PutOwnGetterSetterByVal);
CASE_OUTOFLINE(DirectEval);
CASE_OUTOFLINE(IteratorBegin);
CASE_OUTOFLINE(IteratorNext);
CASE(IteratorClose) {
if (LLVM_UNLIKELY(O1REG(IteratorClose).isObject())) {
// The iterator must be closed if it's still an object.
// That means it was never an index and is not done iterating (a state
// which is indicated by `undefined`).
CAPTURE_IP_ASSIGN(
auto res,
iteratorClose(
runtime,
Handle<JSObject>::vmcast(&O1REG(IteratorClose)),
Runtime::getEmptyValue()));
if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {
if (ip->iIteratorClose.op2 &&
!isUncatchableError(runtime->thrownValue_)) {
// Ignore inner exception.
runtime->clearThrownValue();
} else {
goto exception;
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
}
ip = NEXTINST(IteratorClose);
DISPATCH;
}
CASE(_last) {
llvm_unreachable("Invalid opcode _last");
}
}
llvm_unreachable("unreachable");
// We arrive here if we couldn't allocate the registers for the current frame.
stackOverflow:
CAPTURE_IP(runtime->raiseStackOverflow(
Runtime::StackOverflowKind::JSRegisterStack));
// We arrive here when we raised an exception in a callee, but we don't want
// the callee to be able to handle it.
handleExceptionInParent:
// Restore the caller code block and IP.
curCodeBlock = FRAME.getSavedCodeBlock();
ip = FRAME.getSavedIP();
// Pop to the previous frame where technically the error happened.
frameRegs =
&runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();
// If we are coming from native code, return.
if (!curCodeBlock)
return ExecutionStatus::EXCEPTION;
// Return because of recursive calling structure
#ifdef HERMESVM_PROFILER_EXTERN
return ExecutionStatus::EXCEPTION;
#endif
// Handle the exception.
exception:
UPDATE_OPCODE_TIME_SPENT;
assert(
!runtime->thrownValue_.isEmpty() &&
"thrownValue unavailable at exception");
bool catchable = true;
// If this is an Error object that was thrown internally, it didn't have
// access to the current codeblock and IP, so collect the stack trace here.
if (auto *jsError = dyn_vmcast<JSError>(runtime->thrownValue_)) {
catchable = jsError->catchable();
if (!jsError->getStackTrace()) {
// Temporarily clear the thrown value for following operations.
CAPTURE_IP_ASSIGN(
auto errorHandle,
runtime->makeHandle(vmcast<JSError>(runtime->thrownValue_)));
runtime->clearThrownValue();
CAPTURE_IP(JSError::recordStackTrace(
errorHandle, runtime, false, curCodeBlock, ip));
// Restore the thrown value.
runtime->setThrownValue(errorHandle.getHermesValue());
}
}
gcScope.flushToSmallCount(KEEP_HANDLES);
tmpHandle.clear();
#ifdef HERMES_ENABLE_DEBUGGER
if (SingleStep) {
// If we're single stepping, don't bother with any more checks,
// and simply signal that we should continue execution with an exception.
state.codeBlock = curCodeBlock;
state.offset = CUROFFSET;
return ExecutionStatus::EXCEPTION;
}
using PauseOnThrowMode = facebook::hermes::debugger::PauseOnThrowMode;
auto mode = runtime->debugger_.getPauseOnThrowMode();
if (mode != PauseOnThrowMode::None) {
if (!runtime->debugger_.isDebugging()) {
// Determine whether the PauseOnThrowMode requires us to stop here.
bool caught =
runtime->debugger_
.findCatchTarget(InterpreterState(curCodeBlock, CUROFFSET))
.hasValue();
bool shouldStop = mode == PauseOnThrowMode::All ||
(mode == PauseOnThrowMode::Uncaught && !caught);
if (shouldStop) {
// When runDebugger is invoked after an exception,
// stepping should never happen internally.
// Any step is a step to an exception handler, which we do
// directly here in the interpreter.
// Thus, the result state should be the same as the input state.
InterpreterState tmpState{curCodeBlock, (uint32_t)CUROFFSET};
CAPTURE_IP_ASSIGN(
ExecutionStatus resultStatus,
runtime->debugger_.runDebugger(
Debugger::RunReason::Exception, tmpState));
(void)resultStatus;
assert(
tmpState == InterpreterState(curCodeBlock, CUROFFSET) &&
"not allowed to step internally in a pauseOnThrow");
gcScope.flushToSmallCount(KEEP_HANDLES);
}
}
}
#endif
int32_t handlerOffset = 0;
// If the exception is not catchable, skip found catch blocks.
while (((handlerOffset = curCodeBlock->findCatchTargetOffset(CUROFFSET)) ==
-1) ||
!catchable) {
PROFILER_EXIT_FUNCTION(curCodeBlock);
#ifdef HERMES_ENABLE_ALLOCATION_LOCATION_TRACES
runtime->popCallStack();
#endif
// Restore the code block and IP.
curCodeBlock = FRAME.getSavedCodeBlock();
ip = FRAME.getSavedIP();
// Pop a stack frame.
frameRegs =
&runtime->restoreStackAndPreviousFrame(FRAME).getFirstLocalRef();
SLOW_DEBUG(
dbgs() << "function exit with exception: restored stackLevel="
<< runtime->getStackLevel() << "\n");
// Are we returning to native code?
if (!curCodeBlock) {
SLOW_DEBUG(
dbgs()
<< "function exit with exception: returning to native code\n");
return ExecutionStatus::EXCEPTION;
}
assert(
isCallType(ip->opCode) &&
"return address is not Call-type instruction");
// Return because of recursive calling structure
#ifdef HERMESVM_PROFILER_EXTERN
return ExecutionStatus::EXCEPTION;
#endif
}
INIT_STATE_FOR_CODEBLOCK(curCodeBlock);
ip = IPADD(handlerOffset - CUROFFSET);
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,958 |
oniguruma | 6eb4aca6a7f2f60f473580576d86686ed6a6ebec | is_allowed_callout_name(OnigEncoding enc, UChar* name, UChar* name_end)
{
UChar* p;
OnigCodePoint c;
if (name >= name_end) return 0;
p = name;
while (p < name_end) {
c = ONIGENC_MBC_TO_CODE(enc, p, name_end);
if (! IS_ALLOWED_CODE_IN_CALLOUT_NAME(c))
return 0;
if (p == name) {
if (c >= '0' && c <= '9') return 0;
}
p += ONIGENC_MBC_ENC_LEN(enc, p);
}
return 1;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,459 |
ImageMagick | e88532bd4418e95b70cbc415fe911d22ab27a5fd | static inline Quantum ScaleCharToQuantum(const unsigned char value)
{
return((Quantum) (72340172838076673.0*value));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,559 |
qemu | 415ab35a441eca767d033a2702223e785b9d5190 | static int ne2000_buffer_full(NE2000State *s)
{
int avail, index, boundary;
index = s->curpag << 8;
boundary = s->boundary << 8;
if (index < boundary)
return 1;
return 0;
}
| 1 | CVE-2016-2841 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 22 |
pango | 490f8979a260c16b1df055eab386345da18a2d54 | pango_get_mirror_char (gunichar ch,
gunichar *mirrored_ch)
{
return g_unichar_get_mirror_char (ch, mirrored_ch);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,945 |
ImageMagick | 824f344ceb823e156ad6e85314d79c087933c2a0 | static MagickBooleanType TIFFGetProfiles(TIFF *tiff,Image *image,
ExceptionInfo *exception)
{
MagickBooleanType
status;
uint32
length = 0;
unsigned char
*profile = (unsigned char *) NULL;
status=MagickTrue;
#if defined(TIFFTAG_ICCPROFILE)
if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
status=ReadProfile(image,"icc",profile,(ssize_t) length,exception);
#endif
#if defined(TIFFTAG_PHOTOSHOP)
if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
status=ReadProfile(image,"8bim",profile,(ssize_t) length,exception);
#endif
#if defined(TIFFTAG_RICHTIFFIPTC)
if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
{
const TIFFField
*field;
if (TIFFIsByteSwapped(tiff) != 0)
TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);
field=TIFFFieldWithTag(tiff,TIFFTAG_RICHTIFFIPTC);
if (TIFFFieldDataType(field) == TIFF_LONG)
status=ReadProfile(image,"iptc",profile,4L*length,exception);
else
status=ReadProfile(image,"iptc",profile,length,exception);
}
#endif
#if defined(TIFFTAG_XMLPACKET)
if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
{
StringInfo
*dng;
status=ReadProfile(image,"xmp",profile,(ssize_t) length,exception);
dng=BlobToStringInfo(profile,length);
if (dng != (StringInfo *) NULL)
{
const char
*target = "dc:format=\"image/dng\"";
if (strstr((char *) GetStringInfoDatum(dng),target) != (char *) NULL)
(void) CopyMagickString(image->magick,"DNG",MagickPathExtent);
dng=DestroyStringInfo(dng);
}
}
#endif
if ((TIFFGetField(tiff,34118,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
status=ReadProfile(image,"tiff:34118",profile,(ssize_t) length,
exception);
if ((TIFFGetField(tiff,37724,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
status=ReadProfile(image,"tiff:37724",profile,(ssize_t) length,exception);
return(status);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,150 |
server | 0b5a5258abbeaf8a0c3a18c7e753699787fdf46e | virtual Object_creation_ctx *create_backup_ctx(THD *thd) const
{
/*
We can avoid usual backup/restore employed in stored programs since we
know that this is a top level statement and the worker thread is
allocated exclusively to execute this event.
*/
return NULL;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,977 |
tcpdump | 4601c685e7fd19c3724d5e499c69b8d3ec49933e | pgm_print(netdissect_options *ndo,
register const u_char *bp, register u_int length,
register const u_char *bp2)
{
register const struct pgm_header *pgm;
register const struct ip *ip;
register char ch;
uint16_t sport, dport;
u_int nla_afnum;
char nla_buf[INET6_ADDRSTRLEN];
register const struct ip6_hdr *ip6;
uint8_t opt_type, opt_len;
uint32_t seq, opts_len, len, offset;
pgm = (const struct pgm_header *)bp;
ip = (const struct ip *)bp2;
if (IP_V(ip) == 6)
ip6 = (const struct ip6_hdr *)bp2;
else
ip6 = NULL;
ch = '\0';
if (!ND_TTEST(pgm->pgm_dport)) {
if (ip6) {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ip6addr_string(ndo, &ip6->ip6_src),
ip6addr_string(ndo, &ip6->ip6_dst)));
return;
} else {
ND_PRINT((ndo, "%s > %s: [|pgm]",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
return;
}
}
sport = EXTRACT_16BITS(&pgm->pgm_sport);
dport = EXTRACT_16BITS(&pgm->pgm_dport);
if (ip6) {
if (ip6->ip6_nxt == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ip6addr_string(ndo, &ip6->ip6_src),
tcpport_string(ndo, sport),
ip6addr_string(ndo, &ip6->ip6_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
} else {
if (ip->ip_p == IPPROTO_PGM) {
ND_PRINT((ndo, "%s.%s > %s.%s: ",
ipaddr_string(ndo, &ip->ip_src),
tcpport_string(ndo, sport),
ipaddr_string(ndo, &ip->ip_dst),
tcpport_string(ndo, dport)));
} else {
ND_PRINT((ndo, "%s > %s: ",
tcpport_string(ndo, sport), tcpport_string(ndo, dport)));
}
}
ND_TCHECK(*pgm);
ND_PRINT((ndo, "PGM, length %u", EXTRACT_16BITS(&pgm->pgm_length)));
if (!ndo->ndo_vflag)
return;
ND_PRINT((ndo, " 0x%02x%02x%02x%02x%02x%02x ",
pgm->pgm_gsid[0],
pgm->pgm_gsid[1],
pgm->pgm_gsid[2],
pgm->pgm_gsid[3],
pgm->pgm_gsid[4],
pgm->pgm_gsid[5]));
switch (pgm->pgm_type) {
case PGM_SPM: {
const struct pgm_spm *spm;
spm = (const struct pgm_spm *)(pgm + 1);
ND_TCHECK(*spm);
bp = (const u_char *) (spm + 1);
switch (EXTRACT_16BITS(&spm->pgms_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, "SPM seq %u trail %u lead %u nla %s",
EXTRACT_32BITS(&spm->pgms_seq),
EXTRACT_32BITS(&spm->pgms_trailseq),
EXTRACT_32BITS(&spm->pgms_leadseq),
nla_buf));
break;
}
case PGM_POLL: {
const struct pgm_poll *poll_msg;
poll_msg = (const struct pgm_poll *)(pgm + 1);
ND_TCHECK(*poll_msg);
ND_PRINT((ndo, "POLL seq %u round %u",
EXTRACT_32BITS(&poll_msg->pgmp_seq),
EXTRACT_16BITS(&poll_msg->pgmp_round)));
bp = (const u_char *) (poll_msg + 1);
break;
}
case PGM_POLR: {
const struct pgm_polr *polr;
uint32_t ivl, rnd, mask;
polr = (const struct pgm_polr *)(pgm + 1);
ND_TCHECK(*polr);
bp = (const u_char *) (polr + 1);
switch (EXTRACT_16BITS(&polr->pgmp_nla_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ivl = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
rnd = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_TCHECK2(*bp, sizeof(uint32_t));
mask = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, "POLR seq %u round %u nla %s ivl %u rnd 0x%08x "
"mask 0x%08x", EXTRACT_32BITS(&polr->pgmp_seq),
EXTRACT_16BITS(&polr->pgmp_round), nla_buf, ivl, rnd, mask));
break;
}
case PGM_ODATA: {
const struct pgm_data *odata;
odata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*odata);
ND_PRINT((ndo, "ODATA trail %u seq %u",
EXTRACT_32BITS(&odata->pgmd_trailseq),
EXTRACT_32BITS(&odata->pgmd_seq)));
bp = (const u_char *) (odata + 1);
break;
}
case PGM_RDATA: {
const struct pgm_data *rdata;
rdata = (const struct pgm_data *)(pgm + 1);
ND_TCHECK(*rdata);
ND_PRINT((ndo, "RDATA trail %u seq %u",
EXTRACT_32BITS(&rdata->pgmd_trailseq),
EXTRACT_32BITS(&rdata->pgmd_seq)));
bp = (const u_char *) (rdata + 1);
break;
}
case PGM_NAK:
case PGM_NULLNAK:
case PGM_NCF: {
const struct pgm_nak *nak;
char source_buf[INET6_ADDRSTRLEN], group_buf[INET6_ADDRSTRLEN];
nak = (const struct pgm_nak *)(pgm + 1);
ND_TCHECK(*nak);
bp = (const u_char *) (nak + 1);
/*
* Skip past the source, saving info along the way
* and stopping if we don't have enough.
*/
switch (EXTRACT_16BITS(&nak->pgmn_source_afi)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, source_buf, sizeof(source_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Skip past the group, saving info along the way
* and stopping if we don't have enough.
*/
bp += (2 * sizeof(uint16_t));
switch (EXTRACT_16BITS(bp)) {
case AFNUM_INET:
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in_addr);
break;
case AFNUM_INET6:
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, group_buf, sizeof(group_buf));
bp += sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
/*
* Options decoding can go here.
*/
switch (pgm->pgm_type) {
case PGM_NAK:
ND_PRINT((ndo, "NAK "));
break;
case PGM_NULLNAK:
ND_PRINT((ndo, "NNAK "));
break;
case PGM_NCF:
ND_PRINT((ndo, "NCF "));
break;
default:
break;
}
ND_PRINT((ndo, "(%s -> %s), seq %u",
source_buf, group_buf, EXTRACT_32BITS(&nak->pgmn_seq)));
break;
}
case PGM_ACK: {
const struct pgm_ack *ack;
ack = (const struct pgm_ack *)(pgm + 1);
ND_TCHECK(*ack);
ND_PRINT((ndo, "ACK seq %u",
EXTRACT_32BITS(&ack->pgma_rx_max_seq)));
bp = (const u_char *) (ack + 1);
break;
}
case PGM_SPMR:
ND_PRINT((ndo, "SPMR"));
break;
default:
ND_PRINT((ndo, "UNKNOWN type 0x%02x", pgm->pgm_type));
break;
}
if (pgm->pgm_options & PGM_OPT_BIT_PRESENT) {
/*
* make sure there's enough for the first option header
*/
if (!ND_TTEST2(*bp, PGM_MIN_OPT_LEN)) {
ND_PRINT((ndo, "[|OPT]"));
return;
}
/*
* That option header MUST be an OPT_LENGTH option
* (see the first paragraph of section 9.1 in RFC 3208).
*/
opt_type = *bp++;
if ((opt_type & PGM_OPT_MASK) != PGM_OPT_LENGTH) {
ND_PRINT((ndo, "[First option bad, should be PGM_OPT_LENGTH, is %u]", opt_type & PGM_OPT_MASK));
return;
}
opt_len = *bp++;
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
opts_len = EXTRACT_16BITS(bp);
if (opts_len < 4) {
ND_PRINT((ndo, "[Bad total option length %u < 4]", opts_len));
return;
}
bp += sizeof(uint16_t);
ND_PRINT((ndo, " OPTS LEN %d", opts_len));
opts_len -= 4;
while (opts_len) {
if (opts_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
if (!ND_TTEST2(*bp, 2)) {
ND_PRINT((ndo, " [|OPT]"));
return;
}
opt_type = *bp++;
opt_len = *bp++;
if (opt_len < PGM_MIN_OPT_LEN) {
ND_PRINT((ndo, "[Bad option, length %u < %u]", opt_len,
PGM_MIN_OPT_LEN));
break;
}
if (opts_len < opt_len) {
ND_PRINT((ndo, "[Total option length leaves no room for final option]"));
return;
}
if (!ND_TTEST2(*bp, opt_len - 2)) {
ND_PRINT((ndo, " [|OPT]"));
return;
}
switch (opt_type & PGM_OPT_MASK) {
case PGM_OPT_LENGTH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len));
return;
}
ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
opts_len -= 4;
break;
case PGM_OPT_FRAGMENT:
if (opt_len != 16) {
ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != 16]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len));
opts_len -= 16;
break;
case PGM_OPT_NAK_LIST:
bp += 2;
opt_len -= sizeof(uint32_t); /* option header */
ND_PRINT((ndo, " NAK LIST"));
while (opt_len) {
if (opt_len < sizeof(uint32_t)) {
ND_PRINT((ndo, "[Option length not a multiple of 4]"));
return;
}
ND_TCHECK2(*bp, sizeof(uint32_t));
ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp)));
bp += sizeof(uint32_t);
opt_len -= sizeof(uint32_t);
opts_len -= sizeof(uint32_t);
}
break;
case PGM_OPT_JOIN:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " JOIN %u", seq));
opts_len -= 8;
break;
case PGM_OPT_NAK_BO_IVL:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_NAK_BO_RNG:
if (opt_len != 12) {
ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != 12]", opt_len));
return;
}
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq));
opts_len -= 12;
break;
case PGM_OPT_REDIRECT:
bp += 2;
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 4 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 4 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 4 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 4 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " REDIRECT %s", nla_buf));
break;
case PGM_OPT_PARITY_PRM:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY MAXTGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_PARITY_GRP:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != 8]", opt_len));
return;
}
bp += 2;
seq = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY GROUP %u", seq));
opts_len -= 8;
break;
case PGM_OPT_CURR_TGSIZE:
if (opt_len != 8) {
ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != 8]", opt_len));
return;
}
bp += 2;
len = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
ND_PRINT((ndo, " PARITY ATGS %u", len));
opts_len -= 8;
break;
case PGM_OPT_NBR_UNREACH:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " NBR_UNREACH"));
opts_len -= 4;
break;
case PGM_OPT_PATH_NLA:
ND_PRINT((ndo, " PATH_NLA [%d]", opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_SYN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " SYN"));
opts_len -= 4;
break;
case PGM_OPT_FIN:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " FIN"));
opts_len -= 4;
break;
case PGM_OPT_RST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_RST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " RST"));
opts_len -= 4;
break;
case PGM_OPT_CR:
ND_PRINT((ndo, " CR"));
bp += opt_len;
opts_len -= opt_len;
break;
case PGM_OPT_CRQST:
if (opt_len != 4) {
ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != 4]", opt_len));
return;
}
bp += 2;
ND_PRINT((ndo, " CRQST"));
opts_len -= 4;
break;
case PGM_OPT_PGMCC_DATA:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC DATA %u %s", offset, nla_buf));
break;
case PGM_OPT_PGMCC_FEEDBACK:
bp += 2;
offset = EXTRACT_32BITS(bp);
bp += sizeof(uint32_t);
nla_afnum = EXTRACT_16BITS(bp);
bp += (2 * sizeof(uint16_t));
switch (nla_afnum) {
case AFNUM_INET:
if (opt_len != 12 + sizeof(struct in_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in_addr));
addrtostr(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in_addr);
opts_len -= 12 + sizeof(struct in_addr);
break;
case AFNUM_INET6:
if (opt_len != 12 + sizeof(struct in6_addr)) {
ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len));
return;
}
ND_TCHECK2(*bp, sizeof(struct in6_addr));
addrtostr6(bp, nla_buf, sizeof(nla_buf));
bp += sizeof(struct in6_addr);
opts_len -= 12 + sizeof(struct in6_addr);
break;
default:
goto trunc;
break;
}
ND_PRINT((ndo, " PGMCC FEEDBACK %u %s", offset, nla_buf));
break;
default:
ND_PRINT((ndo, " OPT_%02X [%d] ", opt_type, opt_len));
bp += opt_len;
opts_len -= opt_len;
break;
}
if (opt_type & PGM_OPT_END)
break;
}
}
ND_PRINT((ndo, " [%u]", length));
if (ndo->ndo_packettype == PT_PGM_ZMTP1 &&
(pgm->pgm_type == PGM_ODATA || pgm->pgm_type == PGM_RDATA))
zmtp1_print_datagram(ndo, bp, EXTRACT_16BITS(&pgm->pgm_length));
return;
trunc:
ND_PRINT((ndo, "[|pgm]"));
if (ch != '\0')
ND_PRINT((ndo, ">"));
}
| 1 | CVE-2017-13019 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 2,059 |
mongo | 5285225e71c5c0652520ef99d0ae4ca24655f72f | TEST(BSONValidateFast, StringHasSomething) {
BufBuilder bb;
BSONObjBuilder ob(bb);
bb.appendChar(String);
bb.appendStr("x", /*withNUL*/true);
bb.appendNum(0);
const BSONObj x = ob.done();
ASSERT_EQUALS(5 // overhead
+ 1 // type
+ 2 // name
+ 4 // size
, x.objsize());
ASSERT_NOT_OK(validateBSON(x.objdata(), x.objsize()));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,159 |
swtpm | 634b6294000fb785b9f12e13b852c18a0888b01e | int pidfile_set_fd(int newpidfilefd)
{
pidfilefd = newpidfilefd;
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,868 |
Chrome | 74fce5949bdf05a92c2bc0bd98e6e3e977c55376 | void MediaControlTimelineElement::defaultEventHandler(Event* event) {
if (event->isMouseEvent() &&
toMouseEvent(event)->button() !=
static_cast<short>(WebPointerProperties::Button::Left))
return;
if (!isConnected() || !document().isActive())
return;
if (event->type() == EventTypeNames::mousedown) {
Platform::current()->recordAction(
UserMetricsAction("Media.Controls.ScrubbingBegin"));
mediaControls().beginScrubbing();
}
if (event->type() == EventTypeNames::mouseup) {
Platform::current()->recordAction(
UserMetricsAction("Media.Controls.ScrubbingEnd"));
mediaControls().endScrubbing();
}
MediaControlInputElement::defaultEventHandler(event);
if (event->type() == EventTypeNames::mouseover ||
event->type() == EventTypeNames::mouseout ||
event->type() == EventTypeNames::mousemove)
return;
double time = value().toDouble();
if (event->type() == EventTypeNames::input) {
if (mediaElement().seekable()->contain(time))
mediaElement().setCurrentTime(time);
}
LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject()));
if (!slider.isNull() && slider.inDragMode())
mediaControls().updateCurrentTimeDisplay();
}
| 1 | CVE-2015-1271 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 5,495 |
net | 5d2be1422e02ccd697ccfcd45c85b4a26e6178e2 | static int tipc_nl_compat_media_dump(struct tipc_nl_compat_msg *msg,
struct nlattr **attrs)
{
struct nlattr *media[TIPC_NLA_MEDIA_MAX + 1];
int err;
if (!attrs[TIPC_NLA_MEDIA])
return -EINVAL;
err = nla_parse_nested(media, TIPC_NLA_MEDIA_MAX, attrs[TIPC_NLA_MEDIA],
NULL);
if (err)
return err;
return tipc_add_tlv(msg->rep, TIPC_TLV_MEDIA_NAME,
nla_data(media[TIPC_NLA_MEDIA_NAME]),
nla_len(media[TIPC_NLA_MEDIA_NAME]));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,100 |
tensorflow | a1b11d2fdd1e51bfe18bb1ede804f60abfa92da6 | void ScalarMultiply<quint8, qint32>(OpKernelContext* context,
const quint8* full_input,
int32 full_input_offset, int64 num_elements,
quint8 scalar_input,
int32 scalar_input_offset, qint32* output) {
const int16 scalar_minus_offset =
static_cast<int16>(scalar_input) - scalar_input_offset;
const int16x4_t scalar_minus_offset_16x4 = vmov_n_s16(scalar_minus_offset);
const uint8x8_t full_input_offset_8x8 = vmov_n_u8(full_input_offset);
// Go through the results in 16-element chunks for NEON acceleration.
int i;
for (i = 0; i < (num_elements - 15); i += 16) {
// Load the tensor inputs.
const uint8* full_input_ptr = &(full_input->value) + i;
const uint8x16_t full_input_8x16 = vld1q_u8(full_input_ptr);
// Break into two sets of vectors so we can do further calculations
// easily.
const uint8x8_t full_input_high_8x8 = vget_high_u8(full_input_8x16);
const uint8x8_t full_input_low_8x8 = vget_low_u8(full_input_8x16);
// Subtract off the offset value to get 16-bit results.
const int16x8_t full_input_minus_offset_high_16x8 = vreinterpretq_s16_u16(
vsubl_u8(full_input_high_8x8, full_input_offset_8x8));
const int16x8_t full_input_minus_offset_low_16x8 = vreinterpretq_s16_u16(
vsubl_u8(full_input_low_8x8, full_input_offset_8x8));
// We have to work with 4-wide vectors, so extract them.
const int16x4_t x_high_high_16x4 =
vget_high_s16(full_input_minus_offset_high_16x8);
const int16x4_t x_high_low_16x4 =
vget_low_s16(full_input_minus_offset_high_16x8);
const int16x4_t x_low_high_16x4 =
vget_high_s16(full_input_minus_offset_low_16x8);
const int16x4_t x_low_low_16x4 =
vget_low_s16(full_input_minus_offset_low_16x8);
// Perform the multiplication.
const int32x4_t z_high_high_32x4 =
vmull_s16(x_high_high_16x4, scalar_minus_offset_16x4);
const int32x4_t z_high_low_32x4 =
vmull_s16(x_high_low_16x4, scalar_minus_offset_16x4);
const int32x4_t z_low_high_32x4 =
vmull_s16(x_low_high_16x4, scalar_minus_offset_16x4);
const int32x4_t z_low_low_32x4 =
vmull_s16(x_low_low_16x4, scalar_minus_offset_16x4);
// Write out the results.
int32* output_ptr = &(output->value) + i;
vst1q_s32(output_ptr + 0, z_low_low_32x4);
vst1q_s32(output_ptr + 4, z_low_high_32x4);
vst1q_s32(output_ptr + 8, z_high_low_32x4);
vst1q_s32(output_ptr + 12, z_high_high_32x4);
}
// Finish up any remaining elements that weren't a multiple of 16.
for (; i < num_elements; ++i) {
output[i] = (static_cast<int32>(full_input[i]) - full_input_offset) *
scalar_minus_offset;
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,058 |
Chrome | c4a4dfb26615b5ef5e9dcc730ef43f70ce9202e2 | void RenderThreadImpl::Shutdown() {
FOR_EACH_OBSERVER(
RenderProcessObserver, observers_, OnRenderProcessShutdown());
ChildThread::Shutdown();
if (memory_observer_) {
message_loop()->RemoveTaskObserver(memory_observer_.get());
memory_observer_.reset();
}
if (webkit_platform_support_) {
webkit_platform_support_->web_database_observer_impl()->
WaitForAllDatabasesToClose();
}
if (devtools_agent_message_filter_.get()) {
RemoveFilter(devtools_agent_message_filter_.get());
devtools_agent_message_filter_ = NULL;
}
RemoveFilter(audio_input_message_filter_.get());
audio_input_message_filter_ = NULL;
RemoveFilter(audio_message_filter_.get());
audio_message_filter_ = NULL;
#if defined(ENABLE_WEBRTC)
RTCPeerConnectionHandler::DestructAllHandlers();
peer_connection_factory_.reset();
#endif
RemoveFilter(vc_manager_->video_capture_message_filter());
vc_manager_.reset();
RemoveFilter(db_message_filter_.get());
db_message_filter_ = NULL;
if (file_thread_)
file_thread_->Stop();
if (compositor_output_surface_filter_.get()) {
RemoveFilter(compositor_output_surface_filter_.get());
compositor_output_surface_filter_ = NULL;
}
media_thread_.reset();
compositor_thread_.reset();
input_handler_manager_.reset();
if (input_event_filter_.get()) {
RemoveFilter(input_event_filter_.get());
input_event_filter_ = NULL;
}
embedded_worker_dispatcher_.reset();
main_thread_indexed_db_dispatcher_.reset();
if (webkit_platform_support_)
blink::shutdown();
lazy_tls.Pointer()->Set(NULL);
#if defined(OS_WIN)
NPChannelBase::CleanupChannels();
#endif
}
| 1 | CVE-2013-2906 | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The product contains a concurrent code sequence that requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence operating concurrently. | Phase: Architecture and Design
In languages that support it, use synchronization primitives. Only wrap these around critical code to minimize the impact on performance.
Phase: Architecture and Design
Use thread-safe capabilities such as the data access abstraction in Spring.
Phase: Architecture and Design
Minimize the usage of shared resources in order to remove as much complexity as possible from the control flow and to reduce the likelihood of unexpected conditions occurring.
Additionally, this will minimize the amount of synchronization necessary and may even help to reduce the likelihood of a denial of service where an attacker may be able to repeatedly trigger a critical section (CWE-400).
Phase: Implementation
When using multithreading and operating on shared variables, only use thread-safe functions.
Phase: Implementation
Use atomic operations on shared variables. Be wary of innocent-looking constructs such as "x++". This may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read, followed by a computation, followed by a write.
Phase: Implementation
Use a mutex if available, but be sure to avoid related weaknesses such as CWE-412.
Phase: Implementation
Avoid double-checked locking (CWE-609) and other implementation errors that arise when trying to avoid the overhead of synchronization.
Phase: Implementation
Disable interrupts or signals over critical parts of the code, but also make sure that the code does not go into a large or infinite loop.
Phase: Implementation
Use the volatile type modifier for critical variables to avoid unexpected compiler optimization or reordering. This does not necessarily solve the synchronization problem, but it can help.
Phases: Architecture and Design; Operation
Strategy: Environment Hardening
Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations | 3,838 |
linux | 6ca03f90527e499dd5e32d6522909e2ad390896b | int vt_do_kdgkb_ioctl(int cmd, struct kbsentry __user *user_kdgkb, int perm)
{
struct kbsentry *kbs;
char *p;
u_char *q;
u_char __user *up;
int sz, fnw_sz;
int delta;
char *first_free, *fj, *fnw;
int i, j, k;
int ret;
unsigned long flags;
if (!capable(CAP_SYS_TTY_CONFIG))
perm = 0;
kbs = kmalloc(sizeof(*kbs), GFP_KERNEL);
if (!kbs) {
ret = -ENOMEM;
goto reterr;
}
/* we mostly copy too much here (512bytes), but who cares ;) */
if (copy_from_user(kbs, user_kdgkb, sizeof(struct kbsentry))) {
ret = -EFAULT;
goto reterr;
}
kbs->kb_string[sizeof(kbs->kb_string)-1] = '\0';
i = array_index_nospec(kbs->kb_func, MAX_NR_FUNC);
switch (cmd) {
case KDGKBSENT:
sz = sizeof(kbs->kb_string) - 1; /* sz should have been
a struct member */
up = user_kdgkb->kb_string;
p = func_table[i];
if(p)
for ( ; *p && sz; p++, sz--)
if (put_user(*p, up++)) {
ret = -EFAULT;
goto reterr;
}
if (put_user('\0', up)) {
ret = -EFAULT;
goto reterr;
}
kfree(kbs);
return ((p && *p) ? -EOVERFLOW : 0);
case KDSKBSENT:
if (!perm) {
ret = -EPERM;
goto reterr;
}
fnw = NULL;
fnw_sz = 0;
/* race aginst other writers */
again:
spin_lock_irqsave(&func_buf_lock, flags);
q = func_table[i];
/* fj pointer to next entry after 'q' */
first_free = funcbufptr + (funcbufsize - funcbufleft);
for (j = i+1; j < MAX_NR_FUNC && !func_table[j]; j++)
;
if (j < MAX_NR_FUNC)
fj = func_table[j];
else
fj = first_free;
/* buffer usage increase by new entry */
delta = (q ? -strlen(q) : 1) + strlen(kbs->kb_string);
if (delta <= funcbufleft) { /* it fits in current buf */
if (j < MAX_NR_FUNC) {
/* make enough space for new entry at 'fj' */
memmove(fj + delta, fj, first_free - fj);
for (k = j; k < MAX_NR_FUNC; k++)
if (func_table[k])
func_table[k] += delta;
}
if (!q)
func_table[i] = fj;
funcbufleft -= delta;
} else { /* allocate a larger buffer */
sz = 256;
while (sz < funcbufsize - funcbufleft + delta)
sz <<= 1;
if (fnw_sz != sz) {
spin_unlock_irqrestore(&func_buf_lock, flags);
kfree(fnw);
fnw = kmalloc(sz, GFP_KERNEL);
fnw_sz = sz;
if (!fnw) {
ret = -ENOMEM;
goto reterr;
}
goto again;
}
if (!q)
func_table[i] = fj;
/* copy data before insertion point to new location */
if (fj > funcbufptr)
memmove(fnw, funcbufptr, fj - funcbufptr);
for (k = 0; k < j; k++)
if (func_table[k])
func_table[k] = fnw + (func_table[k] - funcbufptr);
/* copy data after insertion point to new location */
if (first_free > fj) {
memmove(fnw + (fj - funcbufptr) + delta, fj, first_free - fj);
for (k = j; k < MAX_NR_FUNC; k++)
if (func_table[k])
func_table[k] = fnw + (func_table[k] - funcbufptr) + delta;
}
if (funcbufptr != func_buf)
kfree(funcbufptr);
funcbufptr = fnw;
funcbufleft = funcbufleft - delta + sz - funcbufsize;
funcbufsize = sz;
}
/* finally insert item itself */
strcpy(func_table[i], kbs->kb_string);
spin_unlock_irqrestore(&func_buf_lock, flags);
break;
}
ret = 0;
reterr:
kfree(kbs);
return ret;
} | 1 | CVE-2020-25656 | CWE-416 | Use After Free | The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
Phase: Architecture and Design
Strategy: Language Selection
Choose a language that provides automatic memory management.
Phase: Implementation
Strategy: Attack Surface Reduction
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.
Effectiveness: Defense in Depth
Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution. | 5,916 |
pdfresurrect | 0c4120fffa3dffe97b95c486a120eded82afe8a6 | int pdf_display_creator(const pdf_t *pdf, int xref_idx)
{
int i;
if (!pdf->xrefs[xref_idx].creator)
return 0;
for (i=0; i<pdf->xrefs[xref_idx].n_creator_entries; ++i)
printf("%s: %s\n",
pdf->xrefs[xref_idx].creator[i].key,
pdf->xrefs[xref_idx].creator[i].value);
return (i > 0);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,120 |
bubblewrap | d7fc532c42f0e9bf427923bab85433282b3e5117 | drop_all_caps (void)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (capset (&hdr, data) < 0)
die_with_error ("capset failed");
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,692 |
Android | 640b04121d7cd2cac90e2f7c82b97fce05f074a5 | 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() || portIndex >= NELEM(mNumPortBuffers)) {
return BAD_VALUE;
}
bool copy = mMetadataType[portIndex] == kMetadataBufferTypeInvalid;
BufferMeta *buffer_meta = new BufferMeta(
params, portIndex,
(portIndex == kPortIndexInput) && copy /* copyToOmx */,
(portIndex == kPortIndexOutput) && copy /* copyFromOmx */,
NULL /* data */);
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);
memset(header->pBuffer, 0, header->nAllocLen);
*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;
}
| 1 | CVE-2016-6720 | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. |
Phase: Architecture and Design
Strategy: Separation of Privilege
Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area.
Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges. | 7,377 |
php-src | 7245bff300d3fa8bacbef7897ff080a6f1c23eba?w=1 | zend_function *spl_filesystem_object_get_method_check(zval **object_ptr, char *method, int method_len, const struct _zend_literal *key TSRMLS_DC) /* {{{ */
{
spl_filesystem_object *fsobj = zend_object_store_get_object(*object_ptr TSRMLS_CC);
if (fsobj->u.dir.entry.d_name[0] == '\0' && fsobj->orig_path == NULL) {
method = "_bad_state_ex";
method_len = sizeof("_bad_state_ex") - 1;
key = NULL;
}
return zend_get_std_object_handlers()->get_method(object_ptr, method, method_len, key TSRMLS_CC);
}
/* }}} */
| 1 | CVE-2016-5770 | CWE-190 | Integer Overflow or Wraparound | The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number. | Phase: Requirements
Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol.
Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
If possible, choose a language or compiler that performs automatic bounds checking.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Use libraries or frameworks that make it easier to handle numbers without unexpected consequences.
Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106]
Phase: Implementation
Strategy: Input Validation
Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.
Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values.
Phase: Implementation
Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7]
Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Phase: Implementation
Strategy: Compilation or Build Hardening
Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system. | 864 |
ImageMagick6 | 9e7db22f8c374301db3f968757f0d08070fd4e54 | static MagickBooleanType WriteSGIImage(const ImageInfo *image_info,Image *image)
{
CompressionType
compression;
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
SGIInfo
iris_info;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
imageListLength;
ssize_t
y,
z;
unsigned char
*pixels,
*packets;
/*
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);
if ((image->columns > 65535UL) || (image->rows > 65535UL))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
/*
Initialize SGI raster file header.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
(void) memset(&iris_info,0,sizeof(iris_info));
iris_info.magic=0x01DA;
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
if (image->depth > 8)
compression=NoCompression;
if (compression == NoCompression)
iris_info.storage=(unsigned char) 0x00;
else
iris_info.storage=(unsigned char) 0x01;
iris_info.bytes_per_pixel=(unsigned char) (image->depth > 8 ? 2 : 1);
iris_info.dimension=3;
iris_info.columns=(unsigned short) image->columns;
iris_info.rows=(unsigned short) image->rows;
if (image->matte != MagickFalse)
iris_info.depth=4;
else
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
iris_info.dimension=2;
iris_info.depth=1;
}
else
iris_info.depth=3;
}
iris_info.minimum_value=0;
iris_info.maximum_value=(size_t) (image->depth <= 8 ?
1UL*ScaleQuantumToChar(QuantumRange) :
1UL*ScaleQuantumToShort(QuantumRange));
/*
Write SGI header.
*/
(void) WriteBlobMSBShort(image,iris_info.magic);
(void) WriteBlobByte(image,iris_info.storage);
(void) WriteBlobByte(image,iris_info.bytes_per_pixel);
(void) WriteBlobMSBShort(image,iris_info.dimension);
(void) WriteBlobMSBShort(image,iris_info.columns);
(void) WriteBlobMSBShort(image,iris_info.rows);
(void) WriteBlobMSBShort(image,iris_info.depth);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.minimum_value);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.maximum_value);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.sans);
value=GetImageProperty(image,"label");
if (value != (const char *) NULL)
(void) CopyMagickString(iris_info.name,value,sizeof(iris_info.name));
(void) WriteBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.pixel_format);
(void) WriteBlob(image,sizeof(iris_info.filler),iris_info.filler);
/*
Allocate SGI pixels.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((4*iris_info.bytes_per_pixel*number_pixels) !=
((MagickSizeType) (size_t) (4*iris_info.bytes_per_pixel*number_pixels)))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory((size_t) number_pixels,4*
iris_info.bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Convert image pixels to uncompressed SGI pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
if (image->depth <= 8)
for (x=0; x < (ssize_t) image->columns; x++)
{
register unsigned char
*q;
q=(unsigned char *) pixels;
q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x;
*q++=ScaleQuantumToChar(GetPixelRed(p));
*q++=ScaleQuantumToChar(GetPixelGreen(p));
*q++=ScaleQuantumToChar(GetPixelBlue(p));
*q++=ScaleQuantumToChar(GetPixelAlpha(p));
p++;
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
register unsigned short
*q;
q=(unsigned short *) pixels;
q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x;
*q++=ScaleQuantumToShort(GetPixelRed(p));
*q++=ScaleQuantumToShort(GetPixelGreen(p));
*q++=ScaleQuantumToShort(GetPixelBlue(p));
*q++=ScaleQuantumToShort(GetPixelAlpha(p));
p++;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
switch (compression)
{
case NoCompression:
{
/*
Write uncompressed SGI pixels.
*/
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (image->depth <= 8)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
register unsigned char
*q;
q=(unsigned char *) pixels;
q+=y*(4*iris_info.columns)+4*x+z;
(void) WriteBlobByte(image,*q);
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
register unsigned short
*q;
q=(unsigned short *) pixels;
q+=y*(4*iris_info.columns)+4*x+z;
(void) WriteBlobMSBShort(image,*q);
}
}
}
break;
}
default:
{
MemoryInfo
*packet_info;
size_t
length,
number_packets,
*runlength;
ssize_t
offset,
*offsets;
/*
Convert SGI uncompressed pixels.
*/
offsets=(ssize_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((2*(size_t) iris_info.columns+10)*
image->rows,4*sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets != (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength != (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info != (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
offset=512+4*2*((ssize_t) iris_info.rows*iris_info.depth);
number_packets=0;
q=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
length=SGIEncode(q+z,(size_t) iris_info.columns,packets+
number_packets);
number_packets+=length;
offsets[y+z*iris_info.rows]=offset;
runlength[y+z*iris_info.rows]=(size_t) length;
offset+=(ssize_t) length;
}
q+=(iris_info.columns*4);
}
/*
Write out line start and length tables and runlength-encoded pixels.
*/
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
(void) WriteBlobMSBLong(image,(unsigned int) offsets[i]);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
(void) WriteBlobMSBLong(image,(unsigned int) runlength[i]);
(void) WriteBlob(image,number_packets,packets);
/*
Relinquish resources.
*/
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
runlength=(size_t *) RelinquishMagickMemory(runlength);
packet_info=RelinquishVirtualMemory(packet_info);
break;
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
} | 1 | CVE-2019-19948 | CWE-787 | Out-of-bounds Write | The product writes data past the end, or before the beginning, of the intended buffer. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333].
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 4,871 |
libgcrypt | d482948ac41768c36c5352a513fca8c50d2da4db | test_keys ( ELG_secret_key *sk, unsigned int nbits, int nodie )
{
ELG_public_key pk;
gcry_mpi_t test = mpi_new ( 0 );
gcry_mpi_t out1_a = mpi_new ( nbits );
gcry_mpi_t out1_b = mpi_new ( nbits );
gcry_mpi_t out2 = mpi_new ( nbits );
int failed = 0;
pk.p = sk->p;
pk.g = sk->g;
pk.y = sk->y;
_gcry_mpi_randomize ( test, nbits, GCRY_WEAK_RANDOM );
do_encrypt ( out1_a, out1_b, test, &pk );
decrypt ( out2, out1_a, out1_b, sk );
if ( mpi_cmp( test, out2 ) )
failed |= 1;
sign ( out1_a, out1_b, test, sk );
if ( !verify( out1_a, out1_b, test, &pk ) )
failed |= 2;
_gcry_mpi_release ( test );
_gcry_mpi_release ( out1_a );
_gcry_mpi_release ( out1_b );
_gcry_mpi_release ( out2 );
if (failed && !nodie)
log_fatal ("Elgamal test key for %s %s failed\n",
(failed & 1)? "encrypt+decrypt":"",
(failed & 2)? "sign+verify":"");
if (failed && DBG_CIPHER)
log_debug ("Elgamal test key for %s %s failed\n",
(failed & 1)? "encrypt+decrypt":"",
(failed & 2)? "sign+verify":"");
return failed;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,424 |
WavPack | 36a24c7881427d2e1e4dc1cef58f19eee0d13aec | int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int64_t infilesize, total_samples;
DFFFileHeader dff_file_header;
DFFChunkHeader dff_chunk_header;
uint32_t bcount;
infilesize = DoGetFileSize (infile);
memcpy (&dff_file_header, fourcc, 4);
if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) ||
bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
#if 1 // this might be a little too picky...
WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat);
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) &&
dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) {
error_line ("%s is not a valid .DFF file (by total size)!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (debug_logging_mode)
error_line ("file header indicated length = %lld", dff_file_header.ckDataSize);
#endif
// loop through all elements of the DSDIFF header
// (until the data chuck) and copy them to the output file
while (1) {
if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) ||
bcount != sizeof (DFFChunkHeader)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (debug_logging_mode)
error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize);
if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) {
uint32_t version;
if (dff_chunk_header.ckDataSize != sizeof (version) ||
!DoReadFile (infile, &version, sizeof (version), &bcount) ||
bcount != sizeof (version)) {
error_line ("%s is not a valid .DFF file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &version, sizeof (version))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackBigEndianToNative (&version, "L");
if (debug_logging_mode)
error_line ("dsdiff file version = 0x%08x", version);
}
else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) {
char *prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) ||
bcount != dff_chunk_header.ckDataSize) {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
if (!strncmp (prop_chunk, "SND ", 4)) {
char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize;
uint16_t numChannels, chansSpecified, chanMask = 0;
uint32_t sampleRate;
while (eptr - cptr >= sizeof (dff_chunk_header)) {
memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header));
cptr += sizeof (dff_chunk_header);
WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat);
if (eptr - cptr >= dff_chunk_header.ckDataSize) {
if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) {
memcpy (&sampleRate, cptr, sizeof (sampleRate));
WavpackBigEndianToNative (&sampleRate, "L");
cptr += dff_chunk_header.ckDataSize;
if (debug_logging_mode)
error_line ("got sample rate of %u Hz", sampleRate);
}
else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) {
memcpy (&numChannels, cptr, sizeof (numChannels));
WavpackBigEndianToNative (&numChannels, "S");
cptr += sizeof (numChannels);
chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4;
while (chansSpecified--) {
if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4))
chanMask |= 0x1;
else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4))
chanMask |= 0x2;
else if (!strncmp (cptr, "LS ", 4))
chanMask |= 0x10;
else if (!strncmp (cptr, "RS ", 4))
chanMask |= 0x20;
else if (!strncmp (cptr, "C ", 4))
chanMask |= 0x4;
else if (!strncmp (cptr, "LFE ", 4))
chanMask |= 0x8;
else
if (debug_logging_mode)
error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]);
cptr += 4;
}
if (debug_logging_mode)
error_line ("%d channels, mask = 0x%08x", numChannels, chanMask);
}
else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) {
if (strncmp (cptr, "DSD ", 4)) {
error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!",
cptr [0], cptr [1], cptr [2], cptr [3]);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
cptr += dff_chunk_header.ckDataSize;
}
else {
if (debug_logging_mode)
error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0],
dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
cptr += dff_chunk_header.ckDataSize;
}
}
else {
error_line ("%s is not a valid .DFF file!", infilename);
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
}
if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this DSDIFF file already has channel order information!");
free (prop_chunk);
return WAVPACK_SOFT_ERROR;
}
else if (chanMask)
config->channel_mask = chanMask;
config->bits_per_sample = 8;
config->bytes_per_sample = 1;
config->num_channels = numChannels;
config->sample_rate = sampleRate / 8;
config->qmode |= QMODE_DSD_MSB_FIRST;
}
else if (debug_logging_mode)
error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes",
prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize);
free (prop_chunk);
}
else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) {
total_samples = dff_chunk_header.ckDataSize / config->num_channels;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1);
char *buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2],
dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (debug_logging_mode)
error_line ("setting configuration with %lld samples", total_samples);
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
} | 1 | CVE-2018-7253 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 8,020 |
Chrome | 153f8457c7867d5c9b627c11b52f5de0671d2fff | bool WebMediaPlayerImpl::DidGetOpaqueResponseFromServiceWorker() const {
if (data_source_)
return data_source_->DidGetOpaqueResponseViaServiceWorker();
return false;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,194 |
libgd | 7a1aac3343af85b4af4df5f8844946eaa27394ab?w=1 | int gdTransformAffineGetImage(gdImagePtr *dst,
const gdImagePtr src,
gdRectPtr src_area,
const double affine[6])
{
int res;
double m[6];
gdRect bbox;
gdRect area_full;
if (src_area == NULL) {
area_full.x = 0;
area_full.y = 0;
area_full.width = gdImageSX(src);
area_full.height = gdImageSY(src);
src_area = &area_full;
}
gdTransformAffineBoundingBox(src_area, affine, &bbox);
*dst = gdImageCreateTrueColor(bbox.width, bbox.height);
if (*dst == NULL) {
return GD_FALSE;
}
(*dst)->saveAlphaFlag = 1;
if (!src->trueColor) {
gdImagePaletteToTrueColor(src);
}
/* Translate to dst origin (0,0) */
gdAffineTranslate(m, -bbox.x, -bbox.y);
gdAffineConcat(m, affine, m);
gdImageAlphaBlending(*dst, 0);
res = gdTransformAffineCopy(*dst,
0,0,
src,
src_area,
m);
if (res != GD_TRUE) {
gdImageDestroy(*dst);
dst = NULL;
return GD_FALSE;
} else {
return GD_TRUE;
}
}
| 1 | CVE-2013-7456 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 6,755 |
linux | 0f4f199443faca715523b0659aa536251d8b978f | void iwl_pcie_ctxt_info_gen3_free(struct iwl_trans *trans)
{
struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
if (!trans_pcie->ctxt_info_gen3)
return;
dma_free_coherent(trans->dev, sizeof(*trans_pcie->ctxt_info_gen3),
trans_pcie->ctxt_info_gen3,
trans_pcie->ctxt_info_dma_addr);
trans_pcie->ctxt_info_dma_addr = 0;
trans_pcie->ctxt_info_gen3 = NULL;
iwl_pcie_ctxt_info_free_fw_img(trans);
dma_free_coherent(trans->dev, sizeof(*trans_pcie->prph_scratch),
trans_pcie->prph_scratch,
trans_pcie->prph_scratch_dma_addr);
trans_pcie->prph_scratch_dma_addr = 0;
trans_pcie->prph_scratch = NULL;
dma_free_coherent(trans->dev, sizeof(*trans_pcie->prph_info),
trans_pcie->prph_info,
trans_pcie->prph_info_dma_addr);
trans_pcie->prph_info_dma_addr = 0;
trans_pcie->prph_info = NULL;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,439 |
linux | 2d6a0e9de03ee658a9adc3bfb2f0ca55dff1e478 | static netdev_tx_t catc_start_xmit(struct sk_buff *skb,
struct net_device *netdev)
{
struct catc *catc = netdev_priv(netdev);
unsigned long flags;
int r = 0;
char *tx_buf;
spin_lock_irqsave(&catc->tx_lock, flags);
catc->tx_ptr = (((catc->tx_ptr - 1) >> 6) + 1) << 6;
tx_buf = catc->tx_buf[catc->tx_idx] + catc->tx_ptr;
if (catc->is_f5u011)
*(__be16 *)tx_buf = cpu_to_be16(skb->len);
else
*(__le16 *)tx_buf = cpu_to_le16(skb->len);
skb_copy_from_linear_data(skb, tx_buf + 2, skb->len);
catc->tx_ptr += skb->len + 2;
if (!test_and_set_bit(TX_RUNNING, &catc->flags)) {
r = catc_tx_run(catc);
if (r < 0)
clear_bit(TX_RUNNING, &catc->flags);
}
if ((catc->is_f5u011 && catc->tx_ptr) ||
(catc->tx_ptr >= ((TX_MAX_BURST - 1) * (PKT_SZ + 2))))
netif_stop_queue(netdev);
spin_unlock_irqrestore(&catc->tx_lock, flags);
if (r >= 0) {
catc->netdev->stats.tx_bytes += skb->len;
catc->netdev->stats.tx_packets++;
}
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,361 |
libsndfile | 708e996c87c5fae77b104ccfeb8f6db784c32074 | header_put_marker (SF_PRIVATE *psf, int x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4)
{ psf->header [psf->headindex++] = (x >> 24) ;
psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = x ;
} ;
} /* header_put_marker */
| 1 | CVE-2017-7586 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 2,764 |
qemu | 3251bdcf1c67427d964517053c3d185b46e618e8 | void ide_dma_cb(void *opaque, int ret)
{
IDEState *s = opaque;
int n;
int64_t sector_num;
bool stay_active = false;
if (ret == -ECANCELED) {
return;
}
if (ret < 0) {
int op = IDE_RETRY_DMA;
if (s->dma_cmd == IDE_DMA_READ)
op |= IDE_RETRY_READ;
else if (s->dma_cmd == IDE_DMA_TRIM)
op |= IDE_RETRY_TRIM;
if (ide_handle_rw_error(s, -ret, op)) {
return;
}
}
n = s->io_buffer_size >> 9;
if (n > s->nsector) {
/* The PRDs were longer than needed for this request. Shorten them so
* we don't get a negative remainder. The Active bit must remain set
* after the request completes. */
n = s->nsector;
stay_active = true;
}
sector_num = ide_get_sector(s);
if (n > 0) {
assert(s->io_buffer_size == s->sg.size);
dma_buf_commit(s, s->io_buffer_size);
sector_num += n;
ide_set_sector(s, sector_num);
s->nsector -= n;
}
/* end of transfer ? */
if (s->nsector == 0) {
s->status = READY_STAT | SEEK_STAT;
ide_set_irq(s->bus);
goto eot;
}
/* launch next transfer */
n = s->nsector;
s->io_buffer_index = 0;
s->io_buffer_size = n * 512;
if (s->bus->dma->ops->prepare_buf(s->bus->dma, ide_cmd_is_read(s)) == 0) {
/* The PRDs were too short. Reset the Active bit, but don't raise an
* interrupt. */
s->status = READY_STAT | SEEK_STAT;
goto eot;
}
printf("ide_dma_cb: sector_num=%" PRId64 " n=%d, cmd_cmd=%d\n",
sector_num, n, s->dma_cmd);
#endif
if ((s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) &&
!ide_sect_range_ok(s, sector_num, n)) {
ide_dma_error(s);
return;
}
switch (s->dma_cmd) {
case IDE_DMA_READ:
s->bus->dma->aiocb = dma_blk_read(s->blk, &s->sg, sector_num,
ide_dma_cb, s);
break;
case IDE_DMA_WRITE:
s->bus->dma->aiocb = dma_blk_write(s->blk, &s->sg, sector_num,
ide_dma_cb, s);
break;
case IDE_DMA_TRIM:
s->bus->dma->aiocb = dma_blk_io(s->blk, &s->sg, sector_num,
ide_issue_trim, ide_dma_cb, s,
DMA_DIRECTION_TO_DEVICE);
break;
}
return;
eot:
if (s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) {
block_acct_done(blk_get_stats(s->blk), &s->acct);
}
ide_set_inactive(s, stay_active);
}
| 1 | CVE-2014-9718 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 2,487 |
linux | 105cd17a866017b45f3c45901b394c711c97bf40 | static int __bond_release_one(struct net_device *bond_dev,
struct net_device *slave_dev,
bool all, bool unregister)
{
struct bonding *bond = netdev_priv(bond_dev);
struct slave *slave, *oldcurrent;
struct sockaddr_storage ss;
int old_flags = bond_dev->flags;
netdev_features_t old_features = bond_dev->features;
/* slave is not a slave or master is not master of this slave */
if (!(slave_dev->flags & IFF_SLAVE) ||
!netdev_has_upper_dev(slave_dev, bond_dev)) {
slave_dbg(bond_dev, slave_dev, "cannot release slave\n");
return -EINVAL;
}
block_netpoll_tx();
slave = bond_get_slave_by_dev(bond, slave_dev);
if (!slave) {
/* not a slave of this bond */
slave_info(bond_dev, slave_dev, "interface not enslaved\n");
unblock_netpoll_tx();
return -EINVAL;
}
bond_set_slave_inactive_flags(slave, BOND_SLAVE_NOTIFY_NOW);
bond_sysfs_slave_del(slave);
/* recompute stats just before removing the slave */
bond_get_stats(bond->dev, &bond->bond_stats);
bond_upper_dev_unlink(bond, slave);
/* unregister rx_handler early so bond_handle_frame wouldn't be called
* for this slave anymore.
*/
netdev_rx_handler_unregister(slave_dev);
if (BOND_MODE(bond) == BOND_MODE_8023AD)
bond_3ad_unbind_slave(slave);
if (bond_mode_can_use_xmit_hash(bond))
bond_update_slave_arr(bond, slave);
slave_info(bond_dev, slave_dev, "Releasing %s interface\n",
bond_is_active_slave(slave) ? "active" : "backup");
oldcurrent = rcu_access_pointer(bond->curr_active_slave);
RCU_INIT_POINTER(bond->current_arp_slave, NULL);
if (!all && (!bond->params.fail_over_mac ||
BOND_MODE(bond) != BOND_MODE_ACTIVEBACKUP)) {
if (ether_addr_equal_64bits(bond_dev->dev_addr, slave->perm_hwaddr) &&
bond_has_slaves(bond))
slave_warn(bond_dev, slave_dev, "the permanent HWaddr of slave - %pM - is still in use by bond - set the HWaddr of slave to a different address to avoid conflicts\n",
slave->perm_hwaddr);
}
if (rtnl_dereference(bond->primary_slave) == slave)
RCU_INIT_POINTER(bond->primary_slave, NULL);
if (oldcurrent == slave)
bond_change_active_slave(bond, NULL);
if (bond_is_lb(bond)) {
/* Must be called only after the slave has been
* detached from the list and the curr_active_slave
* has been cleared (if our_slave == old_current),
* but before a new active slave is selected.
*/
bond_alb_deinit_slave(bond, slave);
}
if (all) {
RCU_INIT_POINTER(bond->curr_active_slave, NULL);
} else if (oldcurrent == slave) {
/* Note that we hold RTNL over this sequence, so there
* is no concern that another slave add/remove event
* will interfere.
*/
bond_select_active_slave(bond);
}
if (!bond_has_slaves(bond)) {
bond_set_carrier(bond);
eth_hw_addr_random(bond_dev);
}
unblock_netpoll_tx();
synchronize_rcu();
bond->slave_cnt--;
if (!bond_has_slaves(bond)) {
call_netdevice_notifiers(NETDEV_CHANGEADDR, bond->dev);
call_netdevice_notifiers(NETDEV_RELEASE, bond->dev);
}
bond_compute_features(bond);
if (!(bond_dev->features & NETIF_F_VLAN_CHALLENGED) &&
(old_features & NETIF_F_VLAN_CHALLENGED))
slave_info(bond_dev, slave_dev, "last VLAN challenged slave left bond - VLAN blocking is removed\n");
vlan_vids_del_by_dev(slave_dev, bond_dev);
/* If the mode uses primary, then this case was handled above by
* bond_change_active_slave(..., NULL)
*/
if (!bond_uses_primary(bond)) {
/* unset promiscuity level from slave
* NOTE: The NETDEV_CHANGEADDR call above may change the value
* of the IFF_PROMISC flag in the bond_dev, but we need the
* value of that flag before that change, as that was the value
* when this slave was attached, so we cache at the start of the
* function and use it here. Same goes for ALLMULTI below
*/
if (old_flags & IFF_PROMISC)
dev_set_promiscuity(slave_dev, -1);
/* unset allmulti level from slave */
if (old_flags & IFF_ALLMULTI)
dev_set_allmulti(slave_dev, -1);
bond_hw_addr_flush(bond_dev, slave_dev);
}
slave_disable_netpoll(slave);
/* close slave before restoring its mac address */
dev_close(slave_dev);
if (bond->params.fail_over_mac != BOND_FOM_ACTIVE ||
BOND_MODE(bond) != BOND_MODE_ACTIVEBACKUP) {
/* restore original ("permanent") mac address */
bond_hw_addr_copy(ss.__data, slave->perm_hwaddr,
slave->dev->addr_len);
ss.ss_family = slave_dev->type;
dev_set_mac_address(slave_dev, (struct sockaddr *)&ss, NULL);
}
if (unregister)
__dev_set_mtu(slave_dev, slave->original_mtu);
else
dev_set_mtu(slave_dev, slave->original_mtu);
if (!netif_is_bond_master(slave_dev))
slave_dev->priv_flags &= ~IFF_BONDING;
kobject_put(&slave->kobj);
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,552 |
linux | 355b98553789b646ed97ad801a619ff898471b92 | static int rtnl_net_dumpid(struct sk_buff *skb, struct netlink_callback *cb)
{
struct rtnl_net_dump_cb net_cb = {
.tgt_net = sock_net(skb->sk),
.skb = skb,
.fillargs = {
.portid = NETLINK_CB(cb->skb).portid,
.seq = cb->nlh->nlmsg_seq,
.flags = NLM_F_MULTI,
.cmd = RTM_NEWNSID,
},
.idx = 0,
.s_idx = cb->args[0],
};
int err = 0;
if (cb->strict_check) {
err = rtnl_valid_dump_net_req(cb->nlh, skb->sk, &net_cb, cb);
if (err < 0)
goto end;
}
spin_lock_bh(&net_cb.tgt_net->nsid_lock);
if (net_cb.fillargs.add_ref &&
!net_eq(net_cb.ref_net, net_cb.tgt_net) &&
!spin_trylock_bh(&net_cb.ref_net->nsid_lock)) {
spin_unlock_bh(&net_cb.tgt_net->nsid_lock);
err = -EAGAIN;
goto end;
}
idr_for_each(&net_cb.tgt_net->netns_ids, rtnl_net_dumpid_one, &net_cb);
if (net_cb.fillargs.add_ref &&
!net_eq(net_cb.ref_net, net_cb.tgt_net))
spin_unlock_bh(&net_cb.ref_net->nsid_lock);
spin_unlock_bh(&net_cb.tgt_net->nsid_lock);
cb->args[0] = net_cb.idx;
end:
if (net_cb.fillargs.add_ref)
put_net(net_cb.tgt_net);
return err < 0 ? err : skb->len;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,761 |
linux | c88e739b1fad662240e99ecbd0bdaac871717987 | static long media_device_enum_entities(struct media_device *mdev,
struct media_entity_desc __user *uent)
{
struct media_entity *ent;
struct media_entity_desc u_ent;
if (copy_from_user(&u_ent.id, &uent->id, sizeof(u_ent.id)))
return -EFAULT;
ent = find_entity(mdev, u_ent.id);
if (ent == NULL)
return -EINVAL;
u_ent.id = ent->id;
if (ent->name) {
strncpy(u_ent.name, ent->name, sizeof(u_ent.name));
u_ent.name[sizeof(u_ent.name) - 1] = '\0';
} else {
memset(u_ent.name, 0, sizeof(u_ent.name));
}
u_ent.type = ent->type;
u_ent.revision = ent->revision;
u_ent.flags = ent->flags;
u_ent.group_id = ent->group_id;
u_ent.pads = ent->num_pads;
u_ent.links = ent->num_links - ent->num_backlinks;
memcpy(&u_ent.raw, &ent->info, sizeof(ent->info));
if (copy_to_user(uent, &u_ent, sizeof(u_ent)))
return -EFAULT;
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,925 |
openldap | 21981053a1195ae1555e23df4d9ac68d34ede9dd | static int parseDontUseCopy (
Operation *op,
SlapReply *rs,
LDAPControl *ctrl )
{
if ( op->o_dontUseCopy != SLAP_CONTROL_NONE ) {
rs->sr_text = "dontUseCopy control specified multiple times";
return LDAP_PROTOCOL_ERROR;
}
if ( !BER_BVISNULL( &ctrl->ldctl_value )) {
rs->sr_text = "dontUseCopy control value not absent";
return LDAP_PROTOCOL_ERROR;
}
if ( ( global_disallows & SLAP_DISALLOW_DONTUSECOPY_N_CRIT )
&& !ctrl->ldctl_iscritical )
{
rs->sr_text = "dontUseCopy criticality of FALSE not allowed";
return LDAP_PROTOCOL_ERROR;
}
op->o_dontUseCopy = ctrl->ldctl_iscritical
? SLAP_CONTROL_CRITICAL
: SLAP_CONTROL_NONCRITICAL;
return LDAP_SUCCESS;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,355 |
Chrome | ab5e55ff333def909d025ac45da9ffa0d88a63f2 | RTCVoidRequestTask(MockWebRTCPeerConnectionHandler* object, const WebKit::WebRTCVoidRequest& request, bool succeeded)
: MethodTask<MockWebRTCPeerConnectionHandler>(object)
, m_request(request)
, m_succeeded(succeeded)
{
}
| 1 | CVE-2011-2875 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 1,055 |
dcmtk | beaf5a5c24101daeeafa48c375120b16197c9e95 | int main(int argc, char *argv[])
{
T_ASC_Network *net;
DcmAssociationConfiguration asccfg;
#ifdef HAVE_GUSI_H
/* needed for Macintosh */
GUSISetup(GUSIwithSIOUXSockets);
GUSISetup(GUSIwithInternetSockets);
#endif
#ifdef HAVE_WINSOCK_H
WSAData winSockData;
/* we need at least version 1.1 */
WORD winSockVersionNeeded = MAKEWORD( 1, 1 );
WSAStartup(winSockVersionNeeded, &winSockData);
#endif
char tempstr[20];
OFString temp_str;
OFConsoleApplication app(OFFIS_CONSOLE_APPLICATION, "DICOM storage (C-STORE) SCP", rcsid);
OFCommandLine cmd;
cmd.setParamColumn(LONGCOL + SHORTCOL + 4);
cmd.addParam("port", "tcp/ip port number to listen on", OFCmdParam::PM_Optional);
cmd.setOptionColumns(LONGCOL, SHORTCOL);
cmd.addGroup("general options:", LONGCOL, SHORTCOL + 2);
cmd.addOption("--help", "-h", "print this help text and exit", OFCommandLine::AF_Exclusive);
cmd.addOption("--version", "print version information and exit", OFCommandLine::AF_Exclusive);
OFLog::addOptions(cmd);
cmd.addOption("--verbose-pc", "+v", "show presentation contexts in verbose mode");
#if defined(HAVE_FORK) || defined(_WIN32)
cmd.addGroup("multi-process options:", LONGCOL, SHORTCOL + 2);
cmd.addOption("--single-process", "single process mode (default)");
cmd.addOption("--fork", "fork child process for each association");
#ifdef _WIN32
cmd.addOption("--forked-child", "process is forked child, internal use only", OFCommandLine::AF_Internal);
#endif
#endif
cmd.addGroup("network options:");
cmd.addSubGroup("association negotiation profile from configuration file:");
cmd.addOption("--config-file", "-xf", 2, "[f]ilename, [p]rofile: string",
"use profile p from config file f");
cmd.addSubGroup("preferred network transfer syntaxes (not with --config-file):");
cmd.addOption("--prefer-uncompr", "+x=", "prefer explicit VR local byte order (default)");
cmd.addOption("--prefer-little", "+xe", "prefer explicit VR little endian TS");
cmd.addOption("--prefer-big", "+xb", "prefer explicit VR big endian TS");
cmd.addOption("--prefer-lossless", "+xs", "prefer default JPEG lossless TS");
cmd.addOption("--prefer-jpeg8", "+xy", "prefer default JPEG lossy TS for 8 bit data");
cmd.addOption("--prefer-jpeg12", "+xx", "prefer default JPEG lossy TS for 12 bit data");
cmd.addOption("--prefer-j2k-lossless", "+xv", "prefer JPEG 2000 lossless TS");
cmd.addOption("--prefer-j2k-lossy", "+xw", "prefer JPEG 2000 lossy TS");
cmd.addOption("--prefer-jls-lossless", "+xt", "prefer JPEG-LS lossless TS");
cmd.addOption("--prefer-jls-lossy", "+xu", "prefer JPEG-LS lossy TS");
cmd.addOption("--prefer-mpeg2", "+xm", "prefer MPEG2 Main Profile @ Main Level TS");
cmd.addOption("--prefer-mpeg2-high", "+xh", "prefer MPEG2 Main Profile @ High Level TS");
cmd.addOption("--prefer-mpeg4", "+xn", "prefer MPEG4 AVC/H.264 HP / Level 4.1 TS");
cmd.addOption("--prefer-mpeg4-bd", "+xl", "prefer MPEG4 AVC/H.264 BD-compatible TS");
cmd.addOption("--prefer-rle", "+xr", "prefer RLE lossless TS");
#ifdef WITH_ZLIB
cmd.addOption("--prefer-deflated", "+xd", "prefer deflated expl. VR little endian TS");
#endif
cmd.addOption("--implicit", "+xi", "accept implicit VR little endian TS only");
cmd.addOption("--accept-all", "+xa", "accept all supported transfer syntaxes");
#ifdef WITH_TCPWRAPPER
cmd.addSubGroup("network host access control (tcp wrapper):");
cmd.addOption("--access-full", "-ac", "accept connections from any host (default)");
cmd.addOption("--access-control", "+ac", "enforce host access control rules");
#endif
cmd.addSubGroup("other network options:");
#ifdef INETD_AVAILABLE
// this option is only offered on Posix platforms
cmd.addOption("--inetd", "-id", "run from inetd super server (not with --fork)");
#endif
cmd.addOption("--acse-timeout", "-ta", 1, "[s]econds: integer (default: 30)", "timeout for ACSE messages");
cmd.addOption("--dimse-timeout", "-td", 1, "[s]econds: integer (default: unlimited)", "timeout for DIMSE messages");
OFString opt1 = "set my AE title (default: ";
opt1 += APPLICATIONTITLE;
opt1 += ")";
cmd.addOption("--aetitle", "-aet", 1, "[a]etitle: string", opt1.c_str());
OFString opt3 = "set max receive pdu to n bytes (def.: ";
sprintf(tempstr, "%ld", OFstatic_cast(long, ASC_DEFAULTMAXPDU));
opt3 += tempstr;
opt3 += ")";
OFString opt4 = "[n]umber of bytes: integer (";
sprintf(tempstr, "%ld", OFstatic_cast(long, ASC_MINIMUMPDUSIZE));
opt4 += tempstr;
opt4 += "..";
sprintf(tempstr, "%ld", OFstatic_cast(long, ASC_MAXIMUMPDUSIZE));
opt4 += tempstr;
opt4 += ")";
cmd.addOption("--max-pdu", "-pdu", 1, opt4.c_str(), opt3.c_str());
cmd.addOption("--disable-host-lookup", "-dhl", "disable hostname lookup");
cmd.addOption("--refuse", "refuse association");
cmd.addOption("--reject", "reject association if no implement. class UID");
cmd.addOption("--ignore", "ignore store data, receive but do not store");
cmd.addOption("--sleep-after", 1, "[s]econds: integer",
"sleep s seconds after store (default: 0)");
cmd.addOption("--sleep-during", 1, "[s]econds: integer",
"sleep s seconds during store (default: 0)");
cmd.addOption("--abort-after", "abort association after receipt of C-STORE-RQ\n(but before sending response)");
cmd.addOption("--abort-during", "abort association during receipt of C-STORE-RQ");
cmd.addOption("--promiscuous", "-pm", "promiscuous mode, accept unknown SOP classes\n(not with --config-file)");
cmd.addOption("--uid-padding", "-up", "silently correct space-padded UIDs");
#ifdef WITH_OPENSSL
cmd.addGroup("transport layer security (TLS) options:");
cmd.addSubGroup("transport protocol stack:");
cmd.addOption("--disable-tls", "-tls", "use normal TCP/IP connection (default)");
cmd.addOption("--enable-tls", "+tls", 2, "[p]rivate key file, [c]ertificate file: string",
"use authenticated secure TLS connection");
cmd.addSubGroup("private key password (only with --enable-tls):");
cmd.addOption("--std-passwd", "+ps", "prompt user to type password on stdin (default)");
cmd.addOption("--use-passwd", "+pw", 1, "[p]assword: string",
"use specified password");
cmd.addOption("--null-passwd", "-pw", "use empty string as password");
cmd.addSubGroup("key and certificate file format:");
cmd.addOption("--pem-keys", "-pem", "read keys and certificates as PEM file (def.)");
cmd.addOption("--der-keys", "-der", "read keys and certificates as DER file");
cmd.addSubGroup("certification authority:");
cmd.addOption("--add-cert-file", "+cf", 1, "[c]ertificate filename: string",
"add certificate file to list of certificates", OFCommandLine::AF_NoWarning);
cmd.addOption("--add-cert-dir", "+cd", 1, "[c]ertificate directory: string",
"add certificates in d to list of certificates", OFCommandLine::AF_NoWarning);
cmd.addSubGroup("ciphersuite:");
cmd.addOption("--cipher", "+cs", 1, "[c]iphersuite name: string",
"add ciphersuite to list of negotiated suites");
cmd.addOption("--dhparam", "+dp", 1, "[f]ilename: string",
"read DH parameters for DH/DSS ciphersuites");
cmd.addSubGroup("pseudo random generator:");
cmd.addOption("--seed", "+rs", 1, "[f]ilename: string",
"seed random generator with contents of f");
cmd.addOption("--write-seed", "+ws", "write back modified seed (only with --seed)");
cmd.addOption("--write-seed-file", "+wf", 1, "[f]ilename: string (only with --seed)",
"write modified seed to file f");
cmd.addSubGroup("peer authentication");
cmd.addOption("--require-peer-cert", "-rc", "verify peer certificate, fail if absent (def.)");
cmd.addOption("--verify-peer-cert", "-vc", "verify peer certificate if present");
cmd.addOption("--ignore-peer-cert", "-ic", "don't verify peer certificate");
#endif
cmd.addGroup("output options:");
cmd.addSubGroup("general:");
cmd.addOption("--output-directory", "-od", 1, "[d]irectory: string (default: \".\")", "write received objects to existing directory d");
cmd.addSubGroup("bit preserving mode:");
cmd.addOption("--normal", "-B", "allow implicit format conversions (default)");
cmd.addOption("--bit-preserving", "+B", "write data exactly as read");
cmd.addSubGroup("output file format:");
cmd.addOption("--write-file", "+F", "write file format (default)");
cmd.addOption("--write-dataset", "-F", "write data set without file meta information");
cmd.addSubGroup("output transfer syntax (not with --bit-preserving or compressed transmission):");
cmd.addOption("--write-xfer-same", "+t=", "write with same TS as input (default)");
cmd.addOption("--write-xfer-little", "+te", "write with explicit VR little endian TS");
cmd.addOption("--write-xfer-big", "+tb", "write with explicit VR big endian TS");
cmd.addOption("--write-xfer-implicit", "+ti", "write with implicit VR little endian TS");
#ifdef WITH_ZLIB
cmd.addOption("--write-xfer-deflated", "+td", "write with deflated expl. VR little endian TS");
#endif
cmd.addSubGroup("post-1993 value representations (not with --bit-preserving):");
cmd.addOption("--enable-new-vr", "+u", "enable support for new VRs (UN/UT) (default)");
cmd.addOption("--disable-new-vr", "-u", "disable support for new VRs, convert to OB");
cmd.addSubGroup("group length encoding (not with --bit-preserving):");
cmd.addOption("--group-length-recalc", "+g=", "recalculate group lengths if present (default)");
cmd.addOption("--group-length-create", "+g", "always write with group length elements");
cmd.addOption("--group-length-remove", "-g", "always write without group length elements");
cmd.addSubGroup("length encoding in sequences and items (not with --bit-preserving):");
cmd.addOption("--length-explicit", "+e", "write with explicit lengths (default)");
cmd.addOption("--length-undefined", "-e", "write with undefined lengths");
cmd.addSubGroup("data set trailing padding (not with --write-dataset or --bit-preserving):");
cmd.addOption("--padding-off", "-p", "no padding (default)");
cmd.addOption("--padding-create", "+p", 2, "[f]ile-pad [i]tem-pad: integer",
"align file on multiple of f bytes and items\non multiple of i bytes");
#ifdef WITH_ZLIB
cmd.addSubGroup("deflate compression level (only with --write-xfer-deflated/same):");
cmd.addOption("--compression-level", "+cl", 1, "[l]evel: integer (default: 6)",
"0=uncompressed, 1=fastest, 9=best compression");
#endif
cmd.addSubGroup("sorting into subdirectories (not with --bit-preserving):");
cmd.addOption("--sort-conc-studies", "-ss", 1, "[p]refix: string",
"sort studies using prefix p and a timestamp");
cmd.addOption("--sort-on-study-uid", "-su", 1, "[p]refix: string",
"sort studies using prefix p and the Study\nInstance UID");
cmd.addOption("--sort-on-patientname", "-sp", "sort studies using the Patient's Name and\na timestamp");
cmd.addSubGroup("filename generation:");
cmd.addOption("--default-filenames", "-uf", "generate filename from instance UID (default)");
cmd.addOption("--unique-filenames", "+uf", "generate unique filenames");
cmd.addOption("--timenames", "-tn", "generate filename from creation time");
cmd.addOption("--filename-extension", "-fe", 1, "[e]xtension: string",
"append e to all filenames");
cmd.addGroup("event options:", LONGCOL, SHORTCOL + 2);
cmd.addOption("--exec-on-reception", "-xcr", 1, "[c]ommand: string",
"execute command c after having received and\nprocessed one C-STORE-RQ message");
cmd.addOption("--exec-on-eostudy", "-xcs", 1, "[c]ommand: string",
"execute command c after having received and\nprocessed all C-STORE-RQ messages that belong\nto one study");
cmd.addOption("--rename-on-eostudy", "-rns", "having received and processed all C-STORE-RQ\nmessages that belong to one study, rename\noutput files according to certain pattern");
cmd.addOption("--eostudy-timeout", "-tos", 1, "[t]imeout: integer",
"specifies a timeout of t seconds for\nend-of-study determination");
cmd.addOption("--exec-sync", "-xs", "execute command synchronously in foreground");
/* evaluate command line */
prepareCmdLineArgs(argc, argv, OFFIS_CONSOLE_APPLICATION);
if (app.parseCommandLine(cmd, argc, argv))
{
/* print help text and exit */
if (cmd.getArgCount() == 0)
app.printUsage();
/* check exclusive options first */
if (cmd.hasExclusiveOption())
{
if (cmd.findOption("--version"))
{
app.printHeader(OFTrue /*print host identifier*/);
COUT << OFendl << "External libraries used:";
#if !defined(WITH_ZLIB) && !defined(WITH_OPENSSL) && !defined(WITH_TCPWRAPPER)
COUT << " none" << OFendl;
#else
COUT << OFendl;
#endif
#ifdef WITH_ZLIB
COUT << "- ZLIB, Version " << zlibVersion() << OFendl;
#endif
#ifdef WITH_OPENSSL
COUT << "- " << OPENSSL_VERSION_TEXT << OFendl;
#endif
#ifdef WITH_TCPWRAPPER
COUT << "- LIBWRAP" << OFendl;
#endif
return 0;
}
}
#ifdef INETD_AVAILABLE
if (cmd.findOption("--inetd"))
{
opt_inetd_mode = OFTrue;
opt_forkMode = OFFalse;
// duplicate stdin, which is the socket passed by inetd
int inetd_fd = dup(0);
if (inetd_fd < 0) exit(99);
close(0); // close stdin
close(1); // close stdout
close(2); // close stderr
// open new file descriptor for stdin
int fd = open("/dev/null", O_RDONLY);
if (fd != 0) exit(99);
// create new file descriptor for stdout
fd = open("/dev/null", O_WRONLY);
if (fd != 1) exit(99);
// create new file descriptor for stderr
fd = open("/dev/null", O_WRONLY);
if (fd != 2) exit(99);
dcmExternalSocketHandle.set(inetd_fd);
// the port number is not really used. Set to non-privileged port number
// to avoid failing the privilege test.
opt_port = 1024;
}
#endif
#if defined(HAVE_FORK) || defined(_WIN32)
cmd.beginOptionBlock();
if (cmd.findOption("--single-process"))
opt_forkMode = OFFalse;
if (cmd.findOption("--fork"))
{
app.checkConflict("--inetd", "--fork", opt_inetd_mode);
opt_forkMode = OFTrue;
}
cmd.endOptionBlock();
#ifdef _WIN32
if (cmd.findOption("--forked-child")) opt_forkedChild = OFTrue;
#endif
#endif
if (opt_inetd_mode)
{
// port number is not required in inetd mode
if (cmd.getParamCount() > 0)
OFLOG_WARN(storescpLogger, "Parameter port not required in inetd mode");
} else {
// omitting the port number is only allowed in inetd mode
if (cmd.getParamCount() == 0)
app.printError("Missing parameter port");
else
app.checkParam(cmd.getParamAndCheckMinMax(1, opt_port, 1, 65535));
}
OFLog::configureFromCommandLine(cmd, app);
if (cmd.findOption("--verbose-pc"))
{
app.checkDependence("--verbose-pc", "verbose mode", storescpLogger.isEnabledFor(OFLogger::INFO_LOG_LEVEL));
opt_showPresentationContexts = OFTrue;
}
cmd.beginOptionBlock();
if (cmd.findOption("--prefer-uncompr"))
{
opt_acceptAllXfers = OFFalse;
opt_networkTransferSyntax = EXS_Unknown;
}
if (cmd.findOption("--prefer-little")) opt_networkTransferSyntax = EXS_LittleEndianExplicit;
if (cmd.findOption("--prefer-big")) opt_networkTransferSyntax = EXS_BigEndianExplicit;
if (cmd.findOption("--prefer-lossless")) opt_networkTransferSyntax = EXS_JPEGProcess14SV1;
if (cmd.findOption("--prefer-jpeg8")) opt_networkTransferSyntax = EXS_JPEGProcess1;
if (cmd.findOption("--prefer-jpeg12")) opt_networkTransferSyntax = EXS_JPEGProcess2_4;
if (cmd.findOption("--prefer-j2k-lossless")) opt_networkTransferSyntax = EXS_JPEG2000LosslessOnly;
if (cmd.findOption("--prefer-j2k-lossy")) opt_networkTransferSyntax = EXS_JPEG2000;
if (cmd.findOption("--prefer-jls-lossless")) opt_networkTransferSyntax = EXS_JPEGLSLossless;
if (cmd.findOption("--prefer-jls-lossy")) opt_networkTransferSyntax = EXS_JPEGLSLossy;
if (cmd.findOption("--prefer-mpeg2")) opt_networkTransferSyntax = EXS_MPEG2MainProfileAtMainLevel;
if (cmd.findOption("--prefer-mpeg2-high")) opt_networkTransferSyntax = EXS_MPEG2MainProfileAtHighLevel;
if (cmd.findOption("--prefer-mpeg4")) opt_networkTransferSyntax = EXS_MPEG4HighProfileLevel4_1;
if (cmd.findOption("--prefer-mpeg4-bd")) opt_networkTransferSyntax = EXS_MPEG4BDcompatibleHighProfileLevel4_1;
if (cmd.findOption("--prefer-rle")) opt_networkTransferSyntax = EXS_RLELossless;
#ifdef WITH_ZLIB
if (cmd.findOption("--prefer-deflated")) opt_networkTransferSyntax = EXS_DeflatedLittleEndianExplicit;
#endif
if (cmd.findOption("--implicit")) opt_networkTransferSyntax = EXS_LittleEndianImplicit;
if (cmd.findOption("--accept-all"))
{
opt_acceptAllXfers = OFTrue;
opt_networkTransferSyntax = EXS_Unknown;
}
cmd.endOptionBlock();
if (opt_networkTransferSyntax != EXS_Unknown) opt_acceptAllXfers = OFFalse;
if (cmd.findOption("--acse-timeout"))
{
OFCmdSignedInt opt_timeout = 0;
app.checkValue(cmd.getValueAndCheckMin(opt_timeout, 1));
opt_acse_timeout = OFstatic_cast(int, opt_timeout);
}
if (cmd.findOption("--dimse-timeout"))
{
OFCmdSignedInt opt_timeout = 0;
app.checkValue(cmd.getValueAndCheckMin(opt_timeout, 1));
opt_dimse_timeout = OFstatic_cast(int, opt_timeout);
opt_blockMode = DIMSE_NONBLOCKING;
}
if (cmd.findOption("--aetitle")) app.checkValue(cmd.getValue(opt_respondingAETitle));
if (cmd.findOption("--max-pdu")) app.checkValue(cmd.getValueAndCheckMinMax(opt_maxPDU, ASC_MINIMUMPDUSIZE, ASC_MAXIMUMPDUSIZE));
if (cmd.findOption("--disable-host-lookup")) dcmDisableGethostbyaddr.set(OFTrue);
if (cmd.findOption("--refuse")) opt_refuseAssociation = OFTrue;
if (cmd.findOption("--reject")) opt_rejectWithoutImplementationUID = OFTrue;
if (cmd.findOption("--ignore")) opt_ignore = OFTrue;
if (cmd.findOption("--sleep-after")) app.checkValue(cmd.getValueAndCheckMin(opt_sleepAfter, 0));
if (cmd.findOption("--sleep-during")) app.checkValue(cmd.getValueAndCheckMin(opt_sleepDuring, 0));
if (cmd.findOption("--abort-after")) opt_abortAfterStore = OFTrue;
if (cmd.findOption("--abort-during")) opt_abortDuringStore = OFTrue;
if (cmd.findOption("--promiscuous")) opt_promiscuous = OFTrue;
if (cmd.findOption("--uid-padding")) opt_correctUIDPadding = OFTrue;
if (cmd.findOption("--config-file"))
{
// check conflicts with other command line options
app.checkConflict("--config-file", "--prefer-little", opt_networkTransferSyntax == EXS_LittleEndianExplicit);
app.checkConflict("--config-file", "--prefer-big", opt_networkTransferSyntax == EXS_BigEndianExplicit);
app.checkConflict("--config-file", "--prefer-lossless", opt_networkTransferSyntax == EXS_JPEGProcess14SV1);
app.checkConflict("--config-file", "--prefer-jpeg8", opt_networkTransferSyntax == EXS_JPEGProcess1);
app.checkConflict("--config-file", "--prefer-jpeg12", opt_networkTransferSyntax == EXS_JPEGProcess2_4);
app.checkConflict("--config-file", "--prefer-j2k-lossless", opt_networkTransferSyntax == EXS_JPEG2000LosslessOnly);
app.checkConflict("--config-file", "--prefer-j2k-lossy", opt_networkTransferSyntax == EXS_JPEG2000);
app.checkConflict("--config-file", "--prefer-jls-lossless", opt_networkTransferSyntax == EXS_JPEGLSLossless);
app.checkConflict("--config-file", "--prefer-jls-lossy", opt_networkTransferSyntax == EXS_JPEGLSLossy);
app.checkConflict("--config-file", "--prefer-mpeg2", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtMainLevel);
app.checkConflict("--config-file", "--prefer-mpeg2-high", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtHighLevel);
app.checkConflict("--config-file", "--prefer-mpeg4", opt_networkTransferSyntax == EXS_MPEG4HighProfileLevel4_1);
app.checkConflict("--config-file", "--prefer-mpeg4-bd", opt_networkTransferSyntax == EXS_MPEG4BDcompatibleHighProfileLevel4_1);
app.checkConflict("--config-file", "--prefer-rle", opt_networkTransferSyntax == EXS_RLELossless);
#ifdef WITH_ZLIB
app.checkConflict("--config-file", "--prefer-deflated", opt_networkTransferSyntax == EXS_DeflatedLittleEndianExplicit);
#endif
app.checkConflict("--config-file", "--implicit", opt_networkTransferSyntax == EXS_LittleEndianImplicit);
app.checkConflict("--config-file", "--accept-all", opt_acceptAllXfers);
app.checkConflict("--config-file", "--promiscuous", opt_promiscuous);
app.checkValue(cmd.getValue(opt_configFile));
app.checkValue(cmd.getValue(opt_profileName));
// read configuration file
OFCondition cond = DcmAssociationConfigurationFile::initialize(asccfg, opt_configFile);
if (cond.bad())
{
OFLOG_FATAL(storescpLogger, "cannot read config file: " << cond.text());
return 1;
}
/* perform name mangling for config file key */
OFString sprofile;
const unsigned char *c = OFreinterpret_cast(const unsigned char *, opt_profileName);
while (*c)
{
if (! isspace(*c)) sprofile += OFstatic_cast(char, toupper(*c));
++c;
}
if (!asccfg.isKnownProfile(sprofile.c_str()))
{
OFLOG_FATAL(storescpLogger, "unknown configuration profile name: " << sprofile);
return 1;
}
if (!asccfg.isValidSCPProfile(sprofile.c_str()))
{
OFLOG_FATAL(storescpLogger, "profile '" << sprofile << "' is not valid for SCP use, duplicate abstract syntaxes found");
return 1;
}
}
#ifdef WITH_TCPWRAPPER
cmd.beginOptionBlock();
if (cmd.findOption("--access-full")) dcmTCPWrapperDaemonName.set(NULL);
if (cmd.findOption("--access-control")) dcmTCPWrapperDaemonName.set(OFFIS_CONSOLE_APPLICATION);
cmd.endOptionBlock();
#endif
if (cmd.findOption("--output-directory")) app.checkValue(cmd.getValue(opt_outputDirectory));
cmd.beginOptionBlock();
if (cmd.findOption("--normal")) opt_bitPreserving = OFFalse;
if (cmd.findOption("--bit-preserving")) opt_bitPreserving = OFTrue;
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--write-file")) opt_useMetaheader = OFTrue;
if (cmd.findOption("--write-dataset")) opt_useMetaheader = OFFalse;
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--write-xfer-same")) opt_writeTransferSyntax = EXS_Unknown;
if (cmd.findOption("--write-xfer-little"))
{
app.checkConflict("--write-xfer-little", "--accept-all", opt_acceptAllXfers);
app.checkConflict("--write-xfer-little", "--bit-preserving", opt_bitPreserving);
app.checkConflict("--write-xfer-little", "--prefer-lossless", opt_networkTransferSyntax == EXS_JPEGProcess14SV1);
app.checkConflict("--write-xfer-little", "--prefer-jpeg8", opt_networkTransferSyntax == EXS_JPEGProcess1);
app.checkConflict("--write-xfer-little", "--prefer-jpeg12", opt_networkTransferSyntax == EXS_JPEGProcess2_4);
app.checkConflict("--write-xfer-little", "--prefer-j2k-lossless", opt_networkTransferSyntax == EXS_JPEG2000LosslessOnly);
app.checkConflict("--write-xfer-little", "--prefer-j2k-lossy", opt_networkTransferSyntax == EXS_JPEG2000);
app.checkConflict("--write-xfer-little", "--prefer-jls-lossless", opt_networkTransferSyntax == EXS_JPEGLSLossless);
app.checkConflict("--write-xfer-little", "--prefer-jls-lossy", opt_networkTransferSyntax == EXS_JPEGLSLossy);
app.checkConflict("--write-xfer-little", "--prefer-mpeg2", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtMainLevel);
app.checkConflict("--write-xfer-little", "--prefer-mpeg2-high", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtHighLevel);
app.checkConflict("--write-xfer-little", "--prefer-mpeg4", opt_networkTransferSyntax == EXS_MPEG4HighProfileLevel4_1);
app.checkConflict("--write-xfer-little", "--prefer-mpeg4-bd", opt_networkTransferSyntax == EXS_MPEG4BDcompatibleHighProfileLevel4_1);
app.checkConflict("--write-xfer-little", "--prefer-rle", opt_networkTransferSyntax == EXS_RLELossless);
// we don't have to check a conflict for --prefer-deflated because we can always convert that to uncompressed.
opt_writeTransferSyntax = EXS_LittleEndianExplicit;
}
if (cmd.findOption("--write-xfer-big"))
{
app.checkConflict("--write-xfer-big", "--accept-all", opt_acceptAllXfers);
app.checkConflict("--write-xfer-big", "--bit-preserving", opt_bitPreserving);
app.checkConflict("--write-xfer-big", "--prefer-lossless", opt_networkTransferSyntax == EXS_JPEGProcess14SV1);
app.checkConflict("--write-xfer-big", "--prefer-jpeg8", opt_networkTransferSyntax == EXS_JPEGProcess1);
app.checkConflict("--write-xfer-big", "--prefer-jpeg12", opt_networkTransferSyntax == EXS_JPEGProcess2_4);
app.checkConflict("--write-xfer-big", "--prefer-j2k-lossless", opt_networkTransferSyntax == EXS_JPEG2000LosslessOnly);
app.checkConflict("--write-xfer-big", "--prefer-j2k-lossy", opt_networkTransferSyntax == EXS_JPEG2000);
app.checkConflict("--write-xfer-big", "--prefer-jls-lossless", opt_networkTransferSyntax == EXS_JPEGLSLossless);
app.checkConflict("--write-xfer-big", "--prefer-jls-lossy", opt_networkTransferSyntax == EXS_JPEGLSLossy);
app.checkConflict("--write-xfer-big", "--prefer-mpeg2", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtMainLevel);
app.checkConflict("--write-xfer-big", "--prefer-mpeg2-high", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtHighLevel);
app.checkConflict("--write-xfer-big", "--prefer-mpeg4", opt_networkTransferSyntax == EXS_MPEG4HighProfileLevel4_1);
app.checkConflict("--write-xfer-big", "--prefer-mpeg4-bd", opt_networkTransferSyntax == EXS_MPEG4BDcompatibleHighProfileLevel4_1);
app.checkConflict("--write-xfer-big", "--prefer-rle", opt_networkTransferSyntax == EXS_RLELossless);
// we don't have to check a conflict for --prefer-deflated because we can always convert that to uncompressed.
opt_writeTransferSyntax = EXS_BigEndianExplicit;
}
if (cmd.findOption("--write-xfer-implicit"))
{
app.checkConflict("--write-xfer-implicit", "--accept-all", opt_acceptAllXfers);
app.checkConflict("--write-xfer-implicit", "--bit-preserving", opt_bitPreserving);
app.checkConflict("--write-xfer-implicit", "--prefer-lossless", opt_networkTransferSyntax == EXS_JPEGProcess14SV1);
app.checkConflict("--write-xfer-implicit", "--prefer-jpeg8", opt_networkTransferSyntax == EXS_JPEGProcess1);
app.checkConflict("--write-xfer-implicit", "--prefer-jpeg12", opt_networkTransferSyntax == EXS_JPEGProcess2_4);
app.checkConflict("--write-xfer-implicit", "--prefer-j2k-lossless", opt_networkTransferSyntax == EXS_JPEG2000LosslessOnly);
app.checkConflict("--write-xfer-implicit", "--prefer-j2k-lossy", opt_networkTransferSyntax == EXS_JPEG2000);
app.checkConflict("--write-xfer-implicit", "--prefer-jls-lossless", opt_networkTransferSyntax == EXS_JPEGLSLossless);
app.checkConflict("--write-xfer-implicit", "--prefer-jls-lossy", opt_networkTransferSyntax == EXS_JPEGLSLossy);
app.checkConflict("--write-xfer-implicit", "--prefer-mpeg2", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtMainLevel);
app.checkConflict("--write-xfer-implicit", "--prefer-mpeg2-high", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtHighLevel);
app.checkConflict("--write-xfer-implicit", "--prefer-mpeg4", opt_networkTransferSyntax == EXS_MPEG4HighProfileLevel4_1);
app.checkConflict("--write-xfer-implicit", "--prefer-mpeg4-bd", opt_networkTransferSyntax == EXS_MPEG4BDcompatibleHighProfileLevel4_1);
app.checkConflict("--write-xfer-implicit", "--prefer-rle", opt_networkTransferSyntax == EXS_RLELossless);
// we don't have to check a conflict for --prefer-deflated because we can always convert that to uncompressed.
opt_writeTransferSyntax = EXS_LittleEndianImplicit;
}
#ifdef WITH_ZLIB
if (cmd.findOption("--write-xfer-deflated"))
{
app.checkConflict("--write-xfer-deflated", "--accept-all", opt_acceptAllXfers);
app.checkConflict("--write-xfer-deflated", "--bit-preserving", opt_bitPreserving);
app.checkConflict("--write-xfer-deflated", "--prefer-lossless", opt_networkTransferSyntax == EXS_JPEGProcess14SV1);
app.checkConflict("--write-xfer-deflated", "--prefer-jpeg8", opt_networkTransferSyntax == EXS_JPEGProcess1);
app.checkConflict("--write-xfer-deflated", "--prefer-jpeg12", opt_networkTransferSyntax == EXS_JPEGProcess2_4);
app.checkConflict("--write-xfer-deflated", "--prefer-j2k-lossless", opt_networkTransferSyntax == EXS_JPEG2000LosslessOnly);
app.checkConflict("--write-xfer-deflated", "--prefer-j2k-lossy", opt_networkTransferSyntax == EXS_JPEG2000);
app.checkConflict("--write-xfer-deflated", "--prefer-jls-lossless", opt_networkTransferSyntax == EXS_JPEGLSLossless);
app.checkConflict("--write-xfer-deflated", "--prefer-jls-lossy", opt_networkTransferSyntax == EXS_JPEGLSLossy);
app.checkConflict("--write-xfer-deflated", "--prefer-mpeg2", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtMainLevel);
app.checkConflict("--write-xfer-deflated", "--prefer-mpeg2-high", opt_networkTransferSyntax == EXS_MPEG2MainProfileAtHighLevel);
app.checkConflict("--write-xfer-deflated", "--prefer-mpeg4", opt_networkTransferSyntax == EXS_MPEG4HighProfileLevel4_1);
app.checkConflict("--write-xfer-deflated", "--prefer-mpeg4-bd", opt_networkTransferSyntax == EXS_MPEG4BDcompatibleHighProfileLevel4_1);
app.checkConflict("--write-xfer-deflated", "--prefer-rle", opt_networkTransferSyntax == EXS_RLELossless);
opt_writeTransferSyntax = EXS_DeflatedLittleEndianExplicit;
}
#endif
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--enable-new-vr"))
{
app.checkConflict("--enable-new-vr", "--bit-preserving", opt_bitPreserving);
dcmEnableUnknownVRGeneration.set(OFTrue);
dcmEnableUnlimitedTextVRGeneration.set(OFTrue);
dcmEnableOtherFloatStringVRGeneration.set(OFTrue);
dcmEnableOtherDoubleStringVRGeneration.set(OFTrue);
}
if (cmd.findOption("--disable-new-vr"))
{
app.checkConflict("--disable-new-vr", "--bit-preserving", opt_bitPreserving);
dcmEnableUnknownVRGeneration.set(OFFalse);
dcmEnableUnlimitedTextVRGeneration.set(OFFalse);
dcmEnableOtherFloatStringVRGeneration.set(OFFalse);
dcmEnableOtherDoubleStringVRGeneration.set(OFFalse);
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--group-length-recalc"))
{
app.checkConflict("--group-length-recalc", "--bit-preserving", opt_bitPreserving);
opt_groupLength = EGL_recalcGL;
}
if (cmd.findOption("--group-length-create"))
{
app.checkConflict("--group-length-create", "--bit-preserving", opt_bitPreserving);
opt_groupLength = EGL_withGL;
}
if (cmd.findOption("--group-length-remove"))
{
app.checkConflict("--group-length-remove", "--bit-preserving", opt_bitPreserving);
opt_groupLength = EGL_withoutGL;
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--length-explicit"))
{
app.checkConflict("--length-explicit", "--bit-preserving", opt_bitPreserving);
opt_sequenceType = EET_ExplicitLength;
}
if (cmd.findOption("--length-undefined"))
{
app.checkConflict("--length-undefined", "--bit-preserving", opt_bitPreserving);
opt_sequenceType = EET_UndefinedLength;
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--padding-off")) opt_paddingType = EPD_withoutPadding;
if (cmd.findOption("--padding-create"))
{
app.checkConflict("--padding-create", "--write-dataset", !opt_useMetaheader);
app.checkConflict("--padding-create", "--bit-preserving", opt_bitPreserving);
app.checkValue(cmd.getValueAndCheckMin(opt_filepad, 0));
app.checkValue(cmd.getValueAndCheckMin(opt_itempad, 0));
opt_paddingType = EPD_withPadding;
}
cmd.endOptionBlock();
#ifdef WITH_ZLIB
if (cmd.findOption("--compression-level"))
{
app.checkDependence("--compression-level", "--write-xfer-deflated or --write-xfer-same",
(opt_writeTransferSyntax == EXS_DeflatedLittleEndianExplicit) || (opt_writeTransferSyntax == EXS_Unknown));
app.checkValue(cmd.getValueAndCheckMinMax(opt_compressionLevel, 0, 9));
dcmZlibCompressionLevel.set(OFstatic_cast(int, opt_compressionLevel));
}
#endif
cmd.beginOptionBlock();
if (cmd.findOption("--sort-conc-studies"))
{
app.checkConflict("--sort-conc-studies", "--bit-preserving", opt_bitPreserving);
app.checkValue(cmd.getValue(opt_sortStudyDirPrefix));
opt_sortStudyMode = ESM_Timestamp;
}
if (cmd.findOption("--sort-on-study-uid"))
{
app.checkConflict("--sort-on-study-uid", "--bit-preserving", opt_bitPreserving);
app.checkValue(cmd.getValue(opt_sortStudyDirPrefix));
opt_sortStudyMode = ESM_StudyInstanceUID;
}
if (cmd.findOption("--sort-on-patientname"))
{
app.checkConflict("--sort-on-patientname", "--bit-preserving", opt_bitPreserving);
opt_sortStudyDirPrefix = NULL;
opt_sortStudyMode = ESM_PatientName;
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--default-filenames")) opt_uniqueFilenames = OFFalse;
if (cmd.findOption("--unique-filenames")) opt_uniqueFilenames = OFTrue;
cmd.endOptionBlock();
if (cmd.findOption("--timenames")) opt_timeNames = OFTrue;
if (cmd.findOption("--filename-extension"))
app.checkValue(cmd.getValue(opt_fileNameExtension));
if (cmd.findOption("--timenames"))
app.checkConflict("--timenames", "--unique-filenames", opt_uniqueFilenames);
if (cmd.findOption("--exec-on-reception")) app.checkValue(cmd.getValue(opt_execOnReception));
if (cmd.findOption("--exec-on-eostudy"))
{
app.checkConflict("--exec-on-eostudy", "--fork", opt_forkMode);
app.checkConflict("--exec-on-eostudy", "--inetd", opt_inetd_mode);
app.checkDependence("--exec-on-eostudy", "--sort-conc-studies, --sort-on-study-uid or --sort-on-patientname", opt_sortStudyMode != ESM_None );
app.checkValue(cmd.getValue(opt_execOnEndOfStudy));
}
if (cmd.findOption("--rename-on-eostudy"))
{
app.checkConflict("--rename-on-eostudy", "--fork", opt_forkMode);
app.checkConflict("--rename-on-eostudy", "--inetd", opt_inetd_mode);
app.checkDependence("--rename-on-eostudy", "--sort-conc-studies, --sort-on-study-uid or --sort-on-patientname", opt_sortStudyMode != ESM_None );
opt_renameOnEndOfStudy = OFTrue;
}
if (cmd.findOption("--eostudy-timeout"))
{
app.checkDependence("--eostudy-timeout", "--sort-conc-studies, --sort-on-study-uid, --sort-on-patientname, --exec-on-eostudy or --rename-on-eostudy",
(opt_sortStudyMode != ESM_None) || (opt_execOnEndOfStudy != NULL) || opt_renameOnEndOfStudy);
app.checkValue(cmd.getValueAndCheckMin(opt_endOfStudyTimeout, 0));
}
if (cmd.findOption("--exec-sync")) opt_execSync = OFTrue;
}
/* print resource identifier */
OFLOG_DEBUG(storescpLogger, rcsid << OFendl);
#ifdef WITH_OPENSSL
cmd.beginOptionBlock();
if (cmd.findOption("--disable-tls")) opt_secureConnection = OFFalse;
if (cmd.findOption("--enable-tls"))
{
opt_secureConnection = OFTrue;
app.checkValue(cmd.getValue(opt_privateKeyFile));
app.checkValue(cmd.getValue(opt_certificateFile));
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--std-passwd"))
{
app.checkDependence("--std-passwd", "--enable-tls", opt_secureConnection);
opt_passwd = NULL;
}
if (cmd.findOption("--use-passwd"))
{
app.checkDependence("--use-passwd", "--enable-tls", opt_secureConnection);
app.checkValue(cmd.getValue(opt_passwd));
}
if (cmd.findOption("--null-passwd"))
{
app.checkDependence("--null-passwd", "--enable-tls", opt_secureConnection);
opt_passwd = "";
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--pem-keys")) opt_keyFileFormat = SSL_FILETYPE_PEM;
if (cmd.findOption("--der-keys")) opt_keyFileFormat = SSL_FILETYPE_ASN1;
cmd.endOptionBlock();
if (cmd.findOption("--dhparam"))
{
app.checkValue(cmd.getValue(opt_dhparam));
}
if (cmd.findOption("--seed"))
{
app.checkValue(cmd.getValue(opt_readSeedFile));
}
cmd.beginOptionBlock();
if (cmd.findOption("--write-seed"))
{
app.checkDependence("--write-seed", "--seed", opt_readSeedFile != NULL);
opt_writeSeedFile = opt_readSeedFile;
}
if (cmd.findOption("--write-seed-file"))
{
app.checkDependence("--write-seed-file", "--seed", opt_readSeedFile != NULL);
app.checkValue(cmd.getValue(opt_writeSeedFile));
}
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--require-peer-cert")) opt_certVerification = DCV_requireCertificate;
if (cmd.findOption("--verify-peer-cert")) opt_certVerification = DCV_checkCertificate;
if (cmd.findOption("--ignore-peer-cert")) opt_certVerification = DCV_ignoreCertificate;
cmd.endOptionBlock();
const char *current = NULL;
const char *currentOpenSSL;
if (cmd.findOption("--cipher", 0, OFCommandLine::FOM_First))
{
opt_ciphersuites.clear();
do
{
app.checkValue(cmd.getValue(current));
if (NULL == (currentOpenSSL = DcmTLSTransportLayer::findOpenSSLCipherSuiteName(current)))
{
OFLOG_FATAL(storescpLogger, "ciphersuite '" << current << "' is unknown, known ciphersuites are:");
unsigned long numSuites = DcmTLSTransportLayer::getNumberOfCipherSuites();
for (unsigned long cs = 0; cs < numSuites; cs++)
{
OFLOG_FATAL(storescpLogger, " " << DcmTLSTransportLayer::getTLSCipherSuiteName(cs));
}
return 1;
}
else
{
if (!opt_ciphersuites.empty()) opt_ciphersuites += ":";
opt_ciphersuites += currentOpenSSL;
}
} while (cmd.findOption("--cipher", 0, OFCommandLine::FOM_Next));
}
#endif
#ifndef DISABLE_PORT_PERMISSION_CHECK
#ifdef HAVE_GETEUID
/* if port is privileged we must be as well */
if (opt_port < 1024)
{
if (geteuid() != 0)
{
OFLOG_FATAL(storescpLogger, "cannot listen on port " << opt_port << ", insufficient privileges");
return 1;
}
}
#endif
#endif
/* make sure data dictionary is loaded */
if (!dcmDataDict.isDictionaryLoaded())
{
OFLOG_WARN(storescpLogger, "no data dictionary loaded, check environment variable: "
<< DCM_DICT_ENVIRONMENT_VARIABLE);
}
/* if the output directory does not equal "." (default directory) */
if (opt_outputDirectory != ".")
{
/* if there is a path separator at the end of the path, get rid of it */
OFStandard::normalizeDirName(opt_outputDirectory, opt_outputDirectory);
/* check if the specified directory exists and if it is a directory.
* If the output directory is invalid, dump an error message and terminate execution.
*/
if (!OFStandard::dirExists(opt_outputDirectory))
{
OFLOG_FATAL(storescpLogger, "specified output directory does not exist");
return 1;
}
}
/* check if the output directory is writeable */
if (!OFStandard::isWriteable(opt_outputDirectory))
{
OFLOG_FATAL(storescpLogger, "specified output directory is not writeable");
return 1;
}
#ifdef HAVE_FORK
if (opt_forkMode)
DUL_requestForkOnTransportConnectionReceipt(argc, argv);
#elif defined(_WIN32)
if (opt_forkedChild)
{
// child process
DUL_markProcessAsForkedChild();
char buf[256];
DWORD bytesRead = 0;
HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
// read socket handle number from stdin, i.e. the anonymous pipe
// to which our parent process has written the handle number.
if (ReadFile(hStdIn, buf, sizeof(buf), &bytesRead, NULL))
{
// make sure buffer is zero terminated
buf[bytesRead] = '\0';
dcmExternalSocketHandle.set(atoi(buf));
}
else
{
OFLOG_ERROR(storescpLogger, "cannot read socket handle: " << GetLastError());
return 1;
}
}
else
{
// parent process
if (opt_forkMode)
DUL_requestForkOnTransportConnectionReceipt(argc, argv);
}
#endif
/* initialize network, i.e. create an instance of T_ASC_Network*. */
OFCondition cond = ASC_initializeNetwork(NET_ACCEPTOR, OFstatic_cast(int, opt_port), opt_acse_timeout, &net);
if (cond.bad())
{
OFLOG_ERROR(storescpLogger, "cannot create network: " << DimseCondition::dump(temp_str, cond));
return 1;
}
#ifdef HAVE_GETUID
/* return to normal uid so that we can't do too much damage in case
* things go very wrong. Only does something if the program is setuid
* root, and run by another user. Running as root user may be
* potentially disastrous if this program screws up badly.
*/
setuid(getuid());
#endif
#ifdef WITH_OPENSSL
DcmTLSTransportLayer *tLayer = NULL;
if (opt_secureConnection)
{
tLayer = new DcmTLSTransportLayer(DICOM_APPLICATION_ACCEPTOR, opt_readSeedFile);
if (tLayer == NULL)
{
OFLOG_FATAL(storescpLogger, "unable to create TLS transport layer");
return 1;
}
if (cmd.findOption("--add-cert-file", 0, OFCommandLine::FOM_First))
{
do
{
app.checkValue(cmd.getValue(current));
if (TCS_ok != tLayer->addTrustedCertificateFile(current, opt_keyFileFormat))
{
OFLOG_WARN(storescpLogger, "unable to load certificate file '" << current << "', ignoring");
}
} while (cmd.findOption("--add-cert-file", 0, OFCommandLine::FOM_Next));
}
if (cmd.findOption("--add-cert-dir", 0, OFCommandLine::FOM_First))
{
do
{
app.checkValue(cmd.getValue(current));
if (TCS_ok != tLayer->addTrustedCertificateDir(current, opt_keyFileFormat))
{
OFLOG_WARN(storescpLogger, "unable to load certificates from directory '" << current << "', ignoring");
}
} while (cmd.findOption("--add-cert-dir", 0, OFCommandLine::FOM_Next));
}
if (opt_dhparam && !(tLayer->setTempDHParameters(opt_dhparam)))
{
OFLOG_WARN(storescpLogger, "unable to load temporary DH parameter file '" << opt_dhparam << "', ignoring");
}
if (opt_passwd) tLayer->setPrivateKeyPasswd(opt_passwd);
if (TCS_ok != tLayer->setPrivateKeyFile(opt_privateKeyFile, opt_keyFileFormat))
{
OFLOG_WARN(storescpLogger, "unable to load private TLS key from '" << opt_privateKeyFile << "'");
return 1;
}
if (TCS_ok != tLayer->setCertificateFile(opt_certificateFile, opt_keyFileFormat))
{
OFLOG_WARN(storescpLogger, "unable to load certificate from '" << opt_certificateFile << "'");
return 1;
}
if (! tLayer->checkPrivateKeyMatchesCertificate())
{
OFLOG_WARN(storescpLogger, "private key '" << opt_privateKeyFile << "' and certificate '" << opt_certificateFile << "' do not match");
return 1;
}
if (TCS_ok != tLayer->setCipherSuites(opt_ciphersuites.c_str()))
{
OFLOG_WARN(storescpLogger, "unable to set selected cipher suites");
return 1;
}
tLayer->setCertificateVerification(opt_certVerification);
cond = ASC_setTransportLayer(net, tLayer, 0);
if (cond.bad())
{
OFLOG_ERROR(storescpLogger, DimseCondition::dump(temp_str, cond));
return 1;
}
}
#endif
#ifdef HAVE_WAITPID
// register signal handler
signal(SIGCHLD, sigChildHandler);
#endif
while (cond.good())
{
/* receive an association and acknowledge or reject it. If the association was */
/* acknowledged, offer corresponding services and invoke one or more if required. */
cond = acceptAssociation(net, asccfg);
/* remove zombie child processes */
cleanChildren(-1, OFFalse);
#ifdef WITH_OPENSSL
/* since storescp is usually terminated with SIGTERM or the like,
* we write back an updated random seed after every association handled.
*/
if (tLayer && opt_writeSeedFile)
{
if (tLayer->canWriteRandomSeed())
{
if (!tLayer->writeRandomSeed(opt_writeSeedFile))
OFLOG_WARN(storescpLogger, "cannot write random seed file '" << opt_writeSeedFile << "', ignoring");
}
else
{
OFLOG_WARN(storescpLogger, "cannot write random seed, ignoring");
}
}
#endif
// if running in inetd mode, we always terminate after one association
if (opt_inetd_mode) break;
// if running in multi-process mode, always terminate child after one association
if (DUL_processIsForkedChild()) break;
}
/* drop the network, i.e. free memory of T_ASC_Network* structure. This call */
/* is the counterpart of ASC_initializeNetwork(...) which was called above. */
cond = ASC_dropNetwork(&net);
if (cond.bad())
{
OFLOG_ERROR(storescpLogger, DimseCondition::dump(temp_str, cond));
return 1;
}
#ifdef HAVE_WINSOCK_H
WSACleanup();
#endif
#ifdef WITH_OPENSSL
delete tLayer;
#endif
return 0;
} | 1 | CVE-2013-6825 | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | Not Found in CWE Page | 4,431 |
radvd | 074816cd0b37aac7b3209987e6e998f0a847b275 | privsep_read_loop(void)
{
struct privsep_command cmd;
int ret;
while (1) {
ret = readn(pfd, &cmd, sizeof(cmd));
if (ret <= 0) {
/* Error or EOF, give up */
if (ret < 0) {
flog(LOG_ERR, "Exiting, privsep_read_loop had readn error: %s\n",
strerror(errno));
} else {
flog(LOG_ERR, "Exiting, privsep_read_loop had readn return 0 bytes\n");
}
close(pfd);
_exit(0);
}
if (ret != sizeof(cmd)) {
/* Short read, ignore */
continue;
}
cmd.iface[IFNAMSIZ-1] = '\0';
switch(cmd.type) {
case SET_INTERFACE_LINKMTU:
if (cmd.val < MIN_AdvLinkMTU || cmd.val > MAX_AdvLinkMTU) {
flog(LOG_ERR, "(privsep) %s: LinkMTU (%u) is not within the defined bounds, ignoring", cmd.iface, cmd.val);
break;
}
ret = set_interface_var(cmd.iface, PROC_SYS_IP6_LINKMTU, "LinkMTU", cmd.val);
break;
case SET_INTERFACE_CURHLIM:
if (cmd.val < MIN_AdvCurHopLimit || cmd.val > MAX_AdvCurHopLimit) {
flog(LOG_ERR, "(privsep) %s: CurHopLimit (%u) is not within the defined bounds, ignoring", cmd.iface, cmd.val);
break;
}
ret = set_interface_var(cmd.iface, PROC_SYS_IP6_CURHLIM, "CurHopLimit", cmd.val);
break;
case SET_INTERFACE_REACHTIME:
if (cmd.val < MIN_AdvReachableTime || cmd.val > MAX_AdvReachableTime) {
flog(LOG_ERR, "(privsep) %s: BaseReachableTimer (%u) is not within the defined bounds, ignoring", cmd.iface, cmd.val);
break;
}
ret = set_interface_var(cmd.iface, PROC_SYS_IP6_BASEREACHTIME_MS, "BaseReachableTimer (ms)", cmd.val);
if (ret == 0)
break;
set_interface_var(cmd.iface, PROC_SYS_IP6_BASEREACHTIME, "BaseReachableTimer", cmd.val / 1000);
break;
case SET_INTERFACE_RETRANSTIMER:
if (cmd.val < MIN_AdvRetransTimer || cmd.val > MAX_AdvRetransTimer) {
flog(LOG_ERR, "(privsep) %s: RetransTimer (%u) is not within the defined bounds, ignoring", cmd.iface, cmd.val);
break;
}
ret = set_interface_var(cmd.iface, PROC_SYS_IP6_RETRANSTIMER_MS, "RetransTimer (ms)", cmd.val);
if (ret == 0)
break;
set_interface_var(cmd.iface, PROC_SYS_IP6_RETRANSTIMER, "RetransTimer", cmd.val / 1000 * USER_HZ); /* XXX user_hz */
break;
default:
/* Bad command */
break;
}
}
} | 1 | CVE-2011-3603 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 4,254 |
Chrome | dd3b6fe574edad231c01c78e4647a74c38dc4178 | GDataDirectory::GDataDirectory(GDataDirectory* parent,
GDataDirectoryService* directory_service)
: GDataEntry(parent, directory_service) {
file_info_.is_directory = true;
}
| 1 | CVE-2013-0839 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 2,852 |
libgd | 69d2fd2c597ffc0c217de1238b9bf4d4bceba8e6 | _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
int *cs, int *vers, int *fmt, int *ncx, int *ncy,
t_chunk_info ** chunkIdx)
{
int i;
int ch;
char id[5];
t_chunk_info *cidx;
int sidx;
int nc;
GD2_DBG (printf ("Reading gd2 header info\n"));
for (i = 0; i < 4; i++) {
ch = gdGetC (in);
if (ch == EOF) {
goto fail1;
};
id[i] = ch;
};
id[4] = 0;
GD2_DBG (printf ("Got file code: %s\n", id));
/* Equiv. of 'magick'. */
if (strcmp (id, GD2_ID) != 0) {
GD2_DBG (printf ("Not a valid gd2 file\n"));
goto fail1;
};
/* Version */
if (gdGetWord (vers, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Version: %d\n", *vers));
if ((*vers != 1) && (*vers != 2)) {
GD2_DBG (printf ("Bad version: %d\n", *vers));
goto fail1;
};
/* Image Size */
if (!gdGetWord (sx, in)) {
GD2_DBG (printf ("Could not get x-size\n"));
goto fail1;
}
if (!gdGetWord (sy, in)) {
GD2_DBG (printf ("Could not get y-size\n"));
goto fail1;
}
GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy));
/* Chunk Size (pixels, not bytes!) */
if (gdGetWord (cs, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("ChunkSize: %d\n", *cs));
if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
GD2_DBG (printf ("Bad chunk size: %d\n", *cs));
goto fail1;
};
/* Data Format */
if (gdGetWord (fmt, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Format: %d\n", *fmt));
if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) &&
(*fmt != GD2_FMT_TRUECOLOR_RAW) &&
(*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
GD2_DBG (printf ("Bad data format: %d\n", *fmt));
goto fail1;
};
/* # of chunks wide */
if (gdGetWord (ncx, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks Wide\n", *ncx));
/* # of chunks high */
if (gdGetWord (ncy, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks vertically\n", *ncy));
if (gd2_compressed (*fmt)) {
nc = (*ncx) * (*ncy);
GD2_DBG (printf ("Reading %d chunk index entries\n", nc));
if (overflow2(sizeof(t_chunk_info), nc)) {
goto fail1;
}
sidx = sizeof (t_chunk_info) * nc;
if (sidx <= 0) {
goto fail1;
}
cidx = gdCalloc (sidx, 1);
if (cidx == NULL) {
goto fail1;
}
for (i = 0; i < nc; i++) {
if (gdGetInt (&cidx[i].offset, in) != 1) {
goto fail2;
};
if (gdGetInt (&cidx[i].size, in) != 1) {
goto fail2;
};
if (cidx[i].offset < 0 || cidx[i].size < 0)
goto fail2;
};
*chunkIdx = cidx;
};
GD2_DBG (printf ("gd2 header complete\n"));
return 1;
fail2:
gdFree(cidx);
fail1:
return 0;
}
| 1 | CVE-2016-10168 | CWE-190 | Integer Overflow or Wraparound | The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number. | Phase: Requirements
Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol.
Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
If possible, choose a language or compiler that performs automatic bounds checking.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Use libraries or frameworks that make it easier to handle numbers without unexpected consequences.
Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106]
Phase: Implementation
Strategy: Input Validation
Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.
Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values.
Phase: Implementation
Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7]
Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Phase: Implementation
Strategy: Compilation or Build Hardening
Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system. | 3,870 |
tcpdump | 1bc78d795cd5cad5525498658f414a11ea0a7e9c | print_attr_time(netdissect_options *ndo,
register const u_char *data, u_int length, u_short attr_code _U_)
{
time_t attr_time;
char string[26];
if (length != 4)
{
ND_PRINT((ndo, "ERROR: length %u != 4", length));
return;
}
ND_TCHECK2(data[0],4);
attr_time = EXTRACT_32BITS(data);
strlcpy(string, ctime(&attr_time), sizeof(string));
/* Get rid of the newline */
string[24] = '\0';
ND_PRINT((ndo, "%.24s", string));
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,548 |
linux | 9a59029bc218b48eff8b5d4dde5662fd79d3e1a8 | static void oz_usb_handle_ep_data(struct oz_usb_ctx *usb_ctx,
struct oz_usb_hdr *usb_hdr, int len)
{
struct oz_data *data_hdr = (struct oz_data *)usb_hdr;
switch (data_hdr->format) {
case OZ_DATA_F_MULTIPLE_FIXED: {
struct oz_multiple_fixed *body =
(struct oz_multiple_fixed *)data_hdr;
u8 *data = body->data;
int n;
if (!body->unit_size)
break;
n = (len - sizeof(struct oz_multiple_fixed)+1)
/ body->unit_size;
while (n--) {
oz_hcd_data_ind(usb_ctx->hport, body->endpoint,
data, body->unit_size);
data += body->unit_size;
}
}
break;
case OZ_DATA_F_ISOC_FIXED: {
struct oz_isoc_fixed *body =
(struct oz_isoc_fixed *)data_hdr;
int data_len = len-sizeof(struct oz_isoc_fixed)+1;
int unit_size = body->unit_size;
u8 *data = body->data;
int count;
int i;
if (!unit_size)
break;
count = data_len/unit_size;
for (i = 0; i < count; i++) {
oz_hcd_data_ind(usb_ctx->hport,
body->endpoint, data, unit_size);
data += unit_size;
}
}
break;
}
}
| 1 | CVE-2015-4002 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 1,339 |
Chrome | fb5dce12f0462056fc9f66967b0f7b2b7bcd88f5 | void AddMainWebResources(content::WebUIDataSource* html_source) {
html_source->AddResourcePath("media_router.js", IDR_MEDIA_ROUTER_JS);
html_source->AddResourcePath("media_router_common.css",
IDR_MEDIA_ROUTER_COMMON_CSS);
html_source->AddResourcePath("media_router.css",
IDR_MEDIA_ROUTER_CSS);
html_source->AddResourcePath("media_router_data.js",
IDR_MEDIA_ROUTER_DATA_JS);
html_source->AddResourcePath("media_router_ui_interface.js",
IDR_MEDIA_ROUTER_UI_INTERFACE_JS);
html_source->AddResourcePath("polymer_config.js",
IDR_MEDIA_ROUTER_POLYMER_CONFIG_JS);
}
| 1 | CVE-2013-6663 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 8,399 |
gdal | 148115fcc40f1651a5d15fa34c9a8c528e7147bb | static int OGRExpatUnknownEncodingHandler(
void * /* unused_encodingHandlerData */,
const XML_Char *name,
XML_Encoding *info )
{
if( EQUAL(name, "WINDOWS-1252") )
FillWINDOWS1252(info);
else if( EQUAL(name, "ISO-8859-15") )
FillISO885915(info);
else
{
CPLDebug("OGR", "Unhandled encoding %s", name);
return XML_STATUS_ERROR;
}
info->data = nullptr;
info->convert = nullptr;
info->release = nullptr;
return XML_STATUS_OK;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,182 |
libxml2 | bd0526e66a56e75a18da8c15c4750db8f801c52d | xmlParseConditionalSections(xmlParserCtxtPtr ctxt) {
int id = ctxt->input->id;
SKIP(3);
SKIP_BLANKS;
if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) {
SKIP(7);
SKIP_BLANKS;
if (RAW != '[') {
xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
xmlStopParser(ctxt);
return;
} else {
if (ctxt->input->id != id) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not in the same entity\n",
NULL, NULL);
}
NEXT;
}
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Entering INCLUDE Conditional Section\n");
}
while (((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') ||
(NXT(2) != '>'))) && (ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *check = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
xmlParseConditionalSections(ctxt);
} else if (IS_BLANK_CH(CUR)) {
NEXT;
} else if (RAW == '%') {
xmlParsePEReference(ctxt);
} else
xmlParseMarkupDecl(ctxt);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {
xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL);
break;
}
}
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Leaving INCLUDE Conditional Section\n");
}
} else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) {
int state;
xmlParserInputState instate;
int depth = 0;
SKIP(6);
SKIP_BLANKS;
if (RAW != '[') {
xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
xmlStopParser(ctxt);
return;
} else {
if (ctxt->input->id != id) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not in the same entity\n",
NULL, NULL);
}
NEXT;
}
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Entering IGNORE Conditional Section\n");
}
/*
* Parse up to the end of the conditional section
* But disable SAX event generating DTD building in the meantime
*/
state = ctxt->disableSAX;
instate = ctxt->instate;
if (ctxt->recovery == 0) ctxt->disableSAX = 1;
ctxt->instate = XML_PARSER_IGNORE;
while (((depth >= 0) && (RAW != 0)) &&
(ctxt->instate != XML_PARSER_EOF)) {
if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
depth++;
SKIP(3);
continue;
}
if ((RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) {
if (--depth >= 0) SKIP(3);
continue;
}
NEXT;
continue;
}
ctxt->disableSAX = state;
ctxt->instate = instate;
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Leaving IGNORE Conditional Section\n");
}
} else {
xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL);
xmlStopParser(ctxt);
return;
}
if (RAW == 0)
SHRINK;
if (RAW == 0) {
xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL);
} else {
if (ctxt->input->id != id) {
xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not in the same entity\n",
NULL, NULL);
}
SKIP(3);
}
} | 1 | CVE-2015-7942 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 2,301 |
php-src | 7245bff300d3fa8bacbef7897ff080a6f1c23eba?w=1 | static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC)
{
spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter);
object->u.dir.index = 0;
if (object->u.dir.dirp) {
php_stream_rewinddir(object->u.dir.dirp);
}
spl_filesystem_dir_read(object TSRMLS_CC);
}
| 1 | CVE-2016-5770 | CWE-190 | Integer Overflow or Wraparound | The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number. | Phase: Requirements
Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol.
Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
If possible, choose a language or compiler that performs automatic bounds checking.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Use libraries or frameworks that make it easier to handle numbers without unexpected consequences.
Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106]
Phase: Implementation
Strategy: Input Validation
Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.
Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values.
Phase: Implementation
Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7]
Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Phase: Implementation
Strategy: Compilation or Build Hardening
Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system. | 3,596 |
savannah | c265cad1c95b84abfd4e8d861f25926ef13b5d91 | irc_server_gnutls_callback (void *data, gnutls_session_t tls_session,
const gnutls_datum_t *req_ca, int nreq,
const gnutls_pk_algorithm_t *pk_algos,
int pk_algos_len, gnutls_retr_st *answer)
{
struct t_irc_server *server;
gnutls_retr_st tls_struct;
const gnutls_datum_t *cert_list;
gnutls_datum_t filedatum;
unsigned int cert_list_len, status;
time_t cert_time;
char *cert_path0, *cert_path1, *cert_path2, *cert_str, *hostname;
const char *weechat_dir;
int rc, ret, i, j, hostname_match;
#if LIBGNUTLS_VERSION_NUMBER >= 0x010706
gnutls_datum_t cinfo;
int rinfo;
#endif
/* make C compiler happy */
(void) req_ca;
(void) nreq;
(void) pk_algos;
(void) pk_algos_len;
rc = 0;
if (!data)
return -1;
server = (struct t_irc_server *) data;
hostname = server->current_address;
hostname = server->current_address;
hostname_match = 0;
weechat_printf (server->buffer,
_("gnutls: connected using %d-bit Diffie-Hellman shared "
"secret exchange"),
IRC_SERVER_OPTION_INTEGER (server,
IRC_SERVER_OPTION_SSL_DHKEY_SIZE));
if (gnutls_certificate_verify_peers2 (tls_session, &status) < 0)
{
weechat_printf (server->buffer,
_("%sgnutls: error while checking peer's certificate"),
weechat_prefix ("error"));
rc = -1;
}
else
{
/* some checks */
if (status & GNUTLS_CERT_INVALID)
{
weechat_printf (server->buffer,
_("%sgnutls: peer's certificate is NOT trusted"),
weechat_prefix ("error"));
rc = -1;
}
else
{
weechat_printf (server->buffer,
_("gnutls: peer's certificate is trusted"));
}
if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
{
weechat_printf (server->buffer,
_("%sgnutls: peer's certificate issuer is unknown"),
weechat_prefix ("error"));
rc = -1;
}
if (status & GNUTLS_CERT_REVOKED)
{
weechat_printf (server->buffer,
_("%sgnutls: the certificate has been revoked"),
weechat_prefix ("error"));
rc = -1;
}
/* check certificates */
if (gnutls_x509_crt_init (&cert_temp) >= 0)
{
cert_list = gnutls_certificate_get_peers (tls_session, &cert_list_len);
if (cert_list)
{
weechat_printf (server->buffer,
NG_("gnutls: receiving %d certificate",
"gnutls: receiving %d certificates",
cert_list_len),
cert_list_len);
for (i = 0, j = (int) cert_list_len; i < j; i++)
{
if (gnutls_x509_crt_import (cert_temp, &cert_list[i], GNUTLS_X509_FMT_DER) >= 0)
{
/* checking if hostname matches in the first certificate */
if (i == 0 && gnutls_x509_crt_check_hostname (cert_temp, hostname) != 0)
{
hostname_match = 1;
}
#if LIBGNUTLS_VERSION_NUMBER >= 0x010706
/* displaying infos about certificate */
#if LIBGNUTLS_VERSION_NUMBER < 0x020400
rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_X509_CRT_ONELINE, &cinfo);
#else
rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_CRT_PRINT_ONELINE, &cinfo);
#endif
if (rinfo == 0)
{
weechat_printf (server->buffer,
_(" - certificate[%d] info:"), i + 1);
weechat_printf (server->buffer,
" - %s", cinfo.data);
gnutls_free (cinfo.data);
}
#endif
/* check expiration date */
cert_time = gnutls_x509_crt_get_expiration_time (cert_temp);
if (cert_time < time(NULL))
{
weechat_printf (server->buffer,
_("%sgnutls: certificate has expired"),
weechat_prefix ("error"));
rc = -1;
}
/* check expiration date */
cert_time = gnutls_x509_crt_get_activation_time (cert_temp);
if (cert_time > time(NULL))
{
weechat_printf (server->buffer,
_("%sgnutls: certificate is not yet activated"),
weechat_prefix ("error"));
rc = -1;
}
}
}
if (hostname_match == 0)
{
weechat_printf (server->buffer,
_("%sgnutls: the hostname in the "
"certificate does NOT match \"%s\""),
weechat_prefix ("error"), hostname);
rc = -1;
}
}
}
}
/* using client certificate if it exists */
cert_path0 = (char *) IRC_SERVER_OPTION_STRING(server,
IRC_SERVER_OPTION_SSL_CERT);
if (cert_path0 && cert_path0[0])
{
weechat_dir = weechat_info_get ("weechat_dir", "");
cert_path1 = weechat_string_replace (cert_path0, "%h", weechat_dir);
cert_path2 = (cert_path1) ?
weechat_string_expand_home (cert_path1) : NULL;
if (cert_path2)
{
cert_str = weechat_file_get_content (cert_path2);
if (cert_str)
{
weechat_printf (server->buffer,
_("gnutls: sending one certificate"));
filedatum.data = (unsigned char *) cert_str;
filedatum.size = strlen (cert_str);
/* certificate */
gnutls_x509_crt_init (&server->tls_cert);
gnutls_x509_crt_import (server->tls_cert, &filedatum,
GNUTLS_X509_FMT_PEM);
/* key */
gnutls_x509_privkey_init (&server->tls_cert_key);
ret = gnutls_x509_privkey_import (server->tls_cert_key,
&filedatum,
GNUTLS_X509_FMT_PEM);
if (ret < 0)
{
ret = gnutls_x509_privkey_import_pkcs8 (server->tls_cert_key,
&filedatum,
GNUTLS_X509_FMT_PEM,
NULL,
GNUTLS_PKCS_PLAIN);
}
if (ret < 0)
{
weechat_printf (server->buffer,
_("%sgnutls: invalid certificate \"%s\", "
"error: %s"),
weechat_prefix ("error"), cert_path2,
gnutls_strerror (ret));
rc = -1;
}
else
{
tls_struct.type = GNUTLS_CRT_X509;
tls_struct.ncerts = 1;
tls_struct.deinit_all = 0;
tls_struct.cert.x509 = &server->tls_cert;
tls_struct.key.x509 = server->tls_cert_key;
#if LIBGNUTLS_VERSION_NUMBER >= 0x010706
/* client certificate info */
#if LIBGNUTLS_VERSION_NUMBER < 0x020400
rinfo = gnutls_x509_crt_print (server->tls_cert,
GNUTLS_X509_CRT_ONELINE,
&cinfo);
#else
rinfo = gnutls_x509_crt_print (server->tls_cert,
GNUTLS_CRT_PRINT_ONELINE,
&cinfo);
#endif
if (rinfo == 0)
{
weechat_printf (server->buffer,
_(" - client certificate info (%s):"),
cert_path2);
weechat_printf (server->buffer, " - %s", cinfo.data);
gnutls_free (cinfo.data);
}
#endif
memcpy (answer, &tls_struct, sizeof (gnutls_retr_st));
free (cert_str);
}
}
else
{
weechat_printf (server->buffer,
_("%sgnutls: unable to read certifcate \"%s\""),
weechat_prefix ("error"), cert_path2);
}
}
if (cert_path1)
free (cert_path1);
if (cert_path2)
free (cert_path2);
}
/* an error should stop the handshake unless the user doesn't care */
return rc;
}
| 1 | CVE-2011-1428 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 1,295 |
gpac | 55a183e6b8602369c04ea3836e05436a79fbc7f8 | GF_Node *gf_bifs_dec_node(GF_BifsDecoder * codec, GF_BitStream *bs, u32 NDT_Tag)
{
u32 nodeID, NDTBits, node_type, node_tag, ProtoID, BVersion;
Bool skip_init, reset_qp14;
GF_Node *new_node;
GF_Err e;
GF_Proto *proto;
void SetupConditional(GF_BifsDecoder *codec, GF_Node *node);
//to store the UseName
char name[1000];
#if 0
/*should only happen with inputSensor, in which case this is BAAAAD*/
if (!codec->info) {
codec->LastError = GF_BAD_PARAM;
return NULL;
}
#endif
BVersion = GF_BIFS_V1;
/*this is a USE statement*/
if (gf_bs_read_int(bs, 1)) {
nodeID = 1 + gf_bs_read_int(bs, codec->info->config.NodeIDBits);
/*NULL node is encoded as USE with ID = all bits to 1*/
if (nodeID == (u32) (1<<codec->info->config.NodeIDBits))
return NULL;
//find node
new_node = gf_sg_find_node(codec->current_graph, nodeID);
//check node is allowed for the given NDT
if (new_node && !gf_node_in_table(new_node, NDT_Tag)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[BIFS] Node %s not allowed as field/child of NDT type %d\n", gf_node_get_class_name(new_node), NDT_Tag));
codec->LastError = GF_SG_UNKNOWN_NODE;
return NULL;
}
if (!new_node) {
codec->LastError = GF_SG_UNKNOWN_NODE;
} else {
/*restore QP14 length*/
switch (gf_node_get_tag(new_node)) {
case TAG_MPEG4_Coordinate:
{
u32 nbCoord = ((M_Coordinate *)new_node)->point.count;
gf_bifs_dec_qp14_enter(codec, GF_TRUE);
gf_bifs_dec_qp14_set_length(codec, nbCoord);
gf_bifs_dec_qp14_enter(codec, GF_FALSE);
}
break;
case TAG_MPEG4_Coordinate2D:
{
u32 nbCoord = ((M_Coordinate2D *)new_node)->point.count;
gf_bifs_dec_qp14_enter(codec, GF_TRUE);
gf_bifs_dec_qp14_set_length(codec, nbCoord);
gf_bifs_dec_qp14_enter(codec, GF_FALSE);
}
break;
}
}
return new_node;
}
//this is a new node
nodeID = 0;
name[0] = 0;
node_tag = 0;
proto = NULL;
//browse all node groups
while (1) {
NDTBits = gf_bifs_get_ndt_bits(NDT_Tag, BVersion);
/*this happens in replacescene where no top-level node is present (externProto)*/
if ((BVersion==1) && (NDTBits > 8 * gf_bs_available(bs)) ) {
codec->LastError = GF_OK;
return NULL;
}
node_type = gf_bs_read_int(bs, NDTBits);
if (node_type) break;
//increment BIFS version
BVersion += 1;
//not supported
if (BVersion > GF_BIFS_NUM_VERSION) {
codec->LastError = GF_BIFS_UNKNOWN_VERSION;
return NULL;
}
}
if (BVersion==2 && node_type==1) {
ProtoID = gf_bs_read_int(bs, codec->info->config.ProtoIDBits);
/*look in current graph for the proto - this may be a proto graph*/
proto = gf_sg_find_proto(codec->current_graph, ProtoID, NULL);
/*this was in proto so look in main scene*/
if (!proto && codec->current_graph != codec->scenegraph)
proto = gf_sg_find_proto(codec->scenegraph, ProtoID, NULL);
if (!proto) {
codec->LastError = GF_SG_UNKNOWN_NODE;
return NULL;
}
} else {
node_tag = gf_bifs_ndt_get_node_type(NDT_Tag, node_type, BVersion);
}
/*special handling of 3D mesh*/
if ((node_tag == TAG_MPEG4_IndexedFaceSet) && codec->info->config.Use3DMeshCoding) {
if (gf_bs_read_int(bs, 1)) {
/*nodeID = 1 + */gf_bs_read_int(bs, codec->info->config.NodeIDBits);
if (codec->UseName) gf_bifs_dec_name(bs, name, 1000);
}
/*parse the 3DMesh node*/
return NULL;
}
/*unknown node*/
if (!node_tag && !proto) {
codec->LastError = GF_SG_UNKNOWN_NODE;
return NULL;
}
/*DEF'd flag*/
if (gf_bs_read_int(bs, 1)) {
if (!codec->info->config.NodeIDBits) {
codec->LastError = GF_NON_COMPLIANT_BITSTREAM;
return NULL;
}
nodeID = 1 + gf_bs_read_int(bs, codec->info->config.NodeIDBits);
if (codec->UseName) gf_bifs_dec_name(bs, name, 1000);
}
new_node = NULL;
skip_init = GF_FALSE;
/*don't check node IDs duplicate since VRML may use them...*/
#if 0
/*if a node with same DEF is already in the scene, use it
we don't do that in memory mode because commands may force replacement
of a node with a new node with same ID, and we want to be able to dump it (otherwise we would
dump a USE)*/
if (nodeID && !codec->dec_memory_mode) {
new_node = gf_sg_find_node(codec->current_graph, nodeID);
if (new_node) {
if (proto) {
if ((gf_node_get_tag(new_node) != TAG_ProtoNode) || (gf_node_get_proto(new_node) != proto)) {
codec->LastError = GF_NON_COMPLIANT_BITSTREAM;
return NULL;
}
skip_init = 1;
} else {
if (gf_node_get_tag(new_node) != node_tag) {
codec->LastError = GF_NON_COMPLIANT_BITSTREAM;
return NULL;
}
skip_init = 1;
}
}
}
if (!new_node)
#endif
{
if (proto) {
/*create proto interface*/
new_node = gf_sg_proto_create_instance(codec->current_graph, proto);
//don't init protos unless externProto (in which case we want init for hardcoded protos)
if (! proto->ExternProto.count) skip_init = GF_TRUE;
} else {
new_node = gf_node_new(codec->current_graph, node_tag);
}
}
if (!new_node) {
codec->LastError = GF_NOT_SUPPORTED;
return NULL;
}
/*update default time fields except in proto parsing*/
if (!codec->pCurrentProto) UpdateTimeNode(codec, new_node);
/*nodes are only init outside protos, nodes internal to protos are never intialized */
else skip_init = GF_TRUE;
/*if coords were not stored for QP14 before coding this node, reset QP14 it when leaving*/
reset_qp14 = !codec->coord_stored;
/*QP 14 is a special quant mode for IndexFace/Line(2D)Set to quantize the
coordonate(2D) child, based on the first field parsed
we must check the type of the node and notfy the QP*/
switch (node_tag) {
case TAG_MPEG4_Coordinate:
case TAG_MPEG4_Coordinate2D:
gf_bifs_dec_qp14_enter(codec, GF_TRUE);
}
if (gf_bs_read_int(bs, 1)) {
e = gf_bifs_dec_node_mask(codec, bs, new_node, proto ? GF_TRUE : GF_FALSE);
} else {
e = gf_bifs_dec_node_list(codec, bs, new_node, proto ? GF_TRUE : GF_FALSE);
}
if (codec->coord_stored && reset_qp14)
gf_bifs_dec_qp14_reset(codec);
if (e) {
codec->LastError = e;
/*register*/
gf_node_register(new_node, NULL);
/*unregister (deletes)*/
gf_node_unregister(new_node, NULL);
return NULL;
}
/*VRML: "The transformation hierarchy shall be a directed acyclic graph; results are undefined if a node
in the transformation hierarchy is its own ancestor"
that's good, because the scene graph can't handle cyclic graphs (destroy will never be called).
We therefore only register the node once parsed*/
if (nodeID) {
if (strlen(name)) {
gf_node_set_id(new_node, nodeID, name);
} else {
gf_node_set_id(new_node, nodeID, NULL);
}
}
if (!skip_init)
gf_node_init(new_node);
switch (node_tag) {
case TAG_MPEG4_Coordinate:
case TAG_MPEG4_Coordinate2D:
gf_bifs_dec_qp14_enter(codec, GF_FALSE);
break;
case TAG_MPEG4_Script:
/*load script if in main graph (useless to load in proto declaration)*/
if (codec->scenegraph == codec->current_graph) {
gf_sg_script_load(new_node);
}
break;
/*conditionals must be init*/
case TAG_MPEG4_Conditional:
SetupConditional(codec, new_node);
break;
}
/*proto is initialized upon the first traversal to have the same behavior as wth BT/XMT loading*/
#if 0
/*if new node is a proto and we're in the top scene, load proto code*/
if (proto && (codec->scenegraph == codec->current_graph)) {
codec->LastError = gf_sg_proto_load_code(new_node);
}
#endif
return new_node;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,405 |
gnutls | 8dc2822966f64dd9cf7dde9c7aacd80d49d3ffe5 | is_read_comp_null (record_parameters_st * record_params)
{
if (record_params->compression_algorithm == GNUTLS_COMP_NULL)
return 0;
return 1;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,016 |
linux | fa40d9734a57bcbfa79a280189799f76c88f7bb0 | static bool tipc_crypto_key_rcv(struct tipc_crypto *rx, struct tipc_msg *hdr)
{
struct tipc_crypto *tx = tipc_net(rx->net)->crypto_tx;
struct tipc_aead_key *skey = NULL;
u16 key_gen = msg_key_gen(hdr);
u16 size = msg_data_sz(hdr);
u8 *data = msg_data(hdr);
spin_lock(&rx->lock);
if (unlikely(rx->skey || (key_gen == rx->key_gen && rx->key.keys))) {
pr_err("%s: key existed <%p>, gen %d vs %d\n", rx->name,
rx->skey, key_gen, rx->key_gen);
goto exit;
}
/* Allocate memory for the key */
skey = kmalloc(size, GFP_ATOMIC);
if (unlikely(!skey)) {
pr_err("%s: unable to allocate memory for skey\n", rx->name);
goto exit;
}
/* Copy key from msg data */
skey->keylen = ntohl(*((__be32 *)(data + TIPC_AEAD_ALG_NAME)));
memcpy(skey->alg_name, data, TIPC_AEAD_ALG_NAME);
memcpy(skey->key, data + TIPC_AEAD_ALG_NAME + sizeof(__be32),
skey->keylen);
/* Sanity check */
if (unlikely(size != tipc_aead_key_size(skey))) {
kfree(skey);
skey = NULL;
goto exit;
}
rx->key_gen = key_gen;
rx->skey_mode = msg_key_mode(hdr);
rx->skey = skey;
rx->nokey = 0;
mb(); /* for nokey flag */
exit:
spin_unlock(&rx->lock);
/* Schedule the key attaching on this crypto */
if (likely(skey && queue_delayed_work(tx->wq, &rx->work, 0)))
return true;
return false;
} | 1 | CVE-2021-43267 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 4,277 |
evince | 350404c76dc8601e2cdd2636490e2afc83d3090e | dvi_document_get_n_pages (EvDocument *document)
{
DviDocument *dvi_document = DVI_DOCUMENT (document);
return dvi_document->context->npages;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,731 |
linux | 54d83fc74aa9ec72794373cb47432c5f7fb1a309 | mark_source_chains(const struct xt_table_info *newinfo,
unsigned int valid_hooks, void *entry0)
{
unsigned int hook;
/* No recursion; use packet counter to save back ptrs (reset
to 0 as we leave), and comefrom to save source hook bitmask */
for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) {
unsigned int pos = newinfo->hook_entry[hook];
struct ip6t_entry *e = (struct ip6t_entry *)(entry0 + pos);
if (!(valid_hooks & (1 << hook)))
continue;
/* Set initial back pointer. */
e->counters.pcnt = pos;
for (;;) {
const struct xt_standard_target *t
= (void *)ip6t_get_target_c(e);
int visited = e->comefrom & (1 << hook);
if (e->comefrom & (1 << NF_INET_NUMHOOKS)) {
pr_err("iptables: loop hook %u pos %u %08X.\n",
hook, pos, e->comefrom);
return 0;
}
e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS));
/* Unconditional return/END. */
if ((e->target_offset == sizeof(struct ip6t_entry) &&
(strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < 0 &&
unconditional(&e->ipv6)) || visited) {
unsigned int oldpos, size;
if ((strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < -NF_MAX_VERDICT - 1) {
duprintf("mark_source_chains: bad "
"negative verdict (%i)\n",
t->verdict);
return 0;
}
/* Return: backtrack through the last
big jump. */
do {
e->comefrom ^= (1<<NF_INET_NUMHOOKS);
#ifdef DEBUG_IP_FIREWALL_USER
if (e->comefrom
& (1 << NF_INET_NUMHOOKS)) {
duprintf("Back unset "
"on hook %u "
"rule %u\n",
hook, pos);
}
#endif
oldpos = pos;
pos = e->counters.pcnt;
e->counters.pcnt = 0;
/* We're at the start. */
if (pos == oldpos)
goto next;
e = (struct ip6t_entry *)
(entry0 + pos);
} while (oldpos == pos + e->next_offset);
/* Move along one */
size = e->next_offset;
e = (struct ip6t_entry *)
(entry0 + pos + size);
e->counters.pcnt = pos;
pos += size;
} else {
int newpos = t->verdict;
if (strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0 &&
newpos >= 0) {
if (newpos > newinfo->size -
sizeof(struct ip6t_entry)) {
duprintf("mark_source_chains: "
"bad verdict (%i)\n",
newpos);
return 0;
}
/* This a jump; chase it. */
duprintf("Jump rule %u -> %u\n",
pos, newpos);
} else {
/* ... this is a fallthru */
newpos = pos + e->next_offset;
}
e = (struct ip6t_entry *)
(entry0 + newpos);
e->counters.pcnt = pos;
pos = newpos;
}
}
next:
duprintf("Finished chain %u\n", hook);
}
return 1;
}
| 1 | CVE-2016-3134 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 630 |
FFmpeg | 454a11a1c9c686c78aa97954306fb63453299760 | static void add_bytes_c(uint8_t *dst, uint8_t *src, int w){
long i;
for(i=0; i<=w-sizeof(long); i+=sizeof(long)){
long a = *(long*)(src+i);
long b = *(long*)(dst+i);
*(long*)(dst+i) = ((a&pb_7f) + (b&pb_7f)) ^ ((a^b)&pb_80);
}
for(; i<w; i++)
dst[i+0] += src[i+0];
}
| 1 | CVE-2013-7010 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 7,054 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.