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
|
---|---|---|---|---|---|---|---|---|---|
php-src | b6f13a5ef9d6280cf984826a5de012a32c396cd4?w=1 | PHP_FUNCTION(imageaffinematrixget)
{
double affine[6];
long type;
zval *options = NULL;
zval **tmp;
int res = GD_FALSE, i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &type, &options) == FAILURE) {
return;
}
switch((gdAffineStandardMatrix)type) {
case GD_AFFINE_TRANSLATE:
case GD_AFFINE_SCALE: {
double x, y;
if (!options || Z_TYPE_P(options) != IS_ARRAY) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array expected as options");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(options), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_DOUBLE) {
zval dval;
dval = **tmp;
zval_copy_ctor(&dval);
convert_to_double(&dval);
x = Z_DVAL(dval);
} else {
x = Z_DVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(options), "y", sizeof("y"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_DOUBLE) {
zval dval;
dval = **tmp;
zval_copy_ctor(&dval);
convert_to_double(&dval);
y = Z_DVAL(dval);
} else {
y = Z_DVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (type == GD_AFFINE_TRANSLATE) {
res = gdAffineTranslate(affine, x, y);
} else {
res = gdAffineScale(affine, x, y);
}
break;
}
case GD_AFFINE_ROTATE:
case GD_AFFINE_SHEAR_HORIZONTAL:
case GD_AFFINE_SHEAR_VERTICAL: {
double angle;
if (!options) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number is expected as option");
RETURN_FALSE;
}
if(Z_TYPE_P(options) != IS_DOUBLE) {
zval dval;
dval = *options;
zval_copy_ctor(&dval);
convert_to_double(&dval);
angle = Z_DVAL(dval);
} else {
angle = Z_DVAL_P(options);
}
if (type == GD_AFFINE_SHEAR_HORIZONTAL) {
res = gdAffineShearHorizontal(affine, angle);
} else if (type == GD_AFFINE_SHEAR_VERTICAL) {
res = gdAffineShearVertical(affine, angle);
} else {
res = gdAffineRotate(affine, angle);
}
break;
}
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %li", type);
RETURN_FALSE;
}
if (res == GD_FALSE) {
RETURN_FALSE;
} else {
array_init(return_value);
for (i = 0; i < 6; i++) {
add_index_double(return_value, i, affine[i]);
}
}
}
| 1 | CVE-2016-7126 | 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). | 3,907 |
libgit2 | 58a6fe94cb851f71214dbefac3f9bffee437d6fe | static int index_conflict_to_reuc(git_index *index, const char *path)
{
const git_index_entry *conflict_entries[3];
int ancestor_mode, our_mode, their_mode;
git_oid const *ancestor_oid, *our_oid, *their_oid;
int ret;
if ((ret = git_index_conflict_get(&conflict_entries[0],
&conflict_entries[1], &conflict_entries[2], index, path)) < 0)
return ret;
ancestor_mode = conflict_entries[0] == NULL ? 0 : conflict_entries[0]->mode;
our_mode = conflict_entries[1] == NULL ? 0 : conflict_entries[1]->mode;
their_mode = conflict_entries[2] == NULL ? 0 : conflict_entries[2]->mode;
ancestor_oid = conflict_entries[0] == NULL ? NULL : &conflict_entries[0]->id;
our_oid = conflict_entries[1] == NULL ? NULL : &conflict_entries[1]->id;
their_oid = conflict_entries[2] == NULL ? NULL : &conflict_entries[2]->id;
if ((ret = git_index_reuc_add(index, path, ancestor_mode, ancestor_oid,
our_mode, our_oid, their_mode, their_oid)) >= 0)
ret = git_index_conflict_remove(index, path);
return ret;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,528 |
Android | d77f1999ecece56c1cbb333f4ddc26f0b5bac2c5 | bool btif_get_device_type(const BD_ADDR bd_addr, int *p_device_type)
{
if (p_device_type == NULL)
return FALSE;
bt_bdaddr_t bda;
bdcpy(bda.address, bd_addr);
bdstr_t bd_addr_str;
bdaddr_to_string(&bda, bd_addr_str, sizeof(bd_addr_str));
if (!btif_config_get_int(bd_addr_str, "DevType", p_device_type))
return FALSE;
LOG_DEBUG(LOG_TAG, "%s: Device [%s] type %d", __FUNCTION__, bd_addr_str, *p_device_type);
return TRUE;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,149 |
Android | 04839626ed859623901ebd3a5fd483982186b59d | const SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const
{
if (idx < 0)
return 0;
if (idx >= m_void_element_count)
return 0;
return m_void_elements + idx;
}
| 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,170 |
samurai | e84b6d99c85043fa1ba54851ee500540ec206918 | writefile(const char *name, struct string *s)
{
FILE *f;
int ret;
f = fopen(name, "w");
if (!f) {
warn("open %s:", name);
return -1;
}
ret = 0;
if (s && (fwrite(s->s, 1, s->n, f) != s->n || fflush(f) != 0)) {
warn("write %s:", name);
ret = -1;
}
fclose(f);
return ret;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,260 |
ImageMagick | a1142af44f61c038ad3eccc099c5b9548b507846 | static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
BMPInfo
bmp_info;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
offset,
profile_data,
profile_size,
start_position;
MemoryInfo
*pixel_info;
Quantum
index;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bit,
bytes_per_line,
length;
ssize_t
count,
y;
unsigned char
magick[12],
*pixels;
unsigned int
blue,
green,
offset_bits,
red;
/*
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);
}
/*
Determine if this a BMP file.
*/
(void) memset(&bmp_info,0,sizeof(bmp_info));
bmp_info.ba_offset=0;
start_position=0;
offset_bits=0;
count=ReadBlob(image,2,magick);
if (count != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
PixelInfo
quantum_bits;
PixelPacket
shift;
/*
Verify BMP identifier.
*/
start_position=TellBlob(image)-2;
bmp_info.ba_offset=0;
while (LocaleNCompare((char *) magick,"BA",2) == 0)
{
bmp_info.file_size=ReadBlobLSBLong(image);
bmp_info.ba_offset=ReadBlobLSBLong(image);
bmp_info.offset_bits=ReadBlobLSBLong(image);
count=ReadBlob(image,2,magick);
if (count != 2)
break;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c",
magick[0],magick[1]);
if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) &&
(LocaleNCompare((char *) magick,"CI",2) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bmp_info.file_size=ReadBlobLSBLong(image);
(void) ReadBlobLSBLong(image);
bmp_info.offset_bits=ReadBlobLSBLong(image);
bmp_info.size=ReadBlobLSBLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u",
bmp_info.size);
profile_data=0;
profile_size=0;
if (bmp_info.size == 12)
{
/*
OS/2 BMP image file.
*/
(void) CopyMagickString(image->magick,"BMP2",MagickPathExtent);
bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));
bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));
bmp_info.planes=ReadBlobLSBShort(image);
bmp_info.bits_per_pixel=ReadBlobLSBShort(image);
bmp_info.x_pixels=0;
bmp_info.y_pixels=0;
bmp_info.number_colors=0;
bmp_info.compression=BI_RGB;
bmp_info.image_size=0;
bmp_info.alpha_mask=0;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format: OS/2 Bitmap");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Geometry: %.20gx%.20g",(double) bmp_info.width,(double)
bmp_info.height);
}
}
else
{
/*
Microsoft Windows BMP image file.
*/
if (bmp_info.size < 40)
ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError");
bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);
bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);
bmp_info.planes=ReadBlobLSBShort(image);
bmp_info.bits_per_pixel=ReadBlobLSBShort(image);
bmp_info.compression=ReadBlobLSBLong(image);
bmp_info.image_size=ReadBlobLSBLong(image);
bmp_info.x_pixels=ReadBlobLSBLong(image);
bmp_info.y_pixels=ReadBlobLSBLong(image);
bmp_info.number_colors=ReadBlobLSBLong(image);
if ((MagickSizeType) bmp_info.number_colors > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
bmp_info.colors_important=ReadBlobLSBLong(image);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format: MS Windows bitmap");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Geometry: %.20gx%.20g",(double) bmp_info.width,(double)
bmp_info.height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel);
switch (bmp_info.compression)
{
case BI_RGB:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_RGB");
break;
}
case BI_RLE4:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_RLE4");
break;
}
case BI_RLE8:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_RLE8");
break;
}
case BI_BITFIELDS:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_BITFIELDS");
break;
}
case BI_PNG:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_PNG");
break;
}
case BI_JPEG:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_JPEG");
break;
}
default:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: UNKNOWN (%u)",bmp_info.compression);
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %u",bmp_info.number_colors);
}
if ((bmp_info.size > 40) || (bmp_info.compression == BI_BITFIELDS))
{
bmp_info.red_mask=ReadBlobLSBLong(image);
bmp_info.green_mask=ReadBlobLSBLong(image);
bmp_info.blue_mask=ReadBlobLSBLong(image);
}
if (bmp_info.size > 40)
{
double
gamma;
/*
Read color management information.
*/
bmp_info.alpha_mask=ReadBlobLSBLong(image);
bmp_info.colorspace=ReadBlobLSBSignedLong(image);
/*
Decode 2^30 fixed point formatted CIE primaries.
*/
# define BMP_DENOM ((double) 0x40000000)
bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+
bmp_info.red_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.red_primary.x*=gamma;
bmp_info.red_primary.y*=gamma;
image->chromaticity.red_primary.x=bmp_info.red_primary.x;
image->chromaticity.red_primary.y=bmp_info.red_primary.y;
gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+
bmp_info.green_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.green_primary.x*=gamma;
bmp_info.green_primary.y*=gamma;
image->chromaticity.green_primary.x=bmp_info.green_primary.x;
image->chromaticity.green_primary.y=bmp_info.green_primary.y;
gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+
bmp_info.blue_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.blue_primary.x*=gamma;
bmp_info.blue_primary.y*=gamma;
image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;
image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;
/*
Decode 16^16 fixed point formatted gamma_scales.
*/
bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;
bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;
bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;
/*
Compute a single gamma from the BMP 3-channel gamma.
*/
image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+
bmp_info.gamma_scale.z)/3.0;
}
else
(void) CopyMagickString(image->magick,"BMP3",MagickPathExtent);
if (bmp_info.size > 108)
{
size_t
intent;
/*
Read BMP Version 5 color management information.
*/
intent=ReadBlobLSBLong(image);
switch ((int) intent)
{
case LCS_GM_BUSINESS:
{
image->rendering_intent=SaturationIntent;
break;
}
case LCS_GM_GRAPHICS:
{
image->rendering_intent=RelativeIntent;
break;
}
case LCS_GM_IMAGES:
{
image->rendering_intent=PerceptualIntent;
break;
}
case LCS_GM_ABS_COLORIMETRIC:
{
image->rendering_intent=AbsoluteIntent;
break;
}
}
profile_data=(MagickOffsetType)ReadBlobLSBLong(image);
profile_size=(MagickOffsetType)ReadBlobLSBLong(image);
(void) ReadBlobLSBLong(image); /* Reserved byte */
}
}
if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"LengthAndFilesizeDoNotMatch","`%s'",image->filename);
else
if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'",
image->filename);
if (bmp_info.width <= 0)
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
if (bmp_info.height == 0)
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
if (bmp_info.planes != 1)
ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne");
if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&
(bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&
(bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))
ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel");
if (bmp_info.bits_per_pixel < 16 &&
bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))
ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors");
if ((bmp_info.compression == BI_RLE8) && (bmp_info.bits_per_pixel != 8))
ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel");
if ((bmp_info.compression == BI_RLE4) && (bmp_info.bits_per_pixel != 4))
ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel");
if ((bmp_info.compression == BI_BITFIELDS) && (bmp_info.bits_per_pixel < 16))
ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel");
switch (bmp_info.compression)
{
case BI_RGB:
image->compression=NoCompression;
break;
case BI_RLE8:
case BI_RLE4:
image->compression=RLECompression;
break;
case BI_BITFIELDS:
break;
case BI_JPEG:
ThrowReaderException(CoderError,"JPEGCompressNotSupported");
case BI_PNG:
ThrowReaderException(CoderError,"PNGCompressNotSupported");
default:
ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
}
image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);
image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);
image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;
image->alpha_trait=((bmp_info.alpha_mask != 0) &&
(bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait :
UndefinedPixelTrait;
if (bmp_info.bits_per_pixel < 16)
{
size_t
one;
image->storage_class=PseudoClass;
image->colors=bmp_info.number_colors;
one=1;
if (image->colors == 0)
image->colors=one << bmp_info.bits_per_pixel;
}
image->resolution.x=(double) bmp_info.x_pixels/100.0;
image->resolution.y=(double) bmp_info.y_pixels/100.0;
image->units=PixelsPerCentimeterResolution;
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));
if (image->storage_class == PseudoClass)
{
unsigned char
*bmp_colormap;
size_t
packet_size;
/*
Read BMP raster colormap.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading colormap of %.20g colors",(double) image->colors);
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
image->colors,4*sizeof(*bmp_colormap));
if (bmp_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if ((bmp_info.size == 12) || (bmp_info.size == 64))
packet_size=3;
else
packet_size=4;
offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);
if (offset < 0)
{
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,packet_size*image->colors,bmp_colormap);
if (count != (ssize_t) (packet_size*image->colors))
{
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
p=bmp_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++);
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++);
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++);
if (packet_size == 4)
p++;
}
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
}
/*
Read image data.
*/
if (bmp_info.offset_bits == offset_bits)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
offset_bits=bmp_info.offset_bits;
offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (bmp_info.compression == BI_RLE4)
bmp_info.bits_per_pixel<<=1;
bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);
length=(size_t) bytes_per_line*image->rows;
if ((MagickSizeType) (length/256) > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
if ((bmp_info.compression == BI_RGB) ||
(bmp_info.compression == BI_BITFIELDS))
{
pixel_info=AcquireVirtualMemory(image->rows,
MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading pixels (%.20g bytes)",(double) length);
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
}
else
{
/*
Convert run-length encoded raster pixels.
*/
pixel_info=AcquireVirtualMemory(image->rows,
MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
status=DecodeImage(image,bmp_info.compression,pixels,
image->columns*image->rows);
if (status == MagickFalse)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnableToRunlengthDecodeImage");
}
}
/*
Convert BMP raster image to pixel packets.
*/
if (bmp_info.compression == BI_RGB)
{
/*
We should ignore the alpha value in BMP3 files but there have been
reports about 32 bit files with alpha. We do a quick check to see if
the alpha channel contains a value that is not zero (default value).
If we find a non zero value we asume the program that wrote the file
wants to use the alpha channel.
*/
if ((image->alpha_trait == UndefinedPixelTrait) &&
(bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32))
{
bytes_per_line=4*(image->columns);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (*(p+3) != 0)
{
image->alpha_trait=BlendPixelTrait;
y=-1;
break;
}
p+=4;
}
}
}
bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ?
0xff000000U : 0U;
bmp_info.red_mask=0x00ff0000U;
bmp_info.green_mask=0x0000ff00U;
bmp_info.blue_mask=0x000000ffU;
if (bmp_info.bits_per_pixel == 16)
{
/*
RGB555.
*/
bmp_info.red_mask=0x00007c00U;
bmp_info.green_mask=0x000003e0U;
bmp_info.blue_mask=0x0000001fU;
}
}
(void) memset(&shift,0,sizeof(shift));
(void) memset(&quantum_bits,0,sizeof(quantum_bits));
if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))
{
register unsigned int
sample;
/*
Get shift and quantum bits info from bitfield masks.
*/
if (bmp_info.red_mask != 0)
while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)
{
shift.red++;
if (shift.red >= 32U)
break;
}
if (bmp_info.green_mask != 0)
while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)
{
shift.green++;
if (shift.green >= 32U)
break;
}
if (bmp_info.blue_mask != 0)
while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)
{
shift.blue++;
if (shift.blue >= 32U)
break;
}
if (bmp_info.alpha_mask != 0)
while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0)
{
shift.alpha++;
if (shift.alpha >= 32U)
break;
}
sample=shift.red;
while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.red=(MagickRealType) (sample-shift.red);
sample=shift.green;
while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.green=(MagickRealType) (sample-shift.green);
sample=shift.blue;
while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.blue=(MagickRealType) (sample-shift.blue);
sample=shift.alpha;
while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.alpha=(MagickRealType) (sample-shift.alpha);
}
switch (bmp_info.bits_per_pixel)
{
case 1:
{
/*
Convert bitmap scanline.
*/
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (image->columns % 8); bit++)
{
index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
break;
}
case 4:
{
/*
Convert PseudoColor scanline.
*/
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index,
exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 2) != 0)
{
ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index,
exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
x++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
break;
}
case 8:
{
/*
Convert PseudoColor scanline.
*/
if ((bmp_info.compression == BI_RLE8) ||
(bmp_info.compression == BI_RLE4))
bytes_per_line=image->columns;
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=(ssize_t) image->columns; x != 0; --x)
{
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
break;
}
case 16:
{
unsigned int
alpha,
pixel;
/*
Convert bitfield encoded 16-bit PseudoColor scanline.
*/
if ((bmp_info.compression != BI_RGB) &&
(bmp_info.compression != BI_BITFIELDS))
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnrecognizedImageCompression");
}
bytes_per_line=2*(image->columns+image->columns % 2);
image->storage_class=DirectClass;
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(unsigned int) (*p++);
pixel|=(*p++) << 8;
red=((pixel & bmp_info.red_mask) << shift.red) >> 16;
if (quantum_bits.red == 5)
red|=((red & 0xe000) >> 5);
if (quantum_bits.red <= 8)
red|=((red & 0xff00) >> 8);
green=((pixel & bmp_info.green_mask) << shift.green) >> 16;
if (quantum_bits.green == 5)
green|=((green & 0xe000) >> 5);
if (quantum_bits.green == 6)
green|=((green & 0xc000) >> 6);
if (quantum_bits.green <= 8)
green|=((green & 0xff00) >> 8);
blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;
if (quantum_bits.blue == 5)
blue|=((blue & 0xe000) >> 5);
if (quantum_bits.blue <= 8)
blue|=((blue & 0xff00) >> 8);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
if (quantum_bits.alpha <= 8)
alpha|=((alpha & 0xff00) >> 8);
SetPixelAlpha(image,ScaleShortToQuantum(
(unsigned short) alpha),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 24:
{
/*
Convert DirectColor scanline.
*/
bytes_per_line=4*((image->columns*24+31)/32);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 32:
{
/*
Convert bitfield encoded DirectColor scanline.
*/
if ((bmp_info.compression != BI_RGB) &&
(bmp_info.compression != BI_BITFIELDS))
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnrecognizedImageCompression");
}
bytes_per_line=4*(image->columns);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
unsigned int
alpha,
pixel;
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(unsigned int) (*p++);
pixel|=((unsigned int) *p++ << 8);
pixel|=((unsigned int) *p++ << 16);
pixel|=((unsigned int) *p++ << 24);
red=((pixel & bmp_info.red_mask) << shift.red) >> 16;
if (quantum_bits.red == 8)
red|=(red >> 8);
green=((pixel & bmp_info.green_mask) << shift.green) >> 16;
if (quantum_bits.green == 8)
green|=(green >> 8);
blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;
if (quantum_bits.blue == 8)
blue|=(blue >> 8);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
if (quantum_bits.alpha == 8)
alpha|=(alpha >> 8);
SetPixelAlpha(image,ScaleShortToQuantum(
(unsigned short) alpha),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
default:
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (y > 0)
break;
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if (bmp_info.height < 0)
{
Image
*flipped_image;
/*
Correct image orientation.
*/
flipped_image=FlipImage(image,exception);
if (flipped_image != (Image *) NULL)
{
DuplicateBlob(flipped_image,image);
ReplaceImageInList(&image, flipped_image);
image=flipped_image;
}
}
/*
Read embeded ICC profile
*/
if ((bmp_info.colorspace == 0x4D424544L) && (profile_data > 0) &&
(profile_size > 0))
{
StringInfo
*profile;
unsigned char
*datum;
offset=start_position+14+profile_data;
if ((offset < TellBlob(image)) ||
(SeekBlob(image,offset,SEEK_SET) != offset) ||
(GetBlobSize(image) < (MagickSizeType) (offset+profile_size)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
profile=AcquireStringInfo((size_t) profile_size);
if (profile == (StringInfo *) NULL)
ThrowReaderException(CorruptImageError,"MemoryAllocationFailed");
datum=GetStringInfoDatum(profile);
if (ReadBlob(image,(size_t) profile_size,datum) == (ssize_t) profile_size)
{
MagickOffsetType
profile_size_orig;
/*
Trimming padded bytes.
*/
profile_size_orig=(MagickOffsetType) datum[0] << 24;
profile_size_orig|=(MagickOffsetType) datum[1] << 16;
profile_size_orig|=(MagickOffsetType) datum[2] << 8;
profile_size_orig|=(MagickOffsetType) datum[3];
if (profile_size_orig < profile_size)
SetStringInfoLength(profile,(size_t) profile_size_orig);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: ICC, %u bytes",(unsigned int) profile_size_orig);
(void) SetImageProfile(image,"icc",profile,exception);
}
profile=DestroyStringInfo(profile);
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
offset=(MagickOffsetType) bmp_info.ba_offset;
if (offset != 0)
if ((offset < TellBlob(image)) ||
(SeekBlob(image,offset,SEEK_SET) != offset))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
*magick='\0';
count=ReadBlob(image,2,magick);
if ((count == 2) && (IsBMP(magick,2) != MagickFalse))
{
/*
Acquire next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (IsBMP(magick,2) != MagickFalse);
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,420 |
php-src | 2871c70efaaaa0f102557a17c727fd4d5204dd4b | PHP_FUNCTION(escapeshellcmd)
{
char *command;
size_t command_len;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &command, &command_len) == FAILURE) {
return;
}
if (command_len) {
RETVAL_STR(php_escape_shell_cmd(command));
} else {
RETVAL_EMPTY_STRING();
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,200 |
sqlite | 926f796e8feec15f3836aa0a060ed906f8ae04d3 | static void incrAggFunctionDepth(Expr *pExpr, int N){
if( N>0 ){
Walker w;
memset(&w, 0, sizeof(w));
w.xExprCallback = incrAggDepth;
w.u.n = N;
sqlite3WalkExpr(&w, pExpr);
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,583 |
linux | 056ad39ee9253873522f6469c3364964a322912b | void usb_disable_device(struct usb_device *dev, int skip_ep0)
{
int i;
struct usb_hcd *hcd = bus_to_hcd(dev->bus);
/* getting rid of interfaces will disconnect
* any drivers bound to them (a key side effect)
*/
if (dev->actconfig) {
/*
* FIXME: In order to avoid self-deadlock involving the
* bandwidth_mutex, we have to mark all the interfaces
* before unregistering any of them.
*/
for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
dev->actconfig->interface[i]->unregistering = 1;
for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
struct usb_interface *interface;
/* remove this interface if it has been registered */
interface = dev->actconfig->interface[i];
if (!device_is_registered(&interface->dev))
continue;
dev_dbg(&dev->dev, "unregistering interface %s\n",
dev_name(&interface->dev));
remove_intf_ep_devs(interface);
device_del(&interface->dev);
}
/* Now that the interfaces are unbound, nobody should
* try to access them.
*/
for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
put_device(&dev->actconfig->interface[i]->dev);
dev->actconfig->interface[i] = NULL;
}
usb_disable_usb2_hardware_lpm(dev);
usb_unlocked_disable_lpm(dev);
usb_disable_ltm(dev);
dev->actconfig = NULL;
if (dev->state == USB_STATE_CONFIGURED)
usb_set_device_state(dev, USB_STATE_ADDRESS);
}
dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
skip_ep0 ? "non-ep0" : "all");
if (hcd->driver->check_bandwidth) {
/* First pass: Cancel URBs, leave endpoint pointers intact. */
for (i = skip_ep0; i < 16; ++i) {
usb_disable_endpoint(dev, i, false);
usb_disable_endpoint(dev, i + USB_DIR_IN, false);
}
/* Remove endpoints from the host controller internal state */
mutex_lock(hcd->bandwidth_mutex);
usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
mutex_unlock(hcd->bandwidth_mutex);
/* Second pass: remove endpoint pointers */
}
for (i = skip_ep0; i < 16; ++i) {
usb_disable_endpoint(dev, i, true);
usb_disable_endpoint(dev, i + USB_DIR_IN, true);
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,920 |
linux | ffdde5932042600c6807d46c1550b28b0db6a3bc | static int crypto_report(struct sk_buff *in_skb, struct nlmsghdr *in_nlh,
struct nlattr **attrs)
{
struct net *net = sock_net(in_skb->sk);
struct crypto_user_alg *p = nlmsg_data(in_nlh);
struct crypto_alg *alg;
struct sk_buff *skb;
struct crypto_dump_info info;
int err;
if (!null_terminated(p->cru_name) || !null_terminated(p->cru_driver_name))
return -EINVAL;
alg = crypto_alg_match(p, 0);
if (!alg)
return -ENOENT;
err = -ENOMEM;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!skb)
goto drop_alg;
info.in_skb = in_skb;
info.out_skb = skb;
info.nlmsg_seq = in_nlh->nlmsg_seq;
info.nlmsg_flags = 0;
err = crypto_report_alg(alg, &info);
drop_alg:
crypto_mod_put(alg);
if (err) {
kfree_skb(skb);
return err;
}
return nlmsg_unicast(net->crypto_nlsk, skb, NETLINK_CB(in_skb).portid);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,601 |
gpac | 7bb1b4a4dd23c885f9db9f577dfe79ecc5433109 | GF_Err gf_media_vp9_parse_sample(GF_BitStream *bs, GF_VPConfig *vp9_cfg, Bool *key_frame, u32 *FrameWidth, u32 *FrameHeight, u32 *renderWidth, u32 *renderHeight)
{
Bool FrameIsIntra = GF_FALSE, profile_low_bit, profile_high_bit, show_existing_frame = GF_FALSE, frame_type = GF_FALSE, show_frame = GF_FALSE, error_resilient_mode = GF_FALSE;
/*u8 frame_context_idx = 0, reset_frame_context = 0, frame_marker = 0*/;
int Sb64Cols = 0, Sb64Rows = 0, i;
u8 refresh_frame_flags = 0;
assert(bs && key_frame);
/*uncompressed header*/
/*frame_marker = */gf_bs_read_int_log(bs, 2, "frame_marker");
profile_low_bit = gf_bs_read_int_log(bs, 1, "profile_low_bit");
profile_high_bit = gf_bs_read_int_log(bs, 1, "profile_high_bit");
vp9_cfg->profile = (profile_high_bit << 1) + profile_low_bit;
if (vp9_cfg->profile == 3) {
Bool reserved_zero = gf_bs_read_int_log(bs, 1, "reserved_zero");
if (reserved_zero) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[VP9] uncompressed header reserved zero is not zero.\n"));
return GF_NON_COMPLIANT_BITSTREAM;
}
}
show_existing_frame = gf_bs_read_int_log(bs, 1, "show_existing_frame");
if (show_existing_frame == GF_TRUE) {
/*frame_to_show_map_idx = */gf_bs_read_int_log(bs, 3, "frame_to_show_map_idx");
return GF_OK;
}
frame_type = gf_bs_read_int_log(bs, 1, "frame_type");
show_frame = gf_bs_read_int_log(bs, 1, "show_frame");
error_resilient_mode = gf_bs_read_int_log(bs, 1, "error_resilient_mode");
if (frame_type == VP9_KEY_FRAME) {
if (!vp9_frame_sync_code(bs))
return GF_NON_COMPLIANT_BITSTREAM;
if (vp9_color_config(bs, vp9_cfg) != GF_OK)
return GF_NON_COMPLIANT_BITSTREAM;
vp9_frame_size(bs, FrameWidth, FrameHeight, &Sb64Cols, &Sb64Rows);
vp9_render_size(bs, *FrameWidth, *FrameHeight, renderWidth, renderHeight);
refresh_frame_flags = 0xFF;
*key_frame = GF_TRUE;
FrameIsIntra = GF_TRUE;
}
else {
Bool intra_only = GF_FALSE;
*key_frame = GF_FALSE;
if (show_frame == GF_FALSE) {
intra_only = gf_bs_read_int_log(bs, 1, "intra_only");
}
FrameIsIntra = intra_only;
if (error_resilient_mode == GF_FALSE) {
/*reset_frame_context = */gf_bs_read_int_log(bs, 2, "reset_frame_context");
}
if (intra_only == GF_TRUE) {
if (!vp9_frame_sync_code(bs))
return GF_NON_COMPLIANT_BITSTREAM;
if (vp9_cfg->profile > 0) {
if (vp9_color_config(bs, vp9_cfg) != GF_OK)
return GF_NON_COMPLIANT_BITSTREAM;
}
else {
u8 color_space = CS_BT_601;
vp9_cfg->colour_primaries = VP9_CS_to_23001_8_colour_primaries[color_space];
vp9_cfg->transfer_characteristics = VP9_CS_to_23001_8_transfer_characteristics[color_space];
vp9_cfg->matrix_coefficients = VP9_CS_to_23001_8_matrix_coefficients[color_space];
vp9_cfg->chroma_subsampling = 0;
vp9_cfg->bit_depth = 8;
}
refresh_frame_flags = gf_bs_read_int_log(bs, 8, "refresh_frame_flags");
vp9_frame_size(bs, FrameWidth, FrameHeight, &Sb64Cols, &Sb64Rows);
vp9_render_size(bs, *FrameWidth, *FrameHeight, renderWidth, renderHeight);
}
else {
refresh_frame_flags = gf_bs_read_int_log(bs, 8, "refresh_frame_flags");
u8 ref_frame_idx[3];
for (i = 0; i < 3; i++) {
ref_frame_idx[i] = gf_bs_read_int_log_idx(bs, 3, "ref_frame_idx", i);
/*ref_frame_sign_bias[LAST_FRAME + i] = */gf_bs_read_int_log_idx(bs, 1, "ref_frame_sign_bias", i);
}
vp9_frame_size_with_refs(bs, refresh_frame_flags, ref_frame_idx, vp9_cfg->RefFrameWidth, vp9_cfg->RefFrameHeight, FrameWidth, FrameHeight, renderWidth, renderHeight, &Sb64Cols, &Sb64Rows);
/*allow_high_precision_mv = */gf_bs_read_int_log(bs, 1, "allow_high_precision_mv");
vp9_read_interpolation_filter(bs);
}
}
if (error_resilient_mode == 0) {
/*refresh_frame_context = */gf_bs_read_int_log(bs, 1, "refresh_frame_context");
/*frame_parallel_decoding_mode = */gf_bs_read_int_log(bs, 1, "frame_parallel_decoding_mode");
}
/*frame_context_idx = */gf_bs_read_int_log(bs, 2, "frame_context_idx");
if (FrameIsIntra || error_resilient_mode) {
/*setup_past_independence + save_probs ...*/
//frame_context_idx = 0;
}
vp9_loop_filter_params(bs);
vp9_quantization_params(bs);
vp9_segmentation_params(bs);
vp9_tile_info(bs, Sb64Cols);
/*header_size_in_bytes = */gf_bs_read_int_log(bs, 16, "header_size_in_bytes");
/*Reference frame update process (8.10 - partial)*/
for (i = 0; i < VP9_NUM_REF_FRAMES; i++) {
if ((refresh_frame_flags >> i) & 1) {
vp9_cfg->RefFrameWidth[i] = *FrameWidth;
vp9_cfg->RefFrameHeight[i] = *FrameHeight;
}
}
return GF_OK;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,310 |
linux | dd504589577d8e8e70f51f997ad487a4cb6c026f | static int skcipher_accept_parent(void *private, struct sock *sk)
{
struct skcipher_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
unsigned int len = sizeof(*ctx) + crypto_skcipher_reqsize(private);
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->iv = sock_kmalloc(sk, crypto_skcipher_ivsize(private),
GFP_KERNEL);
if (!ctx->iv) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->iv, 0, crypto_skcipher_ivsize(private));
INIT_LIST_HEAD(&ctx->tsgl);
ctx->len = len;
ctx->used = 0;
ctx->more = 0;
ctx->merge = 0;
ctx->enc = 0;
atomic_set(&ctx->inflight, 0);
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
skcipher_request_set_tfm(&ctx->req, private);
skcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = skcipher_sock_destruct;
return 0;
}
| 1 | CVE-2015-8970 | 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. | 7,320 |
libgit2 | 64c612cc3e25eff5fb02c59ef5a66ba7a14751e4 | static int checkout_verify_paths(
git_repository *repo,
int action,
git_diff_delta *delta)
{
unsigned int flags = GIT_PATH_REJECT_WORKDIR_DEFAULTS;
if (action & CHECKOUT_ACTION__REMOVE) {
if (!git_path_isvalid(repo, delta->old_file.path, delta->old_file.mode, flags)) {
git_error_set(GIT_ERROR_CHECKOUT, "cannot remove invalid path '%s'", delta->old_file.path);
return -1;
}
}
if (action & ~CHECKOUT_ACTION__REMOVE) {
if (!git_path_isvalid(repo, delta->new_file.path, delta->new_file.mode, flags)) {
git_error_set(GIT_ERROR_CHECKOUT, "cannot checkout to invalid path '%s'", delta->new_file.path);
return -1;
}
}
return 0;
} | 1 | CVE-2020-12279 | 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. | 6,195 |
ext-http | 17137d4ab1ce81a2cee0fae842340a344ef3da83 | static inline void prepare_escaped(zval *zv TSRMLS_DC)
{
if (Z_TYPE_P(zv) == IS_STRING) {
quote_string(zv, 0 TSRMLS_CC);
} else {
zval_dtor(zv);
ZVAL_EMPTY_STRING(zv);
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,778 |
ox | e4565dbc167f0d38c3f93243d7a4fcfc391cbfc8 | fill_indent(PInfo pi, char *buf, size_t size) {
size_t cnt;
if (0 < (cnt = helper_stack_depth(&pi->helpers))) {
cnt *= 2;
if (size < cnt + 1) {
cnt = size - 1;
}
memset(buf, ' ', cnt);
buf += cnt;
}
*buf = '\0';
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,372 |
vim | d0b5138ba4bccff8a744c99836041ef6322ed39a | did_set_string_option(
int opt_idx, /* index in options[] table */
char_u **varp, /* pointer to the option variable */
int new_value_alloced, /* new value was allocated */
char_u *oldval, /* previous value of the option */
char_u *errbuf, /* buffer for errors, or NULL */
int opt_flags) /* OPT_LOCAL and/or OPT_GLOBAL */
{
char_u *errmsg = NULL;
char_u *s, *p;
int did_chartab = FALSE;
char_u **gvarp;
long_u free_oldval = (options[opt_idx].flags & P_ALLOCED);
#ifdef FEAT_GUI
/* set when changing an option that only requires a redraw in the GUI */
int redraw_gui_only = FALSE;
#endif
/* Get the global option to compare with, otherwise we would have to check
* two values for all local options. */
gvarp = (char_u **)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL);
/* Disallow changing some options from secure mode */
if ((secure
#ifdef HAVE_SANDBOX
|| sandbox != 0
#endif
) && (options[opt_idx].flags & P_SECURE))
{
errmsg = e_secure;
}
/* Check for a "normal" file name in some options. Disallow a path
* separator (slash and/or backslash), wildcards and characters that are
* often illegal in a file name. */
else if ((options[opt_idx].flags & P_NFNAME)
&& vim_strpbrk(*varp, (char_u *)"/\\*?[|<>") != NULL)
{
errmsg = e_invarg;
}
/* 'term' */
else if (varp == &T_NAME)
{
if (T_NAME[0] == NUL)
errmsg = (char_u *)N_("E529: Cannot set 'term' to empty string");
#ifdef FEAT_GUI
if (gui.in_use)
errmsg = (char_u *)N_("E530: Cannot change term in GUI");
else if (term_is_gui(T_NAME))
errmsg = (char_u *)N_("E531: Use \":gui\" to start the GUI");
#endif
else if (set_termname(T_NAME) == FAIL)
errmsg = (char_u *)N_("E522: Not found in termcap");
else
/* Screen colors may have changed. */
redraw_later_clear();
}
/* 'backupcopy' */
else if (gvarp == &p_bkc)
{
char_u *bkc = p_bkc;
unsigned int *flags = &bkc_flags;
if (opt_flags & OPT_LOCAL)
{
bkc = curbuf->b_p_bkc;
flags = &curbuf->b_bkc_flags;
}
if ((opt_flags & OPT_LOCAL) && *bkc == NUL)
/* make the local value empty: use the global value */
*flags = 0;
else
{
if (opt_strings_flags(bkc, p_bkc_values, flags, TRUE) != OK)
errmsg = e_invarg;
if ((((int)*flags & BKC_AUTO) != 0)
+ (((int)*flags & BKC_YES) != 0)
+ (((int)*flags & BKC_NO) != 0) != 1)
{
/* Must have exactly one of "auto", "yes" and "no". */
(void)opt_strings_flags(oldval, p_bkc_values, flags, TRUE);
errmsg = e_invarg;
}
}
}
/* 'backupext' and 'patchmode' */
else if (varp == &p_bex || varp == &p_pm)
{
if (STRCMP(*p_bex == '.' ? p_bex + 1 : p_bex,
*p_pm == '.' ? p_pm + 1 : p_pm) == 0)
errmsg = (char_u *)N_("E589: 'backupext' and 'patchmode' are equal");
}
#ifdef FEAT_LINEBREAK
/* 'breakindentopt' */
else if (varp == &curwin->w_p_briopt)
{
if (briopt_check(curwin) == FAIL)
errmsg = e_invarg;
}
#endif
/*
* 'isident', 'iskeyword', 'isprint or 'isfname' option: refill g_chartab[]
* If the new option is invalid, use old value. 'lisp' option: refill
* g_chartab[] for '-' char
*/
else if ( varp == &p_isi
|| varp == &(curbuf->b_p_isk)
|| varp == &p_isp
|| varp == &p_isf)
{
if (init_chartab() == FAIL)
{
did_chartab = TRUE; /* need to restore it below */
errmsg = e_invarg; /* error in value */
}
}
/* 'helpfile' */
else if (varp == &p_hf)
{
/* May compute new values for $VIM and $VIMRUNTIME */
if (didset_vim)
{
vim_setenv((char_u *)"VIM", (char_u *)"");
didset_vim = FALSE;
}
if (didset_vimruntime)
{
vim_setenv((char_u *)"VIMRUNTIME", (char_u *)"");
didset_vimruntime = FALSE;
}
}
#ifdef FEAT_SYN_HL
/* 'colorcolumn' */
else if (varp == &curwin->w_p_cc)
errmsg = check_colorcolumn(curwin);
#endif
#ifdef FEAT_MULTI_LANG
/* 'helplang' */
else if (varp == &p_hlg)
{
/* Check for "", "ab", "ab,cd", etc. */
for (s = p_hlg; *s != NUL; s += 3)
{
if (s[1] == NUL || ((s[2] != ',' || s[3] == NUL) && s[2] != NUL))
{
errmsg = e_invarg;
break;
}
if (s[2] == NUL)
break;
}
}
#endif
/* 'highlight' */
else if (varp == &p_hl)
{
if (highlight_changed() == FAIL)
errmsg = e_invarg; /* invalid flags */
}
/* 'nrformats' */
else if (gvarp == &p_nf)
{
if (check_opt_strings(*varp, p_nf_values, TRUE) != OK)
errmsg = e_invarg;
}
#ifdef FEAT_SESSION
/* 'sessionoptions' */
else if (varp == &p_ssop)
{
if (opt_strings_flags(p_ssop, p_ssop_values, &ssop_flags, TRUE) != OK)
errmsg = e_invarg;
if ((ssop_flags & SSOP_CURDIR) && (ssop_flags & SSOP_SESDIR))
{
/* Don't allow both "sesdir" and "curdir". */
(void)opt_strings_flags(oldval, p_ssop_values, &ssop_flags, TRUE);
errmsg = e_invarg;
}
}
/* 'viewoptions' */
else if (varp == &p_vop)
{
if (opt_strings_flags(p_vop, p_ssop_values, &vop_flags, TRUE) != OK)
errmsg = e_invarg;
}
#endif
/* 'scrollopt' */
#ifdef FEAT_SCROLLBIND
else if (varp == &p_sbo)
{
if (check_opt_strings(p_sbo, p_scbopt_values, TRUE) != OK)
errmsg = e_invarg;
}
#endif
/* 'ambiwidth' */
#ifdef FEAT_MBYTE
else if (varp == &p_ambw || varp == &p_emoji)
{
if (check_opt_strings(p_ambw, p_ambw_values, FALSE) != OK)
errmsg = e_invarg;
else if (set_chars_option(&p_lcs) != NULL)
errmsg = (char_u *)_("E834: Conflicts with value of 'listchars'");
# if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
else if (set_chars_option(&p_fcs) != NULL)
errmsg = (char_u *)_("E835: Conflicts with value of 'fillchars'");
# endif
}
#endif
/* 'background' */
else if (varp == &p_bg)
{
if (check_opt_strings(p_bg, p_bg_values, FALSE) == OK)
{
#ifdef FEAT_EVAL
int dark = (*p_bg == 'd');
#endif
init_highlight(FALSE, FALSE);
#ifdef FEAT_EVAL
if (dark != (*p_bg == 'd')
&& get_var_value((char_u *)"g:colors_name") != NULL)
{
/* The color scheme must have set 'background' back to another
* value, that's not what we want here. Disable the color
* scheme and set the colors again. */
do_unlet((char_u *)"g:colors_name", TRUE);
free_string_option(p_bg);
p_bg = vim_strsave((char_u *)(dark ? "dark" : "light"));
check_string_option(&p_bg);
init_highlight(FALSE, FALSE);
}
#endif
}
else
errmsg = e_invarg;
}
/* 'wildmode' */
else if (varp == &p_wim)
{
if (check_opt_wim() == FAIL)
errmsg = e_invarg;
}
#ifdef FEAT_CMDL_COMPL
/* 'wildoptions' */
else if (varp == &p_wop)
{
if (check_opt_strings(p_wop, p_wop_values, TRUE) != OK)
errmsg = e_invarg;
}
#endif
#ifdef FEAT_WAK
/* 'winaltkeys' */
else if (varp == &p_wak)
{
if (*p_wak == NUL
|| check_opt_strings(p_wak, p_wak_values, FALSE) != OK)
errmsg = e_invarg;
# ifdef FEAT_MENU
# ifdef FEAT_GUI_MOTIF
else if (gui.in_use)
gui_motif_set_mnemonics(p_wak[0] == 'y' || p_wak[0] == 'm');
# else
# ifdef FEAT_GUI_GTK
else if (gui.in_use)
gui_gtk_set_mnemonics(p_wak[0] == 'y' || p_wak[0] == 'm');
# endif
# endif
# endif
}
#endif
#ifdef FEAT_AUTOCMD
/* 'eventignore' */
else if (varp == &p_ei)
{
if (check_ei() == FAIL)
errmsg = e_invarg;
}
#endif
#ifdef FEAT_MBYTE
/* 'encoding' and 'fileencoding' */
else if (varp == &p_enc || gvarp == &p_fenc || varp == &p_tenc)
{
if (gvarp == &p_fenc)
{
if (!curbuf->b_p_ma && opt_flags != OPT_GLOBAL)
errmsg = e_modifiable;
else if (vim_strchr(*varp, ',') != NULL)
/* No comma allowed in 'fileencoding'; catches confusing it
* with 'fileencodings'. */
errmsg = e_invarg;
else
{
# ifdef FEAT_TITLE
/* May show a "+" in the title now. */
redraw_titles();
# endif
/* Add 'fileencoding' to the swap file. */
ml_setflags(curbuf);
}
}
if (errmsg == NULL)
{
/* canonize the value, so that STRCMP() can be used on it */
p = enc_canonize(*varp);
if (p != NULL)
{
vim_free(*varp);
*varp = p;
}
if (varp == &p_enc)
{
errmsg = mb_init();
# ifdef FEAT_TITLE
redraw_titles();
# endif
}
}
# if defined(FEAT_GUI_GTK)
if (errmsg == NULL && varp == &p_tenc && gui.in_use)
{
/* GTK+ 2 uses only a single encoding, and that is UTF-8. */
if (STRCMP(p_tenc, "utf-8") != 0)
errmsg = (char_u *)N_("E617: Cannot be changed in the GTK+ 2 GUI");
}
# endif
if (errmsg == NULL)
{
# ifdef FEAT_KEYMAP
/* When 'keymap' is used and 'encoding' changes, reload the keymap
* (with another encoding). */
if (varp == &p_enc && *curbuf->b_p_keymap != NUL)
(void)keymap_init();
# endif
/* When 'termencoding' is not empty and 'encoding' changes or when
* 'termencoding' changes, need to setup for keyboard input and
* display output conversion. */
if (((varp == &p_enc && *p_tenc != NUL) || varp == &p_tenc))
{
convert_setup(&input_conv, p_tenc, p_enc);
convert_setup(&output_conv, p_enc, p_tenc);
}
# if defined(WIN3264) && defined(FEAT_MBYTE)
/* $HOME may have characters in active code page. */
if (varp == &p_enc)
init_homedir();
# endif
}
}
#endif
#if defined(FEAT_POSTSCRIPT)
else if (varp == &p_penc)
{
/* Canonize printencoding if VIM standard one */
p = enc_canonize(p_penc);
if (p != NULL)
{
vim_free(p_penc);
p_penc = p;
}
else
{
/* Ensure lower case and '-' for '_' */
for (s = p_penc; *s != NUL; s++)
{
if (*s == '_')
*s = '-';
else
*s = TOLOWER_ASC(*s);
}
}
}
#endif
#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
else if (varp == &p_imak)
{
if (gui.in_use && !im_xim_isvalid_imactivate())
errmsg = e_invarg;
}
#endif
#ifdef FEAT_KEYMAP
else if (varp == &curbuf->b_p_keymap)
{
/* load or unload key mapping tables */
errmsg = keymap_init();
if (errmsg == NULL)
{
if (*curbuf->b_p_keymap != NUL)
{
/* Installed a new keymap, switch on using it. */
curbuf->b_p_iminsert = B_IMODE_LMAP;
if (curbuf->b_p_imsearch != B_IMODE_USE_INSERT)
curbuf->b_p_imsearch = B_IMODE_LMAP;
}
else
{
/* Cleared the keymap, may reset 'iminsert' and 'imsearch'. */
if (curbuf->b_p_iminsert == B_IMODE_LMAP)
curbuf->b_p_iminsert = B_IMODE_NONE;
if (curbuf->b_p_imsearch == B_IMODE_LMAP)
curbuf->b_p_imsearch = B_IMODE_USE_INSERT;
}
if ((opt_flags & OPT_LOCAL) == 0)
{
set_iminsert_global();
set_imsearch_global();
}
# ifdef FEAT_WINDOWS
status_redraw_curbuf();
# endif
}
}
#endif
/* 'fileformat' */
else if (gvarp == &p_ff)
{
if (!curbuf->b_p_ma && !(opt_flags & OPT_GLOBAL))
errmsg = e_modifiable;
else if (check_opt_strings(*varp, p_ff_values, FALSE) != OK)
errmsg = e_invarg;
else
{
/* may also change 'textmode' */
if (get_fileformat(curbuf) == EOL_DOS)
curbuf->b_p_tx = TRUE;
else
curbuf->b_p_tx = FALSE;
#ifdef FEAT_TITLE
redraw_titles();
#endif
/* update flag in swap file */
ml_setflags(curbuf);
/* Redraw needed when switching to/from "mac": a CR in the text
* will be displayed differently. */
if (get_fileformat(curbuf) == EOL_MAC || *oldval == 'm')
redraw_curbuf_later(NOT_VALID);
}
}
/* 'fileformats' */
else if (varp == &p_ffs)
{
if (check_opt_strings(p_ffs, p_ff_values, TRUE) != OK)
errmsg = e_invarg;
else
{
/* also change 'textauto' */
if (*p_ffs == NUL)
p_ta = FALSE;
else
p_ta = TRUE;
}
}
#if defined(FEAT_CRYPT)
/* 'cryptkey' */
else if (gvarp == &p_key)
{
# if defined(FEAT_CMDHIST)
/* Make sure the ":set" command doesn't show the new value in the
* history. */
remove_key_from_history();
# endif
if (STRCMP(curbuf->b_p_key, oldval) != 0)
/* Need to update the swapfile. */
ml_set_crypt_key(curbuf, oldval,
*curbuf->b_p_cm == NUL ? p_cm : curbuf->b_p_cm);
}
else if (gvarp == &p_cm)
{
if (opt_flags & OPT_LOCAL)
p = curbuf->b_p_cm;
else
p = p_cm;
if (check_opt_strings(p, p_cm_values, TRUE) != OK)
errmsg = e_invarg;
else if (crypt_self_test() == FAIL)
errmsg = e_invarg;
else
{
/* When setting the global value to empty, make it "zip". */
if (*p_cm == NUL)
{
if (new_value_alloced)
free_string_option(p_cm);
p_cm = vim_strsave((char_u *)"zip");
new_value_alloced = TRUE;
}
/* When using ":set cm=name" the local value is going to be empty.
* Do that here, otherwise the crypt functions will still use the
* local value. */
if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0)
{
free_string_option(curbuf->b_p_cm);
curbuf->b_p_cm = empty_option;
}
/* Need to update the swapfile when the effective method changed.
* Set "s" to the effective old value, "p" to the effective new
* method and compare. */
if ((opt_flags & OPT_LOCAL) && *oldval == NUL)
s = p_cm; /* was previously using the global value */
else
s = oldval;
if (*curbuf->b_p_cm == NUL)
p = p_cm; /* is now using the global value */
else
p = curbuf->b_p_cm;
if (STRCMP(s, p) != 0)
ml_set_crypt_key(curbuf, curbuf->b_p_key, s);
/* If the global value changes need to update the swapfile for all
* buffers using that value. */
if ((opt_flags & OPT_GLOBAL) && STRCMP(p_cm, oldval) != 0)
{
buf_T *buf;
FOR_ALL_BUFFERS(buf)
if (buf != curbuf && *buf->b_p_cm == NUL)
ml_set_crypt_key(buf, buf->b_p_key, oldval);
}
}
}
#endif
/* 'matchpairs' */
else if (gvarp == &p_mps)
{
#ifdef FEAT_MBYTE
if (has_mbyte)
{
for (p = *varp; *p != NUL; ++p)
{
int x2 = -1;
int x3 = -1;
if (*p != NUL)
p += mb_ptr2len(p);
if (*p != NUL)
x2 = *p++;
if (*p != NUL)
{
x3 = mb_ptr2char(p);
p += mb_ptr2len(p);
}
if (x2 != ':' || x3 == -1 || (*p != NUL && *p != ','))
{
errmsg = e_invarg;
break;
}
if (*p == NUL)
break;
}
}
else
#endif
{
/* Check for "x:y,x:y" */
for (p = *varp; *p != NUL; p += 4)
{
if (p[1] != ':' || p[2] == NUL || (p[3] != NUL && p[3] != ','))
{
errmsg = e_invarg;
break;
}
if (p[3] == NUL)
break;
}
}
}
#ifdef FEAT_COMMENTS
/* 'comments' */
else if (gvarp == &p_com)
{
for (s = *varp; *s; )
{
while (*s && *s != ':')
{
if (vim_strchr((char_u *)COM_ALL, *s) == NULL
&& !VIM_ISDIGIT(*s) && *s != '-')
{
errmsg = illegal_char(errbuf, *s);
break;
}
++s;
}
if (*s++ == NUL)
errmsg = (char_u *)N_("E524: Missing colon");
else if (*s == ',' || *s == NUL)
errmsg = (char_u *)N_("E525: Zero length string");
if (errmsg != NULL)
break;
while (*s && *s != ',')
{
if (*s == '\\' && s[1] != NUL)
++s;
++s;
}
s = skip_to_option_part(s);
}
}
#endif
/* 'listchars' */
else if (varp == &p_lcs)
{
errmsg = set_chars_option(varp);
}
#if defined(FEAT_WINDOWS) || defined(FEAT_FOLDING)
/* 'fillchars' */
else if (varp == &p_fcs)
{
errmsg = set_chars_option(varp);
}
#endif
#ifdef FEAT_CMDWIN
/* 'cedit' */
else if (varp == &p_cedit)
{
errmsg = check_cedit();
}
#endif
/* 'verbosefile' */
else if (varp == &p_vfile)
{
verbose_stop();
if (*p_vfile != NUL && verbose_open() == FAIL)
errmsg = e_invarg;
}
#ifdef FEAT_VIMINFO
/* 'viminfo' */
else if (varp == &p_viminfo)
{
for (s = p_viminfo; *s;)
{
/* Check it's a valid character */
if (vim_strchr((char_u *)"!\"%'/:<@cfhnrs", *s) == NULL)
{
errmsg = illegal_char(errbuf, *s);
break;
}
if (*s == 'n') /* name is always last one */
{
break;
}
else if (*s == 'r') /* skip until next ',' */
{
while (*++s && *s != ',')
;
}
else if (*s == '%')
{
/* optional number */
while (vim_isdigit(*++s))
;
}
else if (*s == '!' || *s == 'h' || *s == 'c')
++s; /* no extra chars */
else /* must have a number */
{
while (vim_isdigit(*++s))
;
if (!VIM_ISDIGIT(*(s - 1)))
{
if (errbuf != NULL)
{
sprintf((char *)errbuf,
_("E526: Missing number after <%s>"),
transchar_byte(*(s - 1)));
errmsg = errbuf;
}
else
errmsg = (char_u *)"";
break;
}
}
if (*s == ',')
++s;
else if (*s)
{
if (errbuf != NULL)
errmsg = (char_u *)N_("E527: Missing comma");
else
errmsg = (char_u *)"";
break;
}
}
if (*p_viminfo && errmsg == NULL && get_viminfo_parameter('\'') < 0)
errmsg = (char_u *)N_("E528: Must specify a ' value");
}
#endif /* FEAT_VIMINFO */
/* terminal options */
else if (istermoption(&options[opt_idx]) && full_screen)
{
/* ":set t_Co=0" and ":set t_Co=1" do ":set t_Co=" */
if (varp == &T_CCO)
{
int colors = atoi((char *)T_CCO);
/* Only reinitialize colors if t_Co value has really changed to
* avoid expensive reload of colorscheme if t_Co is set to the
* same value multiple times. */
if (colors != t_colors)
{
t_colors = colors;
if (t_colors <= 1)
{
if (new_value_alloced)
vim_free(T_CCO);
T_CCO = empty_option;
}
/* We now have a different color setup, initialize it again. */
init_highlight(TRUE, FALSE);
}
}
ttest(FALSE);
if (varp == &T_ME)
{
out_str(T_ME);
redraw_later(CLEAR);
#if defined(WIN3264) && !defined(FEAT_GUI_W32)
/* Since t_me has been set, this probably means that the user
* wants to use this as default colors. Need to reset default
* background/foreground colors. */
mch_set_normal_colors();
#endif
}
}
#ifdef FEAT_LINEBREAK
/* 'showbreak' */
else if (varp == &p_sbr)
{
for (s = p_sbr; *s; )
{
if (ptr2cells(s) != 1)
errmsg = (char_u *)N_("E595: contains unprintable or wide character");
mb_ptr_adv(s);
}
}
#endif
#ifdef FEAT_GUI
/* 'guifont' */
else if (varp == &p_guifont)
{
if (gui.in_use)
{
p = p_guifont;
# if defined(FEAT_GUI_GTK)
/*
* Put up a font dialog and let the user select a new value.
* If this is cancelled go back to the old value but don't
* give an error message.
*/
if (STRCMP(p, "*") == 0)
{
p = gui_mch_font_dialog(oldval);
if (new_value_alloced)
free_string_option(p_guifont);
p_guifont = (p != NULL) ? p : vim_strsave(oldval);
new_value_alloced = TRUE;
}
# endif
if (p != NULL && gui_init_font(p_guifont, FALSE) != OK)
{
# if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_PHOTON)
if (STRCMP(p_guifont, "*") == 0)
{
/* Dialog was cancelled: Keep the old value without giving
* an error message. */
if (new_value_alloced)
free_string_option(p_guifont);
p_guifont = vim_strsave(oldval);
new_value_alloced = TRUE;
}
else
# endif
errmsg = (char_u *)N_("E596: Invalid font(s)");
}
}
redraw_gui_only = TRUE;
}
# ifdef FEAT_XFONTSET
else if (varp == &p_guifontset)
{
if (STRCMP(p_guifontset, "*") == 0)
errmsg = (char_u *)N_("E597: can't select fontset");
else if (gui.in_use && gui_init_font(p_guifontset, TRUE) != OK)
errmsg = (char_u *)N_("E598: Invalid fontset");
redraw_gui_only = TRUE;
}
# endif
# ifdef FEAT_MBYTE
else if (varp == &p_guifontwide)
{
if (STRCMP(p_guifontwide, "*") == 0)
errmsg = (char_u *)N_("E533: can't select wide font");
else if (gui_get_wide_font() == FAIL)
errmsg = (char_u *)N_("E534: Invalid wide font");
redraw_gui_only = TRUE;
}
# endif
#endif
#ifdef CURSOR_SHAPE
/* 'guicursor' */
else if (varp == &p_guicursor)
errmsg = parse_shape_opt(SHAPE_CURSOR);
#endif
#ifdef FEAT_MOUSESHAPE
/* 'mouseshape' */
else if (varp == &p_mouseshape)
{
errmsg = parse_shape_opt(SHAPE_MOUSE);
update_mouseshape(-1);
}
#endif
#ifdef FEAT_PRINTER
else if (varp == &p_popt)
errmsg = parse_printoptions();
# if defined(FEAT_MBYTE) && defined(FEAT_POSTSCRIPT)
else if (varp == &p_pmfn)
errmsg = parse_printmbfont();
# endif
#endif
#ifdef FEAT_LANGMAP
/* 'langmap' */
else if (varp == &p_langmap)
langmap_set();
#endif
#ifdef FEAT_LINEBREAK
/* 'breakat' */
else if (varp == &p_breakat)
fill_breakat_flags();
#endif
#ifdef FEAT_TITLE
/* 'titlestring' and 'iconstring' */
else if (varp == &p_titlestring || varp == &p_iconstring)
{
# ifdef FEAT_STL_OPT
int flagval = (varp == &p_titlestring) ? STL_IN_TITLE : STL_IN_ICON;
/* NULL => statusline syntax */
if (vim_strchr(*varp, '%') && check_stl_option(*varp) == NULL)
stl_syntax |= flagval;
else
stl_syntax &= ~flagval;
# endif
did_set_title(varp == &p_iconstring);
}
#endif
#ifdef FEAT_GUI
/* 'guioptions' */
else if (varp == &p_go)
{
gui_init_which_components(oldval);
redraw_gui_only = TRUE;
}
#endif
#if defined(FEAT_GUI_TABLINE)
/* 'guitablabel' */
else if (varp == &p_gtl)
{
redraw_tabline = TRUE;
redraw_gui_only = TRUE;
}
/* 'guitabtooltip' */
else if (varp == &p_gtt)
{
redraw_gui_only = TRUE;
}
#endif
#if defined(FEAT_MOUSE_TTY) && (defined(UNIX) || defined(VMS))
/* 'ttymouse' */
else if (varp == &p_ttym)
{
/* Switch the mouse off before changing the escape sequences used for
* that. */
mch_setmouse(FALSE);
if (opt_strings_flags(p_ttym, p_ttym_values, &ttym_flags, FALSE) != OK)
errmsg = e_invarg;
else
check_mouse_termcode();
if (termcap_active)
setmouse(); /* may switch it on again */
}
#endif
/* 'selection' */
else if (varp == &p_sel)
{
if (*p_sel == NUL
|| check_opt_strings(p_sel, p_sel_values, FALSE) != OK)
errmsg = e_invarg;
}
/* 'selectmode' */
else if (varp == &p_slm)
{
if (check_opt_strings(p_slm, p_slm_values, TRUE) != OK)
errmsg = e_invarg;
}
#ifdef FEAT_BROWSE
/* 'browsedir' */
else if (varp == &p_bsdir)
{
if (check_opt_strings(p_bsdir, p_bsdir_values, FALSE) != OK
&& !mch_isdir(p_bsdir))
errmsg = e_invarg;
}
#endif
/* 'keymodel' */
else if (varp == &p_km)
{
if (check_opt_strings(p_km, p_km_values, TRUE) != OK)
errmsg = e_invarg;
else
{
km_stopsel = (vim_strchr(p_km, 'o') != NULL);
km_startsel = (vim_strchr(p_km, 'a') != NULL);
}
}
/* 'mousemodel' */
else if (varp == &p_mousem)
{
if (check_opt_strings(p_mousem, p_mousem_values, FALSE) != OK)
errmsg = e_invarg;
#if defined(FEAT_GUI_MOTIF) && defined(FEAT_MENU) && (XmVersion <= 1002)
else if (*p_mousem != *oldval)
/* Changed from "extend" to "popup" or "popup_setpos" or vv: need
* to create or delete the popup menus. */
gui_motif_update_mousemodel(root_menu);
#endif
}
/* 'switchbuf' */
else if (varp == &p_swb)
{
if (opt_strings_flags(p_swb, p_swb_values, &swb_flags, TRUE) != OK)
errmsg = e_invarg;
}
/* 'debug' */
else if (varp == &p_debug)
{
if (check_opt_strings(p_debug, p_debug_values, TRUE) != OK)
errmsg = e_invarg;
}
/* 'display' */
else if (varp == &p_dy)
{
if (opt_strings_flags(p_dy, p_dy_values, &dy_flags, TRUE) != OK)
errmsg = e_invarg;
else
(void)init_chartab();
}
#ifdef FEAT_WINDOWS
/* 'eadirection' */
else if (varp == &p_ead)
{
if (check_opt_strings(p_ead, p_ead_values, FALSE) != OK)
errmsg = e_invarg;
}
#endif
#ifdef FEAT_CLIPBOARD
/* 'clipboard' */
else if (varp == &p_cb)
errmsg = check_clipboard_option();
#endif
#ifdef FEAT_SPELL
/* When 'spelllang' or 'spellfile' is set and there is a window for this
* buffer in which 'spell' is set load the wordlists. */
else if (varp == &(curwin->w_s->b_p_spl)
|| varp == &(curwin->w_s->b_p_spf))
{
errmsg = did_set_spell_option(varp == &(curwin->w_s->b_p_spf));
}
/* When 'spellcapcheck' is set compile the regexp program. */
else if (varp == &(curwin->w_s->b_p_spc))
{
errmsg = compile_cap_prog(curwin->w_s);
}
/* 'spellsuggest' */
else if (varp == &p_sps)
{
if (spell_check_sps() != OK)
errmsg = e_invarg;
}
/* 'mkspellmem' */
else if (varp == &p_msm)
{
if (spell_check_msm() != OK)
errmsg = e_invarg;
}
#endif
#ifdef FEAT_QUICKFIX
/* When 'bufhidden' is set, check for valid value. */
else if (gvarp == &p_bh)
{
if (check_opt_strings(curbuf->b_p_bh, p_bufhidden_values, FALSE) != OK)
errmsg = e_invarg;
}
/* When 'buftype' is set, check for valid value. */
else if (gvarp == &p_bt)
{
if (check_opt_strings(curbuf->b_p_bt, p_buftype_values, FALSE) != OK)
errmsg = e_invarg;
else
{
# ifdef FEAT_WINDOWS
if (curwin->w_status_height)
{
curwin->w_redr_status = TRUE;
redraw_later(VALID);
}
# endif
curbuf->b_help = (curbuf->b_p_bt[0] == 'h');
# ifdef FEAT_TITLE
redraw_titles();
# endif
}
}
#endif
#ifdef FEAT_STL_OPT
/* 'statusline' or 'rulerformat' */
else if (gvarp == &p_stl || varp == &p_ruf)
{
int wid;
if (varp == &p_ruf) /* reset ru_wid first */
ru_wid = 0;
s = *varp;
if (varp == &p_ruf && *s == '%')
{
/* set ru_wid if 'ruf' starts with "%99(" */
if (*++s == '-') /* ignore a '-' */
s++;
wid = getdigits(&s);
if (wid && *s == '(' && (errmsg = check_stl_option(p_ruf)) == NULL)
ru_wid = wid;
else
errmsg = check_stl_option(p_ruf);
}
/* check 'statusline' only if it doesn't start with "%!" */
else if (varp == &p_ruf || s[0] != '%' || s[1] != '!')
errmsg = check_stl_option(s);
if (varp == &p_ruf && errmsg == NULL)
comp_col();
}
#endif
#ifdef FEAT_INS_EXPAND
/* check if it is a valid value for 'complete' -- Acevedo */
else if (gvarp == &p_cpt)
{
for (s = *varp; *s;)
{
while (*s == ',' || *s == ' ')
s++;
if (!*s)
break;
if (vim_strchr((char_u *)".wbuksid]tU", *s) == NULL)
{
errmsg = illegal_char(errbuf, *s);
break;
}
if (*++s != NUL && *s != ',' && *s != ' ')
{
if (s[-1] == 'k' || s[-1] == 's')
{
/* skip optional filename after 'k' and 's' */
while (*s && *s != ',' && *s != ' ')
{
if (*s == '\\')
++s;
++s;
}
}
else
{
if (errbuf != NULL)
{
sprintf((char *)errbuf,
_("E535: Illegal character after <%c>"),
*--s);
errmsg = errbuf;
}
else
errmsg = (char_u *)"";
break;
}
}
}
}
/* 'completeopt' */
else if (varp == &p_cot)
{
if (check_opt_strings(p_cot, p_cot_values, TRUE) != OK)
errmsg = e_invarg;
else
completeopt_was_set();
}
#endif /* FEAT_INS_EXPAND */
#ifdef FEAT_SIGNS
/* 'signcolumn' */
else if (varp == &curwin->w_p_scl)
{
if (check_opt_strings(*varp, p_scl_values, FALSE) != OK)
errmsg = e_invarg;
}
#endif
#if defined(FEAT_TOOLBAR) && !defined(FEAT_GUI_W32)
else if (varp == &p_toolbar)
{
if (opt_strings_flags(p_toolbar, p_toolbar_values,
&toolbar_flags, TRUE) != OK)
errmsg = e_invarg;
else
{
out_flush();
gui_mch_show_toolbar((toolbar_flags &
(TOOLBAR_TEXT | TOOLBAR_ICONS)) != 0);
}
}
#endif
#if defined(FEAT_TOOLBAR) && defined(FEAT_GUI_GTK)
/* 'toolbariconsize': GTK+ 2 only */
else if (varp == &p_tbis)
{
if (opt_strings_flags(p_tbis, p_tbis_values, &tbis_flags, FALSE) != OK)
errmsg = e_invarg;
else
{
out_flush();
gui_mch_show_toolbar((toolbar_flags &
(TOOLBAR_TEXT | TOOLBAR_ICONS)) != 0);
}
}
#endif
/* 'pastetoggle': translate key codes like in a mapping */
else if (varp == &p_pt)
{
if (*p_pt)
{
(void)replace_termcodes(p_pt, &p, TRUE, TRUE, FALSE);
if (p != NULL)
{
if (new_value_alloced)
free_string_option(p_pt);
p_pt = p;
new_value_alloced = TRUE;
}
}
}
/* 'backspace' */
else if (varp == &p_bs)
{
if (VIM_ISDIGIT(*p_bs))
{
if (*p_bs > '2' || p_bs[1] != NUL)
errmsg = e_invarg;
}
else if (check_opt_strings(p_bs, p_bs_values, TRUE) != OK)
errmsg = e_invarg;
}
else if (varp == &p_bo)
{
if (opt_strings_flags(p_bo, p_bo_values, &bo_flags, TRUE) != OK)
errmsg = e_invarg;
}
/* 'tagcase' */
else if (gvarp == &p_tc)
{
unsigned int *flags;
if (opt_flags & OPT_LOCAL)
{
p = curbuf->b_p_tc;
flags = &curbuf->b_tc_flags;
}
else
{
p = p_tc;
flags = &tc_flags;
}
if ((opt_flags & OPT_LOCAL) && *p == NUL)
/* make the local value empty: use the global value */
*flags = 0;
else if (*p == NUL
|| opt_strings_flags(p, p_tc_values, flags, FALSE) != OK)
errmsg = e_invarg;
}
#ifdef FEAT_MBYTE
/* 'casemap' */
else if (varp == &p_cmp)
{
if (opt_strings_flags(p_cmp, p_cmp_values, &cmp_flags, TRUE) != OK)
errmsg = e_invarg;
}
#endif
#ifdef FEAT_DIFF
/* 'diffopt' */
else if (varp == &p_dip)
{
if (diffopt_changed() == FAIL)
errmsg = e_invarg;
}
#endif
#ifdef FEAT_FOLDING
/* 'foldmethod' */
else if (gvarp == &curwin->w_allbuf_opt.wo_fdm)
{
if (check_opt_strings(*varp, p_fdm_values, FALSE) != OK
|| *curwin->w_p_fdm == NUL)
errmsg = e_invarg;
else
{
foldUpdateAll(curwin);
if (foldmethodIsDiff(curwin))
newFoldLevel();
}
}
# ifdef FEAT_EVAL
/* 'foldexpr' */
else if (varp == &curwin->w_p_fde)
{
if (foldmethodIsExpr(curwin))
foldUpdateAll(curwin);
}
# endif
/* 'foldmarker' */
else if (gvarp == &curwin->w_allbuf_opt.wo_fmr)
{
p = vim_strchr(*varp, ',');
if (p == NULL)
errmsg = (char_u *)N_("E536: comma required");
else if (p == *varp || p[1] == NUL)
errmsg = e_invarg;
else if (foldmethodIsMarker(curwin))
foldUpdateAll(curwin);
}
/* 'commentstring' */
else if (gvarp == &p_cms)
{
if (**varp != NUL && strstr((char *)*varp, "%s") == NULL)
errmsg = (char_u *)N_("E537: 'commentstring' must be empty or contain %s");
}
/* 'foldopen' */
else if (varp == &p_fdo)
{
if (opt_strings_flags(p_fdo, p_fdo_values, &fdo_flags, TRUE) != OK)
errmsg = e_invarg;
}
/* 'foldclose' */
else if (varp == &p_fcl)
{
if (check_opt_strings(p_fcl, p_fcl_values, TRUE) != OK)
errmsg = e_invarg;
}
/* 'foldignore' */
else if (gvarp == &curwin->w_allbuf_opt.wo_fdi)
{
if (foldmethodIsIndent(curwin))
foldUpdateAll(curwin);
}
#endif
#ifdef FEAT_VIRTUALEDIT
/* 'virtualedit' */
else if (varp == &p_ve)
{
if (opt_strings_flags(p_ve, p_ve_values, &ve_flags, TRUE) != OK)
errmsg = e_invarg;
else if (STRCMP(p_ve, oldval) != 0)
{
/* Recompute cursor position in case the new 've' setting
* changes something. */
validate_virtcol();
coladvance(curwin->w_virtcol);
}
}
#endif
#if defined(FEAT_CSCOPE) && defined(FEAT_QUICKFIX)
else if (varp == &p_csqf)
{
if (p_csqf != NULL)
{
p = p_csqf;
while (*p != NUL)
{
if (vim_strchr((char_u *)CSQF_CMDS, *p) == NULL
|| p[1] == NUL
|| vim_strchr((char_u *)CSQF_FLAGS, p[1]) == NULL
|| (p[2] != NUL && p[2] != ','))
{
errmsg = e_invarg;
break;
}
else if (p[2] == NUL)
break;
else
p += 3;
}
}
}
#endif
#ifdef FEAT_CINDENT
/* 'cinoptions' */
else if (gvarp == &p_cino)
{
/* TODO: recognize errors */
parse_cino(curbuf);
}
#endif
#if defined(FEAT_RENDER_OPTIONS)
else if (varp == &p_rop && gui.in_use)
{
if (!gui_mch_set_rendering_options(p_rop))
errmsg = e_invarg;
}
#endif
/* Options that are a list of flags. */
else
{
p = NULL;
if (varp == &p_ww)
p = (char_u *)WW_ALL;
if (varp == &p_shm)
p = (char_u *)SHM_ALL;
else if (varp == &(p_cpo))
p = (char_u *)CPO_ALL;
else if (varp == &(curbuf->b_p_fo))
p = (char_u *)FO_ALL;
#ifdef FEAT_CONCEAL
else if (varp == &curwin->w_p_cocu)
p = (char_u *)COCU_ALL;
#endif
else if (varp == &p_mouse)
{
#ifdef FEAT_MOUSE
p = (char_u *)MOUSE_ALL;
#else
if (*p_mouse != NUL)
errmsg = (char_u *)N_("E538: No mouse support");
#endif
}
#if defined(FEAT_GUI)
else if (varp == &p_go)
p = (char_u *)GO_ALL;
#endif
if (p != NULL)
{
for (s = *varp; *s; ++s)
if (vim_strchr(p, *s) == NULL)
{
errmsg = illegal_char(errbuf, *s);
break;
}
}
}
/*
* If error detected, restore the previous value.
*/
if (errmsg != NULL)
{
if (new_value_alloced)
free_string_option(*varp);
*varp = oldval;
/*
* When resetting some values, need to act on it.
*/
if (did_chartab)
(void)init_chartab();
if (varp == &p_hl)
(void)highlight_changed();
}
else
{
#ifdef FEAT_EVAL
/* Remember where the option was set. */
set_option_scriptID_idx(opt_idx, opt_flags, current_SID);
#endif
/*
* Free string options that are in allocated memory.
* Use "free_oldval", because recursiveness may change the flags under
* our fingers (esp. init_highlight()).
*/
if (free_oldval)
free_string_option(oldval);
if (new_value_alloced)
options[opt_idx].flags |= P_ALLOCED;
else
options[opt_idx].flags &= ~P_ALLOCED;
if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0
&& ((int)options[opt_idx].indir & PV_BOTH))
{
/* global option with local value set to use global value; free
* the local value and make it empty */
p = get_varp_scope(&(options[opt_idx]), OPT_LOCAL);
free_string_option(*(char_u **)p);
*(char_u **)p = empty_option;
}
/* May set global value for local option. */
else if (!(opt_flags & OPT_LOCAL) && opt_flags != OPT_GLOBAL)
set_string_option_global(opt_idx, varp);
#ifdef FEAT_AUTOCMD
/*
* Trigger the autocommand only after setting the flags.
*/
# ifdef FEAT_SYN_HL
/* When 'syntax' is set, load the syntax of that name */
if (varp == &(curbuf->b_p_syn))
{
apply_autocmds(EVENT_SYNTAX, curbuf->b_p_syn,
curbuf->b_fname, TRUE, curbuf);
}
# endif
else if (varp == &(curbuf->b_p_ft))
{
/* 'filetype' is set, trigger the FileType autocommand */
did_filetype = TRUE;
apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft,
curbuf->b_fname, TRUE, curbuf);
}
#endif
#ifdef FEAT_SPELL
if (varp == &(curwin->w_s->b_p_spl))
{
char_u fname[200];
char_u *q = curwin->w_s->b_p_spl;
/* Skip the first name if it is "cjk". */
if (STRNCMP(q, "cjk,", 4) == 0)
q += 4;
/*
* Source the spell/LANG.vim in 'runtimepath'.
* They could set 'spellcapcheck' depending on the language.
* Use the first name in 'spelllang' up to '_region' or
* '.encoding'.
*/
for (p = q; *p != NUL; ++p)
if (vim_strchr((char_u *)"_.,", *p) != NULL)
break;
vim_snprintf((char *)fname, 200, "spell/%.*s.vim", (int)(p - q), q);
source_runtime(fname, DIP_ALL);
}
#endif
}
#ifdef FEAT_MOUSE
if (varp == &p_mouse)
{
# ifdef FEAT_MOUSE_TTY
if (*p_mouse == NUL)
mch_setmouse(FALSE); /* switch mouse off */
else
# endif
setmouse(); /* in case 'mouse' changed */
}
#endif
if (curwin->w_curswant != MAXCOL
&& (options[opt_idx].flags & (P_CURSWANT | P_RALL)) != 0)
curwin->w_set_curswant = TRUE;
#ifdef FEAT_GUI
/* check redraw when it's not a GUI option or the GUI is active. */
if (!redraw_gui_only || gui.in_use)
#endif
check_redraw(options[opt_idx].flags);
return errmsg;
} | 1 | CVE-2016-1248 | 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. | 676 |
gpac | a51f951b878c2b73c1d8e2f1518c7cdc5fb82c3f | GF_Err afra_box_read(GF_Box *s, GF_BitStream *bs)
{
unsigned int i;
GF_AdobeFragRandomAccessBox *ptr = (GF_AdobeFragRandomAccessBox *)s;
ISOM_DECREASE_SIZE(ptr, 9)
ptr->long_ids = gf_bs_read_int(bs, 1);
ptr->long_offsets = gf_bs_read_int(bs, 1);
ptr->global_entries = gf_bs_read_int(bs, 1);
ptr->reserved = gf_bs_read_int(bs, 5);
ptr->time_scale = gf_bs_read_u32(bs);
ptr->entry_count = gf_bs_read_u32(bs);
if (ptr->size / ( (ptr->long_offsets ? 16 : 12) ) < ptr->entry_count)
return GF_ISOM_INVALID_FILE;
for (i=0; i<ptr->entry_count; i++) {
GF_AfraEntry *ae = gf_malloc(sizeof(GF_AfraEntry));
if (!ae) return GF_OUT_OF_MEM;
ISOM_DECREASE_SIZE(ptr, 8)
ae->time = gf_bs_read_u64(bs);
if (ptr->long_offsets) {
ISOM_DECREASE_SIZE(ptr, 8)
ae->offset = gf_bs_read_u64(bs);
} else {
ISOM_DECREASE_SIZE(ptr, 4)
ae->offset = gf_bs_read_u32(bs);
}
gf_list_insert(ptr->local_access_entries, ae, i);
}
if (ptr->global_entries) {
ISOM_DECREASE_SIZE(ptr, 4)
ptr->global_entry_count = gf_bs_read_u32(bs);
for (i=0; i<ptr->global_entry_count; i++) {
GF_GlobalAfraEntry *ae = gf_malloc(sizeof(GF_GlobalAfraEntry));
if (!ae) return GF_OUT_OF_MEM;
ISOM_DECREASE_SIZE(ptr, 8)
ae->time = gf_bs_read_u64(bs);
if (ptr->long_ids) {
ISOM_DECREASE_SIZE(ptr, 8)
ae->segment = gf_bs_read_u32(bs);
ae->fragment = gf_bs_read_u32(bs);
} else {
ISOM_DECREASE_SIZE(ptr, 4)
ae->segment = gf_bs_read_u16(bs);
ae->fragment = gf_bs_read_u16(bs);
}
if (ptr->long_offsets) {
ISOM_DECREASE_SIZE(ptr, 16)
ae->afra_offset = gf_bs_read_u64(bs);
ae->offset_from_afra = gf_bs_read_u64(bs);
} else {
ISOM_DECREASE_SIZE(ptr, 8)
ae->afra_offset = gf_bs_read_u32(bs);
ae->offset_from_afra = gf_bs_read_u32(bs);
}
gf_list_insert(ptr->global_access_entries, ae, i);
}
}
return GF_OK;
} | 1 | CVE-2021-33361 | 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). | 8,307 |
qemu | cc96677469388bad3d66479379735cf75db069e3 | void esp_init(hwaddr espaddr, int it_shift,
ESPDMAMemoryReadWriteFunc dma_memory_read,
ESPDMAMemoryReadWriteFunc dma_memory_write,
void *dma_opaque, qemu_irq irq, qemu_irq *reset,
qemu_irq *dma_enable)
{
DeviceState *dev;
SysBusDevice *s;
SysBusESPState *sysbus;
ESPState *esp;
dev = qdev_create(NULL, TYPE_ESP);
sysbus = ESP(dev);
esp = &sysbus->esp;
esp->dma_memory_read = dma_memory_read;
esp->dma_memory_write = dma_memory_write;
esp->dma_opaque = dma_opaque;
sysbus->it_shift = it_shift;
/* XXX for now until rc4030 has been changed to use DMA enable signal */
esp->dma_enabled = 1;
qdev_init_nofail(dev);
s = SYS_BUS_DEVICE(dev);
sysbus_connect_irq(s, 0, irq);
sysbus_mmio_map(s, 0, espaddr);
*reset = qdev_get_gpio_in(dev, 0);
*dma_enable = qdev_get_gpio_in(dev, 1);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,710 |
FreeRDP | 6d86e20e1e7caaab4f0c7f89e36d32914dbccc52 | int shadow_server_init(rdpShadowServer* server)
{
int status;
winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT);
WTSRegisterWtsApiFunctionTable(FreeRDP_InitWtsApi());
if (!(server->clients = ArrayList_New(TRUE)))
goto fail_client_array;
if (!(server->StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))
goto fail_stop_event;
if (!InitializeCriticalSectionAndSpinCount(&(server->lock), 4000))
goto fail_server_lock;
status = shadow_server_init_config_path(server);
if (status < 0)
goto fail_config_path;
status = shadow_server_init_certificate(server);
if (status < 0)
goto fail_certificate;
server->listener = freerdp_listener_new();
if (!server->listener)
goto fail_listener;
server->listener->info = (void*)server;
server->listener->PeerAccepted = shadow_client_accepted;
server->subsystem = shadow_subsystem_new();
if (!server->subsystem)
goto fail_subsystem_new;
status = shadow_subsystem_init(server->subsystem, server);
if (status >= 0)
return status;
shadow_subsystem_free(server->subsystem);
fail_subsystem_new:
freerdp_listener_free(server->listener);
server->listener = NULL;
fail_listener:
free(server->CertificateFile);
server->CertificateFile = NULL;
free(server->PrivateKeyFile);
server->PrivateKeyFile = NULL;
fail_certificate:
free(server->ConfigPath);
server->ConfigPath = NULL;
fail_config_path:
DeleteCriticalSection(&(server->lock));
fail_server_lock:
CloseHandle(server->StopEvent);
server->StopEvent = NULL;
fail_stop_event:
ArrayList_Free(server->clients);
server->clients = NULL;
fail_client_array:
WLog_ERR(TAG, "Failed to initialize shadow server");
return -1;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,579 |
netfilter | 2ae1099a42e6a0f06de305ca13a842ac83d4683e | void add_param_to_argv(char *parsestart, int line)
{
int quote_open = 0, escaped = 0, param_len = 0;
char param_buffer[1024], *curchar;
/* After fighting with strtok enough, here's now
* a 'real' parser. According to Rusty I'm now no
} else {
param_buffer[param_len++] = *curchar;
for (curchar = parsestart; *curchar; curchar++) {
if (quote_open) {
if (escaped) {
param_buffer[param_len++] = *curchar;
escaped = 0;
continue;
} else if (*curchar == '\\') {
}
switch (*curchar) {
quote_open = 0;
*curchar = '"';
} else {
param_buffer[param_len++] = *curchar;
continue;
}
} else {
continue;
}
break;
default:
/* regular character, copy to buffer */
param_buffer[param_len++] = *curchar;
if (param_len >= sizeof(param_buffer))
xtables_error(PARAMETER_PROBLEM,
case ' ':
case '\t':
case '\n':
if (!param_len) {
/* two spaces? */
continue;
}
break;
default:
/* regular character, copy to buffer */
param_buffer[param_len++] = *curchar;
if (param_len >= sizeof(param_buffer))
xtables_error(PARAMETER_PROBLEM,
"Parameter too long!");
continue;
}
param_buffer[param_len] = '\0';
/* check if table name specified */
if ((param_buffer[0] == '-' &&
param_buffer[1] != '-' &&
strchr(param_buffer, 't')) ||
(!strncmp(param_buffer, "--t", 3) &&
!strncmp(param_buffer, "--table", strlen(param_buffer)))) {
xtables_error(PARAMETER_PROBLEM,
"The -t option (seen in line %u) cannot be used in %s.\n",
line, xt_params->program_name);
}
add_argv(param_buffer, 0);
param_len = 0;
}
| 1 | CVE-2019-11360 | 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,334 |
linux | 453393369dc9806d2455151e329c599684762428 | static void ttm_put_pages(struct page **pages, unsigned npages, int flags,
enum ttm_caching_state cstate)
{
struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate);
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate);
#endif
unsigned long irq_flags;
unsigned i;
if (pool == NULL) {
/* No pool for this memory type so free the pages */
i = 0;
while (i < npages) {
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
struct page *p = pages[i];
#endif
unsigned order = 0, j;
if (!pages[i]) {
++i;
continue;
}
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (!(flags & TTM_PAGE_FLAG_DMA32) &&
(npages - i) >= HPAGE_PMD_NR) {
for (j = 1; j < HPAGE_PMD_NR; ++j)
if (++p != pages[i + j])
break;
if (j == HPAGE_PMD_NR)
order = HPAGE_PMD_ORDER;
}
#endif
if (page_count(pages[i]) != 1)
pr_err("Erroneous page count. Leaking pages.\n");
__free_pages(pages[i], order);
j = 1 << order;
while (j) {
pages[i++] = NULL;
--j;
}
}
return;
}
i = 0;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (huge) {
unsigned max_size, n2free;
spin_lock_irqsave(&huge->lock, irq_flags);
while ((npages - i) >= HPAGE_PMD_NR) {
struct page *p = pages[i];
unsigned j;
if (!p)
break;
for (j = 1; j < HPAGE_PMD_NR; ++j)
if (++p != pages[i + j])
break;
if (j != HPAGE_PMD_NR)
break;
list_add_tail(&pages[i]->lru, &huge->list);
for (j = 0; j < HPAGE_PMD_NR; ++j)
pages[i++] = NULL;
huge->npages++;
}
/* Check that we don't go over the pool limit */
max_size = _manager->options.max_size;
max_size /= HPAGE_PMD_NR;
if (huge->npages > max_size)
n2free = huge->npages - max_size;
else
n2free = 0;
spin_unlock_irqrestore(&huge->lock, irq_flags);
if (n2free)
ttm_page_pool_free(huge, n2free, false);
}
#endif
spin_lock_irqsave(&pool->lock, irq_flags);
while (i < npages) {
if (pages[i]) {
if (page_count(pages[i]) != 1)
pr_err("Erroneous page count. Leaking pages.\n");
list_add_tail(&pages[i]->lru, &pool->list);
pages[i] = NULL;
pool->npages++;
}
++i;
}
/* Check that we don't go over the pool limit */
npages = 0;
if (pool->npages > _manager->options.max_size) {
npages = pool->npages - _manager->options.max_size;
/* free at least NUM_PAGES_TO_ALLOC number of pages
* to reduce calls to set_memory_wb */
if (npages < NUM_PAGES_TO_ALLOC)
npages = NUM_PAGES_TO_ALLOC;
}
spin_unlock_irqrestore(&pool->lock, irq_flags);
if (npages)
ttm_page_pool_free(pool, npages, false);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,817 |
gpac | b2db2f99b4c30f96e17b9a14537c776da6cb5dca | GF_Err latm_dmx_configure_pid(GF_Filter *filter, GF_FilterPid *pid, Bool is_remove)
{
const GF_PropertyValue *p;
GF_LATMDmxCtx *ctx = gf_filter_get_udta(filter);
if (is_remove) {
ctx->ipid = NULL;
if (ctx->opid) {
gf_filter_pid_remove(ctx->opid);
ctx->opid = NULL;
}
return GF_OK;
}
if (! gf_filter_pid_check_caps(pid))
return GF_NOT_SUPPORTED;
ctx->ipid = pid;
p = gf_filter_pid_get_property(pid, GF_PROP_PID_TIMESCALE);
if (p) ctx->timescale = p->value.uint;
if (ctx->timescale && !ctx->opid) {
ctx->opid = gf_filter_pid_new(filter);
gf_filter_pid_copy_properties(ctx->opid, ctx->ipid);
gf_filter_pid_set_property(ctx->opid, GF_PROP_PID_UNFRAMED, NULL);
}
return GF_OK;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,215 |
linux | a8b0ca17b80e92faab46ee7179ba9e99ccb61233 | static void perf_event_interrupt(struct pt_regs *regs)
{
int i;
struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);
struct perf_event *event;
unsigned long val;
int found = 0;
int nmi;
nmi = perf_intr_is_nmi(regs);
if (nmi)
nmi_enter();
else
irq_enter();
for (i = 0; i < ppmu->n_counter; ++i) {
event = cpuhw->event[i];
val = read_pmc(i);
if ((int)val < 0) {
if (event) {
/* event has overflowed */
found = 1;
record_and_restart(event, val, regs, nmi);
} else {
/*
* Disabled counter is negative,
* reset it just in case.
*/
write_pmc(i, 0);
}
}
}
/* PMM will keep counters frozen until we return from the interrupt. */
mtmsr(mfmsr() | MSR_PMM);
mtpmr(PMRN_PMGC0, PMGC0_PMIE | PMGC0_FCECE);
isync();
if (nmi)
nmi_exit();
else
irq_exit();
}
| 1 | CVE-2011-2918 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 7,046 |
libevent | ec65c42052d95d2c23d1d837136d1cf1d9ecef9e | search_make_new(const struct search_state *const state, int n, const char *const base_name) {
const size_t base_len = strlen(base_name);
const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
struct search_domain *dom;
for (dom = state->head; dom; dom = dom->next) {
if (!n--) {
/* this is the postfix we want */
/* the actual postfix string is kept at the end of the structure */
const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
const int postfix_len = dom->len;
char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
if (!newname) return NULL;
memcpy(newname, base_name, base_len);
if (need_to_append_dot) newname[base_len] = '.';
memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
newname[base_len + need_to_append_dot + postfix_len] = 0;
return newname;
}
}
/* we ran off the end of the list and still didn't find the requested string */
EVUTIL_ASSERT(0);
return NULL; /* unreachable; stops warnings in some compilers. */
}
| 1 | CVE-2016-10197 | 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. | 7,691 |
ZRTPCPP | c8617100f359b217a974938c5539a1dd8a120b0e | void ZrtpQueue::handleTimeout(const std::string &c) {
if (zrtpEngine != NULL) {
zrtpEngine->processTimeout();
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,938 |
tensorflow | dcd7867de0fea4b72a2b34bd41eb74548dc23886 | static void launch(OpKernelContext* context, const PoolParameters& params,
const Tensor& grad_in, const Tensor& argmax,
Tensor* grad_out, const bool include_batch_in_index) {
const DeviceBase::CpuWorkerThreads& worker_threads =
*(context->device()->tensorflow_cpu_worker_threads());
auto shard = [&grad_in, &argmax, &grad_out, include_batch_in_index](
int64 start, int64 limit) {
const int64 batch_size =
GetTensorDim(grad_out->shape(), FORMAT_NHWC, 'N');
const int64 output_size_per_batch = grad_out->NumElements() / batch_size;
const int64 input_size_per_batch = grad_in.NumElements() / batch_size;
{
auto grad_out_flat = grad_out->flat<T>();
auto argmax_flat = argmax.flat<int64>();
auto grad_in_flat = grad_in.flat<T>();
const int64 output_start = start * output_size_per_batch;
const int64 output_end = limit * output_size_per_batch;
EigenMatrixMap inputShard(grad_out_flat.data() + output_start, 1,
output_end - output_start);
inputShard.setConstant(T(0));
const int input_start = start * input_size_per_batch;
const int input_end = limit * input_size_per_batch;
for (int64 index = input_start; index < input_end; index++) {
int64 grad_out_index = argmax_flat(index);
if (!include_batch_in_index) {
const int64 cur_batch = index / input_size_per_batch;
grad_out_index += cur_batch * output_size_per_batch;
}
CHECK(grad_out_index >= output_start && grad_out_index < output_end)
<< "Invalid output gradient index: " << grad_out_index << ", "
<< output_start << ", " << output_end;
grad_out_flat(grad_out_index) += grad_in_flat(index);
}
}
};
const int64 batch_size = GetTensorDim(grad_out->shape(), FORMAT_NHWC, 'N');
const int64 shard_cost = grad_out->NumElements() / batch_size;
Shard(worker_threads.num_threads, worker_threads.workers, batch_size,
shard_cost, shard);
} | 1 | CVE-2021-29570 | 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. | 862 |
libzmq | 77f14aad95cdf0d2a244ae9b4a025e5ba0adf01a | void zmq::stream_engine_t::zap_msg_available ()
{
zmq_assert (mechanism != NULL);
const int rc = mechanism->zap_msg_available ();
if (rc == -1) {
error (protocol_error);
return;
}
if (input_stopped)
restart_input ();
if (output_stopped)
restart_output ();
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,289 |
linux | d563131ef23cbc756026f839a82598c8445bc45f | static int rsi_load_bootup_params(struct rsi_common *common)
{
struct sk_buff *skb;
struct rsi_boot_params *boot_params;
rsi_dbg(MGMT_TX_ZONE, "%s: Sending boot params frame\n", __func__);
skb = dev_alloc_skb(sizeof(struct rsi_boot_params));
if (!skb) {
rsi_dbg(ERR_ZONE, "%s: Failed in allocation of skb\n",
__func__);
return -ENOMEM;
}
memset(skb->data, 0, sizeof(struct rsi_boot_params));
boot_params = (struct rsi_boot_params *)skb->data;
rsi_dbg(MGMT_TX_ZONE, "%s:\n", __func__);
if (common->channel_width == BW_40MHZ) {
memcpy(&boot_params->bootup_params,
&boot_params_40,
sizeof(struct bootup_params));
rsi_dbg(MGMT_TX_ZONE, "%s: Packet 40MHZ <=== %d\n", __func__,
UMAC_CLK_40BW);
boot_params->desc_word[7] = cpu_to_le16(UMAC_CLK_40BW);
} else {
memcpy(&boot_params->bootup_params,
&boot_params_20,
sizeof(struct bootup_params));
if (boot_params_20.valid != cpu_to_le32(VALID_20)) {
boot_params->desc_word[7] = cpu_to_le16(UMAC_CLK_20BW);
rsi_dbg(MGMT_TX_ZONE,
"%s: Packet 20MHZ <=== %d\n", __func__,
UMAC_CLK_20BW);
} else {
boot_params->desc_word[7] = cpu_to_le16(UMAC_CLK_40MHZ);
rsi_dbg(MGMT_TX_ZONE,
"%s: Packet 20MHZ <=== %d\n", __func__,
UMAC_CLK_40MHZ);
}
}
/**
* Bit{0:11} indicates length of the Packet
* Bit{12:15} indicates host queue number
*/
boot_params->desc_word[0] = cpu_to_le16(sizeof(struct bootup_params) |
(RSI_WIFI_MGMT_Q << 12));
boot_params->desc_word[1] = cpu_to_le16(BOOTUP_PARAMS_REQUEST);
skb_put(skb, sizeof(struct rsi_boot_params));
return rsi_send_internal_mgmt_frame(common, skb);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,043 |
radare2 | 10517e3ff0e609697eb8cde60ec8dc999ee5ea24 | R_API char *r_core_anal_fcn_name(RCore *core, RAnalFunction *fcn) {
bool demangle = r_config_get_i (core->config, "bin.demangle");
const char *lang = demangle ? r_config_get (core->config, "bin.lang") : NULL;
bool keep_lib = r_config_get_i (core->config, "bin.demangle.libs");
char *name = strdup (r_str_get (fcn->name));
if (demangle) {
char *tmp = r_bin_demangle (core->bin->cur, lang, name, fcn->addr, keep_lib);
if (tmp) {
free (name);
name = tmp;
}
}
return name;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,294 |
linux | c7559663e42f4294ffe31fe159da6b6a66b35d61 | void nfs_write_prepare(struct rpc_task *task, void *calldata)
{
struct nfs_write_data *data = calldata;
NFS_PROTO(data->header->inode)->write_rpc_prepare(task, data);
if (unlikely(test_bit(NFS_CONTEXT_BAD, &data->args.context->flags)))
rpc_exit(task, -EIO);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,013 |
exiv2 | afb98cbc6e288dc8ea75f3394a347fb9b37abc55 | void TiffImage::readMetadata()
{
#ifdef DEBUG
std::cerr << "Reading TIFF file " << io_->path() << "\n";
#endif
if (io_->open() != 0) throw Error(kerDataSourceOpenFailed, io_->path(), strError());
IoCloser closer(*io_);
// Ensure that this is the correct image type
if (!isTiffType(*io_, false)) {
if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
throw Error(kerNotAnImage, "TIFF");
}
clearMetadata();
ByteOrder bo = TiffParser::decode(exifData_,
iptcData_,
xmpData_,
io_->mmap(),
(uint32_t) io_->size());
setByteOrder(bo);
// read profile from the metadata
Exiv2::ExifKey key("Exif.Image.InterColorProfile");
Exiv2::ExifData::iterator pos = exifData_.findKey(key);
if ( pos != exifData_.end() ) {
iccProfile_.alloc(pos->count());
pos->copy(iccProfile_.pData_,bo);
}
} // TiffImage::readMetadata | 1 | CVE-2018-17229 | 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). | 9,366 |
mongo-c-driver | 0d9a4d98bfdf4acd2c0138d4aaeb4e2e0934bd84 | _bson_iter_next_internal (bson_iter_t *iter, /* INOUT */
uint32_t next_keylen, /* IN */
const char **key, /* OUT */
uint32_t *bson_type, /* OUT */
bool *unsupported) /* OUT */
{
const uint8_t *data;
uint32_t o;
unsigned int len;
BSON_ASSERT (iter);
*unsupported = false;
if (!iter->raw) {
*key = NULL;
*bson_type = BSON_TYPE_EOD;
return false;
}
data = iter->raw;
len = iter->len;
iter->off = iter->next_off;
iter->type = iter->off;
iter->key = iter->off + 1;
iter->d1 = 0;
iter->d2 = 0;
iter->d3 = 0;
iter->d4 = 0;
if (next_keylen == 0) {
/* iterate from start to end of NULL-terminated key string */
for (o = iter->key; o < len; o++) {
if (!data[o]) {
iter->d1 = ++o;
goto fill_data_fields;
}
}
} else {
o = iter->key + next_keylen + 1;
iter->d1 = o;
goto fill_data_fields;
}
goto mark_invalid;
fill_data_fields:
*key = bson_iter_key_unsafe (iter);
*bson_type = ITER_TYPE (iter);
switch (*bson_type) {
case BSON_TYPE_DATE_TIME:
case BSON_TYPE_DOUBLE:
case BSON_TYPE_INT64:
case BSON_TYPE_TIMESTAMP:
iter->next_off = o + 8;
break;
case BSON_TYPE_CODE:
case BSON_TYPE_SYMBOL:
case BSON_TYPE_UTF8: {
uint32_t l;
if ((o + 4) >= len) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if (l > (len - (o + 4))) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + 4 + l;
/*
* Make sure the string length includes the NUL byte.
*/
if (BSON_UNLIKELY ((l == 0) || (iter->next_off >= len))) {
iter->err_off = o;
goto mark_invalid;
}
/*
* Make sure the last byte is a NUL byte.
*/
if (BSON_UNLIKELY ((iter->raw + iter->d2)[l - 1] != '\0')) {
iter->err_off = o + 4 + l - 1;
goto mark_invalid;
}
} break;
case BSON_TYPE_BINARY: {
bson_subtype_t subtype;
uint32_t l;
if (o >= (len - 4)) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
iter->d3 = o + 5;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if (l >= (len - o)) {
iter->err_off = o;
goto mark_invalid;
}
subtype = *(iter->raw + iter->d2);
if (subtype == BSON_SUBTYPE_BINARY_DEPRECATED) {
int32_t binary_len;
if (l < 4) {
iter->err_off = o;
goto mark_invalid;
}
/* subtype 2 has a redundant length header in the data */
memcpy (&binary_len, (iter->raw + iter->d3), sizeof (binary_len));
binary_len = BSON_UINT32_FROM_LE (binary_len);
if (binary_len + 4 != l) {
iter->err_off = iter->d3;
goto mark_invalid;
}
}
iter->next_off = o + 5 + l;
} break;
case BSON_TYPE_ARRAY:
case BSON_TYPE_DOCUMENT: {
uint32_t l;
if (o >= (len - 4)) {
iter->err_off = o;
goto mark_invalid;
}
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if ((l > len) || (l > (len - o))) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + l;
} break;
case BSON_TYPE_OID:
iter->next_off = o + 12;
break;
case BSON_TYPE_BOOL: {
char val;
if (iter->d1 >= len) {
iter->err_off = o;
goto mark_invalid;
}
memcpy (&val, iter->raw + iter->d1, 1);
if (val != 0x00 && val != 0x01) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + 1;
} break;
case BSON_TYPE_REGEX: {
bool eor = false;
bool eoo = false;
for (; o < len; o++) {
if (!data[o]) {
iter->d2 = ++o;
eor = true;
break;
}
}
if (!eor) {
iter->err_off = iter->next_off;
goto mark_invalid;
}
for (; o < len; o++) {
if (!data[o]) {
eoo = true;
break;
}
}
if (!eoo) {
iter->err_off = iter->next_off;
goto mark_invalid;
}
iter->next_off = o + 1;
} break;
case BSON_TYPE_DBPOINTER: {
uint32_t l;
if (o >= (len - 4)) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
/* Check valid string length. l counts '\0' but not 4 bytes for itself. */
if (l == 0 || l > (len - o - 4)) {
iter->err_off = o;
goto mark_invalid;
}
if (*(iter->raw + o + l + 3)) {
/* not null terminated */
iter->err_off = o + l + 3;
goto mark_invalid;
}
iter->d3 = o + 4 + l;
iter->next_off = o + 4 + l + 12;
} break;
case BSON_TYPE_CODEWSCOPE: {
uint32_t l;
uint32_t doclen;
if ((len < 19) || (o >= (len - 14))) {
iter->err_off = o;
goto mark_invalid;
}
iter->d2 = o + 4;
iter->d3 = o + 8;
memcpy (&l, iter->raw + iter->d1, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if ((l < 14) || (l >= (len - o))) {
iter->err_off = o;
goto mark_invalid;
}
iter->next_off = o + l;
if (iter->next_off >= len) {
iter->err_off = o;
goto mark_invalid;
}
memcpy (&l, iter->raw + iter->d2, sizeof (l));
l = BSON_UINT32_FROM_LE (l);
if (l == 0 || l >= (len - o - 4 - 4)) {
iter->err_off = o;
goto mark_invalid;
}
if ((o + 4 + 4 + l + 4) >= iter->next_off) {
iter->err_off = o + 4;
goto mark_invalid;
}
iter->d4 = o + 4 + 4 + l;
memcpy (&doclen, iter->raw + iter->d4, sizeof (doclen));
doclen = BSON_UINT32_FROM_LE (doclen);
if ((o + 4 + 4 + l + doclen) != iter->next_off) {
iter->err_off = o + 4 + 4 + l;
goto mark_invalid;
}
} break;
case BSON_TYPE_INT32:
iter->next_off = o + 4;
break;
case BSON_TYPE_DECIMAL128:
iter->next_off = o + 16;
break;
case BSON_TYPE_MAXKEY:
case BSON_TYPE_MINKEY:
case BSON_TYPE_NULL:
case BSON_TYPE_UNDEFINED:
iter->next_off = o;
break;
default:
*unsupported = true;
/* FALL THROUGH */
case BSON_TYPE_EOD:
iter->err_off = o;
goto mark_invalid;
}
/*
* Check to see if any of the field locations would overflow the
* current BSON buffer. If so, set the error location to the offset
* of where the field starts.
*/
if (iter->next_off >= len) {
iter->err_off = o;
goto mark_invalid;
}
iter->err_off = 0;
return true;
mark_invalid:
iter->raw = NULL;
iter->len = 0;
iter->next_off = 0;
return false;
}
| 1 | CVE-2018-16790 | 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,989 |
linux | b57a55e2200ede754e4dc9cce4ba9402544b9365 | SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
unsigned int *nbytes, char **buf, int *buf_type)
{
struct smb_rqst rqst;
int resp_buftype, rc = -EACCES;
struct smb2_read_plain_req *req = NULL;
struct smb2_read_rsp *rsp = NULL;
struct kvec iov[1];
struct kvec rsp_iov;
unsigned int total_len;
int flags = CIFS_LOG_ERROR;
struct cifs_ses *ses = io_parms->tcon->ses;
*nbytes = 0;
rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
if (rc)
return rc;
if (smb3_encryption_required(io_parms->tcon))
flags |= CIFS_TRANSFORM_REQ;
iov[0].iov_base = (char *)req;
iov[0].iov_len = total_len;
memset(&rqst, 0, sizeof(struct smb_rqst));
rqst.rq_iov = iov;
rqst.rq_nvec = 1;
rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
if (rc) {
if (rc != -ENODATA) {
cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
cifs_dbg(VFS, "Send error in read = %d\n", rc);
trace_smb3_read_err(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, io_parms->length,
rc);
} else
trace_smb3_read_done(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, 0);
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
return rc == -ENODATA ? 0 : rc;
} else
trace_smb3_read_done(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, io_parms->length);
cifs_small_buf_release(req);
*nbytes = le32_to_cpu(rsp->DataLength);
if ((*nbytes > CIFS_MAX_MSGSIZE) ||
(*nbytes > io_parms->length)) {
cifs_dbg(FYI, "bad length %d for count %d\n",
*nbytes, io_parms->length);
rc = -EIO;
*nbytes = 0;
}
if (*buf) {
memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
} else if (resp_buftype != CIFS_NO_BUFFER) {
*buf = rsp_iov.iov_base;
if (resp_buftype == CIFS_SMALL_BUFFER)
*buf_type = CIFS_SMALL_BUFFER;
else if (resp_buftype == CIFS_LARGE_BUFFER)
*buf_type = CIFS_LARGE_BUFFER;
}
return rc;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,278 |
ImageMagick | f6e9d0d9955e85bdd7540b251cd50d598dacc5e6 | static Image *ReadICONImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
IconFile
icon_file;
IconInfo
icon_info;
Image
*image;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
size_t
bit,
byte,
bytes_per_line,
one,
scanline_pad;
ssize_t
count,
offset,
y;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"%s",image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
icon_file.reserved=(short) ReadBlobLSBShort(image);
icon_file.resource_type=(short) ReadBlobLSBShort(image);
icon_file.count=(short) ReadBlobLSBShort(image);
if ((icon_file.reserved != 0) ||
((icon_file.resource_type != 1) && (icon_file.resource_type != 2)) ||
(icon_file.count > MaxIcons))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
for (i=0; i < icon_file.count; i++)
{
icon_file.directory[i].width=(unsigned char) ReadBlobByte(image);
icon_file.directory[i].height=(unsigned char) ReadBlobByte(image);
icon_file.directory[i].colors=(unsigned char) ReadBlobByte(image);
icon_file.directory[i].reserved=(unsigned char) ReadBlobByte(image);
icon_file.directory[i].planes=(unsigned short) ReadBlobLSBShort(image);
icon_file.directory[i].bits_per_pixel=(unsigned short)
ReadBlobLSBShort(image);
icon_file.directory[i].size=ReadBlobLSBLong(image);
icon_file.directory[i].offset=ReadBlobLSBLong(image);
}
one=1;
for (i=0; i < icon_file.count; i++)
{
/*
Verify Icon identifier.
*/
offset=(ssize_t) SeekBlob(image,(MagickOffsetType)
icon_file.directory[i].offset,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
icon_info.size=ReadBlobLSBLong(image);
icon_info.width=(unsigned char) ((int) ReadBlobLSBLong(image));
icon_info.height=(unsigned char) ((int) ReadBlobLSBLong(image)/2);
icon_info.planes=ReadBlobLSBShort(image);
icon_info.bits_per_pixel=ReadBlobLSBShort(image);
if (((icon_info.planes == 18505) && (icon_info.bits_per_pixel == 21060)) ||
(icon_info.size == 0x474e5089))
{
Image
*icon_image;
ImageInfo
*read_info;
size_t
length;
unsigned char
*png;
/*
Icon image encoded as a compressed PNG image.
*/
length=icon_file.directory[i].size;
png=(unsigned char *) AcquireQuantumMemory(length+16,sizeof(*png));
if (png == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) CopyMagickMemory(png,"\211PNG\r\n\032\n\000\000\000\015",12);
png[12]=(unsigned char) icon_info.planes;
png[13]=(unsigned char) (icon_info.planes >> 8);
png[14]=(unsigned char) icon_info.bits_per_pixel;
png[15]=(unsigned char) (icon_info.bits_per_pixel >> 8);
count=ReadBlob(image,length-16,png+16);
icon_image=(Image *) NULL;
if (count > 0)
{
read_info=CloneImageInfo(image_info);
(void) CopyMagickString(read_info->magick,"PNG",MaxTextExtent);
icon_image=BlobToImage(read_info,png,length+16,exception);
read_info=DestroyImageInfo(read_info);
}
png=(unsigned char *) RelinquishMagickMemory(png);
if (icon_image == (Image *) NULL)
{
if (count != (ssize_t) (length-16))
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
image=DestroyImageList(image);
return((Image *) NULL);
}
DestroyBlob(icon_image);
icon_image->blob=ReferenceBlob(image->blob);
ReplaceImageInList(&image,icon_image);
icon_image->scene=i;
}
else
{
if (icon_info.bits_per_pixel > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
icon_info.compression=ReadBlobLSBLong(image);
icon_info.image_size=ReadBlobLSBLong(image);
icon_info.x_pixels=ReadBlobLSBLong(image);
icon_info.y_pixels=ReadBlobLSBLong(image);
icon_info.number_colors=ReadBlobLSBLong(image);
icon_info.colors_important=ReadBlobLSBLong(image);
image->matte=MagickTrue;
image->columns=(size_t) icon_file.directory[i].width;
if ((ssize_t) image->columns > icon_info.width)
image->columns=(size_t) icon_info.width;
if (image->columns == 0)
image->columns=256;
image->rows=(size_t) icon_file.directory[i].height;
if ((ssize_t) image->rows > icon_info.height)
image->rows=(size_t) icon_info.height;
if (image->rows == 0)
image->rows=256;
image->depth=icon_info.bits_per_pixel;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene = %.20g",(double) i);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" size = %.20g",(double) icon_info.size);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" width = %.20g",(double) icon_file.directory[i].width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" height = %.20g",(double) icon_file.directory[i].height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" colors = %.20g",(double ) icon_info.number_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" planes = %.20g",(double) icon_info.planes);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" bpp = %.20g",(double) icon_info.bits_per_pixel);
}
if ((icon_info.number_colors != 0) || (icon_info.bits_per_pixel <= 16U))
{
image->storage_class=PseudoClass;
image->colors=icon_info.number_colors;
if (image->colors == 0)
image->colors=one << icon_info.bits_per_pixel;
}
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
unsigned char
*icon_colormap;
/*
Read Icon raster colormap.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
image->colors,4UL*sizeof(*icon_colormap));
if (icon_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) (4*image->colors),icon_colormap);
if (count != (ssize_t) (4*image->colors))
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
p=icon_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].blue=(Quantum) ScaleCharToQuantum(*p++);
image->colormap[i].green=(Quantum) ScaleCharToQuantum(*p++);
image->colormap[i].red=(Quantum) ScaleCharToQuantum(*p++);
p++;
}
icon_colormap=(unsigned char *) RelinquishMagickMemory(icon_colormap);
}
/*
Convert Icon raster image to pixel packets.
*/
if ((image_info->ping != MagickFalse) &&
(image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
bytes_per_line=(((image->columns*icon_info.bits_per_pixel)+31) &
~31) >> 3;
(void) bytes_per_line;
scanline_pad=((((image->columns*icon_info.bits_per_pixel)+31) & ~31)-
(image->columns*icon_info.bits_per_pixel)) >> 3;
switch (icon_info.bits_per_pixel)
{
case 1:
{
/*
Convert bitmap scanline.
*/
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) (image->columns-7); x+=8)
{
byte=(size_t) ReadBlobByte(image);
for (bit=0; bit < 8; bit++)
SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ?
0x01 : 0x00));
}
if ((image->columns % 8) != 0)
{
byte=(size_t) ReadBlobByte(image);
for (bit=0; bit < (image->columns % 8); bit++)
SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ?
0x01 : 0x00));
}
for (x=0; x < (ssize_t) scanline_pad; x++)
(void) ReadBlobByte(image);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,image->rows-y-1,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 4:
{
/*
Read 4-bit Icon scanline.
*/
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
byte=(size_t) ReadBlobByte(image);
SetPixelIndex(indexes+x,((byte >> 4) & 0xf));
SetPixelIndex(indexes+x+1,((byte) & 0xf));
}
if ((image->columns % 2) != 0)
{
byte=(size_t) ReadBlobByte(image);
SetPixelIndex(indexes+x,((byte >> 4) & 0xf));
}
for (x=0; x < (ssize_t) scanline_pad; x++)
(void) ReadBlobByte(image);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,image->rows-y-1,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 8:
{
/*
Convert PseudoColor scanline.
*/
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
byte=(size_t) ReadBlobByte(image);
SetPixelIndex(indexes+x,byte);
}
for (x=0; x < (ssize_t) scanline_pad; x++)
(void) ReadBlobByte(image);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,image->rows-y-1,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 16:
{
/*
Convert PseudoColor scanline.
*/
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
byte=(size_t) ReadBlobByte(image);
byte|=(size_t) (ReadBlobByte(image) << 8);
SetPixelIndex(indexes+x,byte);
}
for (x=0; x < (ssize_t) scanline_pad; x++)
(void) ReadBlobByte(image);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,image->rows-y-1,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 24:
case 32:
{
/*
Convert DirectColor scanline.
*/
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
if (icon_info.bits_per_pixel == 32)
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
q++;
}
if (icon_info.bits_per_pixel == 24)
for (x=0; x < (ssize_t) scanline_pad; x++)
(void) ReadBlobByte(image);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,image->rows-y-1,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (image_info->ping == MagickFalse)
(void) SyncImage(image);
if (icon_info.bits_per_pixel != 32)
{
/*
Read the ICON alpha mask.
*/
image->storage_class=DirectClass;
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
byte=(size_t) ReadBlobByte(image);
for (bit=0; bit < 8; bit++)
SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ?
TransparentOpacity : OpaqueOpacity));
}
if ((image->columns % 8) != 0)
{
byte=(size_t) ReadBlobByte(image);
for (bit=0; bit < (image->columns % 8); bit++)
SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ?
TransparentOpacity : OpaqueOpacity));
}
if ((image->columns % 32) != 0)
for (x=0; x < (ssize_t) ((32-(image->columns % 32))/8); x++)
(void) ReadBlobByte(image);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (i < (ssize_t) (icon_file.count-1))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 1 | CVE-2016-10066 | 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,108 |
poppler | 58e04a08afee39370283c494ee2e4e392fd3b684 | int JBIG2MMRDecoder::getBlackCode() {
const CCITTCode *p;
Guint code;
if (bufLen == 0) {
buf = str->getChar() & 0xff;
bufLen = 8;
++nBytesRead;
}
while (1) {
if (bufLen >= 10 && ((buf >> (bufLen - 6)) & 0x3f) == 0) {
if (bufLen <= 13) {
code = buf << (13 - bufLen);
} else {
code = buf >> (bufLen - 13);
}
p = &blackTab1[code & 0x7f];
} else if (bufLen >= 7 && ((buf >> (bufLen - 4)) & 0x0f) == 0 &&
((buf >> (bufLen - 6)) & 0x03) != 0) {
if (bufLen <= 12) {
code = buf << (12 - bufLen);
} else {
code = buf >> (bufLen - 12);
}
if (unlikely((code & 0xff) < 64)) {
break;
}
p = &blackTab2[(code & 0xff) - 64];
} else {
if (bufLen <= 6) {
code = buf << (6 - bufLen);
} else {
code = buf >> (bufLen - 6);
}
p = &blackTab3[code & 0x3f];
}
if (p->bits > 0 && p->bits <= (int)bufLen) {
bufLen -= p->bits;
return p->n;
}
if (bufLen >= 13) {
break;
}
buf = (buf << 8) | (str->getChar() & 0xff);
bufLen += 8;
++nBytesRead;
}
error(errSyntaxError, str->getPos(), "Bad black code in JBIG2 MMR stream");
--bufLen;
return 1;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,248 |
libplist | fbd8494d5e4e46bf2e90cb6116903e404374fb56 | static plist_t parse_data_node(const char **bnode, uint64_t size)
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_DATA;
data->length = size;
data->buff = (uint8_t *) malloc(sizeof(uint8_t) * size);
memcpy(data->buff, *bnode, sizeof(uint8_t) * size);
return node_create(NULL, data);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,841 |
Android | acc192347665943ca674acf117e4f74a88436922 | MediaBuffer *FLACParser::readBuffer(bool doSeek, FLAC__uint64 sample)
{
mWriteRequested = true;
mWriteCompleted = false;
if (doSeek) {
if (!FLAC__stream_decoder_seek_absolute(mDecoder, sample)) {
ALOGE("FLACParser::readBuffer seek to sample %lld failed", (long long)sample);
return NULL;
}
ALOGV("FLACParser::readBuffer seek to sample %lld succeeded", (long long)sample);
} else {
if (!FLAC__stream_decoder_process_single(mDecoder)) {
ALOGE("FLACParser::readBuffer process_single failed");
return NULL;
}
}
if (!mWriteCompleted) {
ALOGV("FLACParser::readBuffer write did not complete");
return NULL;
}
unsigned blocksize = mWriteHeader.blocksize;
if (blocksize == 0 || blocksize > getMaxBlockSize()) {
ALOGE("FLACParser::readBuffer write invalid blocksize %u", blocksize);
return NULL;
}
if (mWriteHeader.sample_rate != getSampleRate() ||
mWriteHeader.channels != getChannels() ||
mWriteHeader.bits_per_sample != getBitsPerSample()) {
ALOGE("FLACParser::readBuffer write changed parameters mid-stream: %d/%d/%d -> %d/%d/%d",
getSampleRate(), getChannels(), getBitsPerSample(),
mWriteHeader.sample_rate, mWriteHeader.channels, mWriteHeader.bits_per_sample);
return NULL;
}
CHECK(mGroup != NULL);
MediaBuffer *buffer;
status_t err = mGroup->acquire_buffer(&buffer);
if (err != OK) {
return NULL;
}
size_t bufferSize = blocksize * getChannels() * sizeof(short);
CHECK(bufferSize <= mMaxBufferSize);
short *data = (short *) buffer->data();
buffer->set_range(0, bufferSize);
(*mCopy)(data, mWriteBuffer, blocksize, getChannels());
CHECK(mWriteHeader.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
FLAC__uint64 sampleNumber = mWriteHeader.number.sample_number;
int64_t timeUs = (1000000LL * sampleNumber) / getSampleRate();
buffer->meta_data()->setInt64(kKeyTime, timeUs);
buffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
return buffer;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,814 |
file | e96f86b5311572be1360ee0bb05d4926f8df3189 | file_buffer(struct magic_set *ms, int fd, const char *inname __attribute__ ((unused)),
const void *buf, size_t nb)
{
int m = 0, rv = 0, looks_text = 0;
int mime = ms->flags & MAGIC_MIME;
const unsigned char *ubuf = CAST(const unsigned char *, buf);
unichar *u8buf = NULL;
size_t ulen;
const char *code = NULL;
const char *code_mime = "binary";
const char *type = "application/octet-stream";
const char *def = "data";
const char *ftype = NULL;
if (nb == 0) {
def = "empty";
type = "application/x-empty";
goto simple;
} else if (nb == 1) {
def = "very short file (no magic)";
goto simple;
}
if ((ms->flags & MAGIC_NO_CHECK_ENCODING) == 0) {
looks_text = file_encoding(ms, ubuf, nb, &u8buf, &ulen,
&code, &code_mime, &ftype);
}
#ifdef __EMX__
if ((ms->flags & MAGIC_NO_CHECK_APPTYPE) == 0 && inname) {
switch (file_os2_apptype(ms, inname, buf, nb)) {
case -1:
return -1;
case 0:
break;
default:
return 1;
}
}
#endif
#if HAVE_FORK
/* try compression stuff */
if ((ms->flags & MAGIC_NO_CHECK_COMPRESS) == 0)
if ((m = file_zmagic(ms, fd, inname, ubuf, nb)) != 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "zmagic %d\n", m);
goto done_encoding;
}
#endif
/* Check if we have a tar file */
if ((ms->flags & MAGIC_NO_CHECK_TAR) == 0)
if ((m = file_is_tar(ms, ubuf, nb)) != 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "tar %d\n", m);
goto done;
}
/* Check if we have a CDF file */
if ((ms->flags & MAGIC_NO_CHECK_CDF) == 0)
if ((m = file_trycdf(ms, fd, ubuf, nb)) != 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "cdf %d\n", m);
goto done;
}
/* try soft magic tests */
if ((ms->flags & MAGIC_NO_CHECK_SOFT) == 0)
if ((m = file_softmagic(ms, ubuf, nb, 0, NULL, BINTEST,
looks_text)) != 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "softmagic %d\n", m);
#ifdef BUILTIN_ELF
if ((ms->flags & MAGIC_NO_CHECK_ELF) == 0 && m == 1 &&
nb > 5 && fd != -1) {
/*
* We matched something in the file, so this
* *might* be an ELF file, and the file is at
* least 5 bytes long, so if it's an ELF file
* it has at least one byte past the ELF magic
* number - try extracting information from the
* ELF headers that cannot easily * be
* extracted with rules in the magic file.
*/
if ((m = file_tryelf(ms, fd, ubuf, nb)) != 0)
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr,
"elf %d\n", m);
}
#endif
goto done;
}
/* try text properties */
if ((ms->flags & MAGIC_NO_CHECK_TEXT) == 0) {
if ((m = file_ascmagic(ms, ubuf, nb, looks_text)) != 0) {
if ((ms->flags & MAGIC_DEBUG) != 0)
(void)fprintf(stderr, "ascmagic %d\n", m);
goto done;
}
}
simple:
/* give up */
m = 1;
if ((!mime || (mime & MAGIC_MIME_TYPE)) &&
file_printf(ms, "%s", mime ? type : def) == -1) {
rv = -1;
}
done:
if ((ms->flags & MAGIC_MIME_ENCODING) != 0) {
if (ms->flags & MAGIC_MIME_TYPE)
if (file_printf(ms, "; charset=") == -1)
rv = -1;
if (file_printf(ms, "%s", code_mime) == -1)
rv = -1;
}
#if HAVE_FORK
done_encoding:
#endif
free(u8buf);
if (rv)
return rv;
return m;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,261 |
linux-2.6 | be6aab0e9fa6d3c6d75aa1e38ac972d8b4ee82b8 | static int bad_inode_removexattr(struct dentry *dentry, const char *name)
{
return -EIO;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,018 |
gssproxy | cb761412e299ef907f22cd7c4146d50c8a792003 | int gp_workers_init(struct gssproxy_ctx *gpctx)
{
struct gp_workers *w;
struct gp_thread *t;
pthread_attr_t attr;
verto_ev *ev;
int vflags;
int ret;
int i;
w = calloc(1, sizeof(struct gp_workers));
if (!w) {
return ENOMEM;
}
w->gpctx = gpctx;
/* init global queue mutex */
ret = pthread_mutex_init(&w->lock, NULL);
if (ret) {
free(w);
return ENOMEM;
}
if (gpctx->config->num_workers > 0) {
w->num_threads = gpctx->config->num_workers;
} else {
w->num_threads = DEFAULT_WORKER_THREADS_NUM;
}
/* make thread joinable (portability) */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
/* init all workers */
for (i = 0; i < w->num_threads; i++) {
t = calloc(1, sizeof(struct gp_thread));
if (!t) {
ret = -1;
goto done;
}
t->pool = w;
ret = pthread_cond_init(&t->cond_wakeup, NULL);
if (ret) {
free(t);
goto done;
}
ret = pthread_mutex_init(&t->cond_mutex, NULL);
if (ret) {
free(t);
goto done;
}
ret = pthread_create(&t->tid, &attr, gp_worker_main, t);
if (ret) {
free(t);
goto done;
}
LIST_ADD(w->free_list, t);
}
/* add wakeup pipe, so that threads can hand back replies to the
* dispatcher */
ret = pipe2(w->sig_pipe, O_NONBLOCK | O_CLOEXEC);
if (ret == -1) {
goto done;
}
vflags = VERTO_EV_FLAG_PERSIST | VERTO_EV_FLAG_IO_READ;
ev = verto_add_io(gpctx->vctx, vflags, gp_handle_reply, w->sig_pipe[0]);
if (!ev) {
ret = -1;
goto done;
}
verto_set_private(ev, w, NULL);
gpctx->workers = w;
ret = 0;
done:
if (ret) {
gp_workers_free(w);
}
return ret;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,611 |
c-blosc2 | c4c6470e88210afc95262c8b9fcc27e30ca043ee | static int blosc_c(struct thread_context* thread_context, int32_t bsize,
int32_t leftoverblock, int32_t ntbytes, int32_t maxbytes,
const uint8_t* src, const int32_t offset, uint8_t* dest,
uint8_t* tmp, uint8_t* tmp2) {
blosc2_context* context = thread_context->parent_context;
int dont_split = (context->header_flags & 0x10) >> 4;
int dict_training = context->use_dict && context->dict_cdict == NULL;
int32_t j, neblock, nstreams;
int32_t cbytes; /* number of compressed bytes in split */
int32_t ctbytes = 0; /* number of compressed bytes in block */
int64_t maxout;
int32_t typesize = context->typesize;
const char* compname;
int accel;
const uint8_t* _src;
uint8_t *_tmp = tmp, *_tmp2 = tmp2;
uint8_t *_tmp3 = thread_context->tmp4;
int last_filter_index = last_filter(context->filters, 'c');
bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED;
if (last_filter_index >= 0 || context->prefilter != NULL) {
/* Apply the filter pipeline just for the prefilter */
if (memcpyed && context->prefilter != NULL) {
// We only need the prefilter output
_src = pipeline_c(thread_context, bsize, src, offset, dest, _tmp2, _tmp3);
if (_src == NULL) {
return -9; // signals a problem with the filter pipeline
}
return bsize;
}
/* Apply regular filter pipeline */
_src = pipeline_c(thread_context, bsize, src, offset, _tmp, _tmp2, _tmp3);
if (_src == NULL) {
return -9; // signals a problem with the filter pipeline
}
} else {
_src = src + offset;
}
assert(context->clevel > 0);
/* Calculate acceleration for different compressors */
accel = get_accel(context);
/* The number of compressed data streams for this block */
if (!dont_split && !leftoverblock && !dict_training) {
nstreams = (int32_t)typesize;
}
else {
nstreams = 1;
}
neblock = bsize / nstreams;
for (j = 0; j < nstreams; j++) {
if (!dict_training) {
dest += sizeof(int32_t);
ntbytes += sizeof(int32_t);
ctbytes += sizeof(int32_t);
}
// See if we have a run here
const uint8_t* ip = (uint8_t*)_src + j * neblock;
const uint8_t* ipbound = (uint8_t*)_src + (j + 1) * neblock;
if (get_run(ip, ipbound)) {
// A run. Encode the repeated byte as a negative length in the length of the split.
int32_t value = _src[j * neblock];
_sw32(dest - 4, -value);
continue;
}
maxout = neblock;
#if defined(HAVE_SNAPPY)
if (context->compcode == BLOSC_SNAPPY) {
maxout = (int32_t)snappy_max_compressed_length((size_t)neblock);
}
#endif /* HAVE_SNAPPY */
if (ntbytes + maxout > maxbytes) {
/* avoid buffer * overrun */
maxout = (int64_t)maxbytes - (int64_t)ntbytes;
if (maxout <= 0) {
return 0; /* non-compressible block */
}
}
if (dict_training) {
// We are in the build dict state, so don't compress
// TODO: copy only a percentage for sampling
memcpy(dest, _src + j * neblock, (unsigned int)neblock);
cbytes = (int32_t)neblock;
}
else if (context->compcode == BLOSC_BLOSCLZ) {
cbytes = blosclz_compress(context->clevel, _src + j * neblock,
(int)neblock, dest, (int)maxout);
}
#if defined(HAVE_LZ4)
else if (context->compcode == BLOSC_LZ4) {
void *hash_table = NULL;
#ifdef HAVE_IPP
hash_table = (void*)thread_context->lz4_hash_table;
#endif
cbytes = lz4_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, accel, hash_table);
}
else if (context->compcode == BLOSC_LZ4HC) {
cbytes = lz4hc_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, context->clevel);
}
#endif /* HAVE_LZ4 */
#if defined(HAVE_LIZARD)
else if (context->compcode == BLOSC_LIZARD) {
cbytes = lizard_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, accel);
}
#endif /* HAVE_LIZARD */
#if defined(HAVE_SNAPPY)
else if (context->compcode == BLOSC_SNAPPY) {
cbytes = snappy_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout);
}
#endif /* HAVE_SNAPPY */
#if defined(HAVE_ZLIB)
else if (context->compcode == BLOSC_ZLIB) {
cbytes = zlib_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, context->clevel);
}
#endif /* HAVE_ZLIB */
#if defined(HAVE_ZSTD)
else if (context->compcode == BLOSC_ZSTD) {
cbytes = zstd_wrap_compress(thread_context,
(char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, context->clevel);
}
#endif /* HAVE_ZSTD */
else {
blosc_compcode_to_compname(context->compcode, &compname);
fprintf(stderr, "Blosc has not been compiled with '%s' ", compname);
fprintf(stderr, "compression support. Please use one having it.");
return -5; /* signals no compression support */
}
if (cbytes > maxout) {
/* Buffer overrun caused by compression (should never happen) */
return -1;
}
if (cbytes < 0) {
/* cbytes should never be negative */
return -2;
}
if (!dict_training) {
if (cbytes == 0 || cbytes == neblock) {
/* The compressor has been unable to compress data at all. */
/* Before doing the copy, check that we are not running into a
buffer overflow. */
if ((ntbytes + neblock) > maxbytes) {
return 0; /* Non-compressible data */
}
memcpy(dest, _src + j * neblock, (unsigned int)neblock);
cbytes = neblock;
}
_sw32(dest - 4, cbytes);
}
dest += cbytes;
ntbytes += cbytes;
ctbytes += cbytes;
} /* Closes j < nstreams */
//printf("c%d", ctbytes);
return ctbytes;
} | 1 | CVE-2020-29367 | 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). | 3,844 |
php-src | 28022c9b1fd937436ab67bb3d61f652c108baf96 | PHP_FUNCTION(imagepalettetotruecolor)
{
zval *IM;
gdImagePtr im;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &IM) == FAILURE) {
return;
}
if ((im = (gdImagePtr)zend_fetch_resource(Z_RES_P(IM), "Image", le_gd)) == NULL) {
RETURN_FALSE;
}
if (gdImagePaletteToTrueColor(im) == 0) {
RETURN_FALSE;
}
RETURN_TRUE;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,108 |
ceph | 92da834cababc4dddd5dbbab5837310478d1e6d4 | int RGWCopyObj_ObjStore_S3::check_storage_class(const rgw_placement_rule& src_placement)
{
if (src_placement == s->dest_placement) {
/* can only copy object into itself if replacing attrs */
s->err.message = "This copy request is illegal because it is trying to copy "
"an object to itself without changing the object's metadata, "
"storage class, website redirect location or encryption attributes.";
ldpp_dout(this, 0) << s->err.message << dendl;
return -ERR_INVALID_REQUEST;
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,306 |
ImageMagick | c1b09bbec148f6ae11d0b686fdb89ac6dc0ab14e | static MagickBooleanType WritePICTImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
#define MaxCount 128
#define PictCropRegionOp 0x01
#define PictEndOfPictureOp 0xff
#define PictJPEGOp 0x8200
#define PictInfoOp 0x0C00
#define PictInfoSize 512
#define PictPixmapOp 0x9A
#define PictPICTOp 0x98
#define PictVersion 0x11
const StringInfo
*profile;
double
x_resolution,
y_resolution;
MagickBooleanType
status;
MagickOffsetType
offset;
PICTPixmap
pixmap;
PICTRectangle
bounds,
crop_rectangle,
destination_rectangle,
frame_rectangle,
size_rectangle,
source_rectangle;
register const Quantum
*p;
register ssize_t
i,
x;
size_t
bytes_per_line,
count,
row_bytes,
storage_class;
ssize_t
y;
unsigned char
*buffer,
*packed_scanline,
*scanline;
unsigned short
base_address,
transfer_mode;
/*
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 > 65535L) || (image->rows > 65535L))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Initialize image info.
*/
size_rectangle.top=0;
size_rectangle.left=0;
size_rectangle.bottom=(short) image->rows;
size_rectangle.right=(short) image->columns;
frame_rectangle=size_rectangle;
crop_rectangle=size_rectangle;
source_rectangle=size_rectangle;
destination_rectangle=size_rectangle;
base_address=0xff;
row_bytes=image->columns;
bounds.top=0;
bounds.left=0;
bounds.bottom=(short) image->rows;
bounds.right=(short) image->columns;
pixmap.version=0;
pixmap.pack_type=0;
pixmap.pack_size=0;
pixmap.pixel_type=0;
pixmap.bits_per_pixel=8;
pixmap.component_count=1;
pixmap.component_size=8;
pixmap.plane_bytes=0;
pixmap.table=0;
pixmap.reserved=0;
transfer_mode=0;
x_resolution=image->resolution.x != 0.0 ? image->resolution.x :
DefaultResolution;
y_resolution=image->resolution.y != 0.0 ? image->resolution.y :
DefaultResolution;
storage_class=image->storage_class;
if (image_info->compression == JPEGCompression)
storage_class=DirectClass;
if (storage_class == DirectClass)
{
pixmap.component_count=image->alpha_trait != UndefinedPixelTrait ? 4 : 3;
pixmap.pixel_type=16;
pixmap.bits_per_pixel=32;
pixmap.pack_type=0x04;
transfer_mode=0x40;
row_bytes=4*image->columns;
}
/*
Allocate memory.
*/
bytes_per_line=image->columns;
if (storage_class == DirectClass)
bytes_per_line*=image->alpha_trait != UndefinedPixelTrait ? 4 : 3;
buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer));
packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t)
(row_bytes+MaxCount),sizeof(*packed_scanline));
scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline));
if ((buffer == (unsigned char *) NULL) ||
(packed_scanline == (unsigned char *) NULL) ||
(scanline == (unsigned char *) NULL))
{
if (scanline != (unsigned char *) NULL)
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
if (packed_scanline != (unsigned char *) NULL)
packed_scanline=(unsigned char *) RelinquishMagickMemory(
packed_scanline);
if (buffer != (unsigned char *) NULL)
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) ResetMagickMemory(scanline,0,row_bytes);
(void) ResetMagickMemory(packed_scanline,0,(size_t) (row_bytes+MaxCount));
/*
Write header, header size, size bounding box, version, and reserved.
*/
(void) ResetMagickMemory(buffer,0,PictInfoSize);
(void) WriteBlob(image,PictInfoSize,buffer);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right);
(void) WriteBlobMSBShort(image,PictVersion);
(void) WriteBlobMSBShort(image,0x02ff); /* version #2 */
(void) WriteBlobMSBShort(image,PictInfoOp);
(void) WriteBlobMSBLong(image,0xFFFE0000UL);
/*
Write full size of the file, resolution, frame bounding box, and reserved.
*/
(void) WriteBlobMSBShort(image,(unsigned short) x_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) y_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right);
(void) WriteBlobMSBLong(image,0x00000000L);
profile=GetImageProfile(image,"iptc");
if (profile != (StringInfo *) NULL)
{
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0x1f2);
(void) WriteBlobMSBShort(image,(unsigned short)
(GetStringInfoLength(profile)+4));
(void) WriteBlobString(image,"8BIM");
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
}
profile=GetImageProfile(image,"icc");
if (profile != (StringInfo *) NULL)
{
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0xe0);
(void) WriteBlobMSBShort(image,(unsigned short)
(GetStringInfoLength(profile)+4));
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0xe0);
(void) WriteBlobMSBShort(image,4);
(void) WriteBlobMSBLong(image,0x00000002UL);
}
/*
Write crop region opcode and crop bounding box.
*/
(void) WriteBlobMSBShort(image,PictCropRegionOp);
(void) WriteBlobMSBShort(image,0xa);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right);
if (image_info->compression == JPEGCompression)
{
Image
*jpeg_image;
ImageInfo
*jpeg_info;
size_t
length;
unsigned char
*blob;
jpeg_image=CloneImage(image,0,0,MagickTrue,exception);
if (jpeg_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
jpeg_info=CloneImageInfo(image_info);
(void) CopyMagickString(jpeg_info->magick,"JPEG",MagickPathExtent);
length=0;
blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length,
exception);
jpeg_info=DestroyImageInfo(jpeg_info);
if (blob == (unsigned char *) NULL)
return(MagickFalse);
jpeg_image=DestroyImage(jpeg_image);
(void) WriteBlobMSBShort(image,PictJPEGOp);
(void) WriteBlobMSBLong(image,(unsigned int) length+154);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBLong(image,0x00010000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00010000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x40000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00400000UL);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) image->rows);
(void) WriteBlobMSBShort(image,(unsigned short) image->columns);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,768);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00566A70UL);
(void) WriteBlobMSBLong(image,0x65670000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000001UL);
(void) WriteBlobMSBLong(image,0x00016170UL);
(void) WriteBlobMSBLong(image,0x706C0000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBShort(image,768);
(void) WriteBlobMSBShort(image,(unsigned short) image->columns);
(void) WriteBlobMSBShort(image,(unsigned short) image->rows);
(void) WriteBlobMSBShort(image,(unsigned short) x_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) y_resolution);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x87AC0001UL);
(void) WriteBlobMSBLong(image,0x0B466F74UL);
(void) WriteBlobMSBLong(image,0x6F202D20UL);
(void) WriteBlobMSBLong(image,0x4A504547UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x0018FFFFUL);
(void) WriteBlob(image,length,blob);
if ((length & 0x01) != 0)
(void) WriteBlobByte(image,'\0');
blob=(unsigned char *) RelinquishMagickMemory(blob);
}
/*
Write picture opcode, row bytes, and picture bounding box, and version.
*/
if (storage_class == PseudoClass)
(void) WriteBlobMSBShort(image,PictPICTOp);
else
{
(void) WriteBlobMSBShort(image,PictPixmapOp);
(void) WriteBlobMSBLong(image,(size_t) base_address);
}
(void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000));
(void) WriteBlobMSBShort(image,(unsigned short) bounds.top);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.left);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.right);
/*
Write pack type, pack size, resolution, pixel type, and pixel size.
*/
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.version);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size);
(void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel);
/*
Write component count, size, plane bytes, table size, and reserved.
*/
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.table);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved);
if (storage_class == PseudoClass)
{
/*
Write image colormap.
*/
(void) WriteBlobMSBLong(image,0x00000000L); /* color seed */
(void) WriteBlobMSBShort(image,0L); /* color flags */
(void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1));
for (i=0; i < (ssize_t) image->colors; i++)
{
(void) WriteBlobMSBShort(image,(unsigned short) i);
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].red));
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].green));
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].blue));
}
}
/*
Write source and destination rectangle.
*/
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right);
(void) WriteBlobMSBShort(image,(unsigned short) transfer_mode);
/*
Write picture data.
*/
count=0;
if (storage_class == PseudoClass)
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
scanline[x]=(unsigned char) GetPixelIndex(image,p);
p+=GetPixelChannels(image);
}
count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF),
packed_scanline);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image_info->compression == JPEGCompression)
{
(void) ResetMagickMemory(scanline,0,row_bytes);
for (y=0; y < (ssize_t) image->rows; y++)
count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF),
packed_scanline);
}
else
{
register unsigned char
*blue,
*green,
*opacity,
*red;
red=scanline;
green=scanline+image->columns;
blue=scanline+2*image->columns;
opacity=scanline+3*image->columns;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
red=scanline;
green=scanline+image->columns;
blue=scanline+2*image->columns;
if (image->alpha_trait != UndefinedPixelTrait)
{
opacity=scanline;
red=scanline+image->columns;
green=scanline+2*image->columns;
blue=scanline+3*image->columns;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
*red++=ScaleQuantumToChar(GetPixelRed(image,p));
*green++=ScaleQuantumToChar(GetPixelGreen(image,p));
*blue++=ScaleQuantumToChar(GetPixelBlue(image,p));
if (image->alpha_trait != UndefinedPixelTrait)
*opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(image,p)));
p+=GetPixelChannels(image);
}
count+=EncodeImage(image,scanline,bytes_per_line,packed_scanline);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if ((count & 0x01) != 0)
(void) WriteBlobByte(image,'\0');
(void) WriteBlobMSBShort(image,PictEndOfPictureOp);
offset=TellBlob(image);
offset=SeekBlob(image,512,SEEK_SET);
(void) WriteBlobMSBShort(image,(unsigned short) offset);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
(void) CloseBlob(image);
return(MagickTrue);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,189 |
gnupg | ed8383c618e124cfa708c9ee87563fcdf2f4649c | build_key_bag (unsigned char *buffer, size_t buflen, char *salt,
const unsigned char *sha1hash, const char *keyidstr,
size_t *r_length)
{
size_t len[11], needed;
unsigned char *p, *keybag;
size_t keybaglen;
/* Walk 11 steps down to collect the info: */
/* 10. The data goes into an octet string. */
needed = compute_tag_length (buflen);
needed += buflen;
/* 9. Prepend the algorithm identifier. */
needed += DIM (data_3desiter2048);
/* 8. Put a sequence around. */
len[8] = needed;
needed += compute_tag_length (needed);
/* 7. Prepend a [0] tag. */
len[7] = needed;
needed += compute_tag_length (needed);
/* 6b. The attributes which are appended at the end. */
if (sha1hash)
needed += DIM (data_attrtemplate) + 20;
/* 6. Prepend the shroudedKeyBag OID. */
needed += 2 + DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag);
/* 5+4. Put all into two sequences. */
len[5] = needed;
needed += compute_tag_length ( needed);
len[4] = needed;
needed += compute_tag_length (needed);
/* 3. This all goes into an octet string. */
len[3] = needed;
needed += compute_tag_length (needed);
/* 2. Prepend another [0] tag. */
len[2] = needed;
needed += compute_tag_length (needed);
/* 1. Prepend the data OID. */
needed += 2 + DIM (oid_data);
/* 0. Prepend another sequence. */
len[0] = needed;
needed += compute_tag_length (needed);
/* Now that we have all length information, allocate a buffer. */
p = keybag = gcry_malloc (needed);
if (!keybag)
{
log_error ("error allocating buffer\n");
return NULL;
}
/* Walk 11 steps up to store the data. */
/* 0. Store the first sequence. */
p = store_tag_length (p, TAG_SEQUENCE, len[0]);
/* 1. Store the data OID. */
p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_data));
memcpy (p, oid_data, DIM (oid_data));
p += DIM (oid_data);
/* 2. Store a [0] tag. */
p = store_tag_length (p, 0xa0, len[2]);
/* 3. And an octet string. */
p = store_tag_length (p, TAG_OCTET_STRING, len[3]);
/* 4+5. Two sequences. */
p = store_tag_length (p, TAG_SEQUENCE, len[4]);
p = store_tag_length (p, TAG_SEQUENCE, len[5]);
/* 6. Store the shroudedKeyBag OID. */
p = store_tag_length (p, TAG_OBJECT_ID,
DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag));
memcpy (p, oid_pkcs_12_pkcs_8ShroudedKeyBag,
DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag));
p += DIM (oid_pkcs_12_pkcs_8ShroudedKeyBag);
/* 7. Store a [0] tag. */
p = store_tag_length (p, 0xa0, len[7]);
/* 8. Store a sequence. */
p = store_tag_length (p, TAG_SEQUENCE, len[8]);
/* 9. Now for the pre-encoded algorithm identifier and the salt. */
memcpy (p, data_3desiter2048, DIM (data_3desiter2048));
memcpy (p + DATA_3DESITER2048_SALT_OFF, salt, 8);
p += DIM (data_3desiter2048);
/* 10. And the octet string with the encrypted data. */
p = store_tag_length (p, TAG_OCTET_STRING, buflen);
memcpy (p, buffer, buflen);
p += buflen;
/* Append the attributes whose length we calculated at step 2b. */
if (sha1hash)
{
int i;
memcpy (p, data_attrtemplate, DIM (data_attrtemplate));
for (i=0; i < 8; i++)
p[DATA_ATTRTEMPLATE_KEYID_OFF+2*i+1] = keyidstr[i];
p += DIM (data_attrtemplate);
memcpy (p, sha1hash, 20);
p += 20;
}
keybaglen = p - keybag;
if (needed != keybaglen)
log_debug ("length mismatch: %lu, %lu\n",
(unsigned long)needed, (unsigned long)keybaglen);
*r_length = keybaglen;
return keybag;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,231 |
rabbitmq-c | fc85be7123050b91b054e45b91c78d3241a5047a | void amqp_release_buffers(amqp_connection_state_t state) {
int i;
ENFORCE_STATE(state, CONNECTION_STATE_IDLE);
for (i = 0; i < POOL_TABLE_SIZE; ++i) {
amqp_pool_table_entry_t *entry = state->pool_table[i];
for (; NULL != entry; entry = entry->next) {
amqp_maybe_release_buffers_on_channel(state, entry->channel);
}
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,891 |
net | 36d5fe6a000790f56039afe26834265db0a3ad4c | __enqueue_entry(struct nfqnl_instance *queue, struct nf_queue_entry *entry)
{
list_add_tail(&entry->list, &queue->queue_list);
queue->queue_total++;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,503 |
linux | 086ba77a6db00ed858ff07451bedee197df868c9 | static void perf_sysenter_disable(struct ftrace_event_call *call)
{
int num;
num = ((struct syscall_metadata *)call->data)->syscall_nr;
mutex_lock(&syscall_trace_lock);
sys_perf_refcount_enter--;
clear_bit(num, enabled_perf_enter_syscalls);
if (!sys_perf_refcount_enter)
unregister_trace_sys_enter(perf_syscall_enter, NULL);
mutex_unlock(&syscall_trace_lock);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,347 |
leptonica | 5ee24b398bb67666f6d173763eaaedd9c36fb1e5 | pixDitherOctindexWithCmap(PIX *pixs,
PIX *pixd,
l_uint32 *rtab,
l_uint32 *gtab,
l_uint32 *btab,
l_int32 *indexmap,
l_int32 difcap)
{
l_uint8 *bufu8r, *bufu8g, *bufu8b;
l_int32 i, j, w, h, wpld, octindex, cmapindex, success;
l_int32 rval, gval, bval, rc, gc, bc;
l_int32 dif, val1, val2, val3;
l_int32 *buf1r, *buf1g, *buf1b, *buf2r, *buf2g, *buf2b;
l_uint32 *datad, *lined;
PIXCMAP *cmap;
PROCNAME("pixDitherOctindexWithCmap");
if (!pixs || pixGetDepth(pixs) != 32)
return ERROR_INT("pixs undefined or not 32 bpp", procName, 1);
if (!pixd || pixGetDepth(pixd) != 8)
return ERROR_INT("pixd undefined or not 8 bpp", procName, 1);
if ((cmap = pixGetColormap(pixd)) == NULL)
return ERROR_INT("pixd not cmapped", procName, 1);
if (!rtab || !gtab || !btab || !indexmap)
return ERROR_INT("not all 4 tables defined", procName, 1);
pixGetDimensions(pixs, &w, &h, NULL);
if (pixGetWidth(pixd) != w || pixGetHeight(pixd) != h)
return ERROR_INT("pixs and pixd not same size", procName, 1);
success = TRUE;
bufu8r = bufu8g = bufu8b = NULL;
buf1r = buf1g = buf1b = buf2r = buf2g = buf2b = NULL;
bufu8r = (l_uint8 *)LEPT_CALLOC(w, sizeof(l_uint8));
bufu8g = (l_uint8 *)LEPT_CALLOC(w, sizeof(l_uint8));
bufu8b = (l_uint8 *)LEPT_CALLOC(w, sizeof(l_uint8));
buf1r = (l_int32 *)LEPT_CALLOC(w, sizeof(l_int32));
buf1g = (l_int32 *)LEPT_CALLOC(w, sizeof(l_int32));
buf1b = (l_int32 *)LEPT_CALLOC(w, sizeof(l_int32));
buf2r = (l_int32 *)LEPT_CALLOC(w, sizeof(l_int32));
buf2g = (l_int32 *)LEPT_CALLOC(w, sizeof(l_int32));
buf2b = (l_int32 *)LEPT_CALLOC(w, sizeof(l_int32));
if (!bufu8r || !bufu8g || !bufu8b || !buf1r || !buf1g ||
!buf1b || !buf2r || !buf2g || !buf2b) {
L_ERROR("buffer not made\n", procName);
success = FALSE;
goto buffer_cleanup;
}
/* Start by priming buf2; line 1 is above line 2 */
pixGetRGBLine(pixs, 0, bufu8r, bufu8g, bufu8b);
for (j = 0; j < w; j++) {
buf2r[j] = 64 * bufu8r[j];
buf2g[j] = 64 * bufu8g[j];
buf2b[j] = 64 * bufu8b[j];
}
datad = pixGetData(pixd);
wpld = pixGetWpl(pixd);
for (i = 0; i < h - 1; i++) {
/* Swap data 2 --> 1, and read in new line 2 */
memcpy(buf1r, buf2r, 4 * w);
memcpy(buf1g, buf2g, 4 * w);
memcpy(buf1b, buf2b, 4 * w);
pixGetRGBLine(pixs, i + 1, bufu8r, bufu8g, bufu8b);
for (j = 0; j < w; j++) {
buf2r[j] = 64 * bufu8r[j];
buf2g[j] = 64 * bufu8g[j];
buf2b[j] = 64 * bufu8b[j];
}
/* Dither */
lined = datad + i * wpld;
for (j = 0; j < w - 1; j++) {
rval = buf1r[j] / 64;
gval = buf1g[j] / 64;
bval = buf1b[j] / 64;
octindex = rtab[rval] | gtab[gval] | btab[bval];
cmapindex = indexmap[octindex] - 1;
SET_DATA_BYTE(lined, j, cmapindex);
pixcmapGetColor(cmap, cmapindex, &rc, &gc, &bc);
dif = buf1r[j] / 8 - 8 * rc;
if (difcap > 0) {
if (dif > difcap) dif = difcap;
if (dif < -difcap) dif = -difcap;
}
if (dif != 0) {
val1 = buf1r[j + 1] + 3 * dif;
val2 = buf2r[j] + 3 * dif;
val3 = buf2r[j + 1] + 2 * dif;
if (dif > 0) {
buf1r[j + 1] = L_MIN(16383, val1);
buf2r[j] = L_MIN(16383, val2);
buf2r[j + 1] = L_MIN(16383, val3);
} else {
buf1r[j + 1] = L_MAX(0, val1);
buf2r[j] = L_MAX(0, val2);
buf2r[j + 1] = L_MAX(0, val3);
}
}
dif = buf1g[j] / 8 - 8 * gc;
if (difcap > 0) {
if (dif > difcap) dif = difcap;
if (dif < -difcap) dif = -difcap;
}
if (dif != 0) {
val1 = buf1g[j + 1] + 3 * dif;
val2 = buf2g[j] + 3 * dif;
val3 = buf2g[j + 1] + 2 * dif;
if (dif > 0) {
buf1g[j + 1] = L_MIN(16383, val1);
buf2g[j] = L_MIN(16383, val2);
buf2g[j + 1] = L_MIN(16383, val3);
} else {
buf1g[j + 1] = L_MAX(0, val1);
buf2g[j] = L_MAX(0, val2);
buf2g[j + 1] = L_MAX(0, val3);
}
}
dif = buf1b[j] / 8 - 8 * bc;
if (difcap > 0) {
if (dif > difcap) dif = difcap;
if (dif < -difcap) dif = -difcap;
}
if (dif != 0) {
val1 = buf1b[j + 1] + 3 * dif;
val2 = buf2b[j] + 3 * dif;
val3 = buf2b[j + 1] + 2 * dif;
if (dif > 0) {
buf1b[j + 1] = L_MIN(16383, val1);
buf2b[j] = L_MIN(16383, val2);
buf2b[j + 1] = L_MIN(16383, val3);
} else {
buf1b[j + 1] = L_MAX(0, val1);
buf2b[j] = L_MAX(0, val2);
buf2b[j + 1] = L_MAX(0, val3);
}
}
}
/* Get last pixel in row; no downward propagation */
rval = buf1r[w - 1] / 64;
gval = buf1g[w - 1] / 64;
bval = buf1b[w - 1] / 64;
octindex = rtab[rval] | gtab[gval] | btab[bval];
cmapindex = indexmap[octindex] - 1;
SET_DATA_BYTE(lined, w - 1, cmapindex);
}
/* Get last row of pixels; no leftward propagation */
lined = datad + (h - 1) * wpld;
for (j = 0; j < w; j++) {
rval = buf2r[j] / 64;
gval = buf2g[j] / 64;
bval = buf2b[j] / 64;
octindex = rtab[rval] | gtab[gval] | btab[bval];
cmapindex = indexmap[octindex] - 1;
SET_DATA_BYTE(lined, j, cmapindex);
}
buffer_cleanup:
LEPT_FREE(bufu8r);
LEPT_FREE(bufu8g);
LEPT_FREE(bufu8b);
LEPT_FREE(buf1r);
LEPT_FREE(buf1g);
LEPT_FREE(buf1b);
LEPT_FREE(buf2r);
LEPT_FREE(buf2g);
LEPT_FREE(buf2b);
return (success) ? 0 : 1;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,200 |
file | 59e63838913eee47f5c120a6c53d4565af638158 | mconvert(struct magic_set *ms, struct magic *m, int flip)
{
union VALUETYPE *p = &ms->ms_value;
uint8_t type;
switch (type = cvt_flip(m->type, flip)) {
case FILE_BYTE:
cvt_8(p, m);
return 1;
case FILE_SHORT:
cvt_16(p, m);
return 1;
case FILE_LONG:
case FILE_DATE:
case FILE_LDATE:
cvt_32(p, m);
return 1;
case FILE_QUAD:
case FILE_QDATE:
case FILE_QLDATE:
case FILE_QWDATE:
cvt_64(p, m);
return 1;
case FILE_STRING:
case FILE_BESTRING16:
case FILE_LESTRING16: {
/* Null terminate and eat *trailing* return */
p->s[sizeof(p->s) - 1] = '\0';
return 1;
}
case FILE_PSTRING: {
size_t sz = file_pstring_length_size(m);
char *ptr1 = p->s, *ptr2 = ptr1 + sz;
size_t len = file_pstring_get_length(m, ptr1);
if (len >= sizeof(p->s)) {
/*
* The size of the pascal string length (sz)
* is 1, 2, or 4. We need at least 1 byte for NUL
* termination, but we've already truncated the
* string by p->s, so we need to deduct sz.
*/
len = sizeof(p->s) - sz;
}
while (len--)
*ptr1++ = *ptr2++;
*ptr1 = '\0';
return 1;
}
case FILE_BESHORT:
p->h = (short)((p->hs[0]<<8)|(p->hs[1]));
cvt_16(p, m);
return 1;
case FILE_BELONG:
case FILE_BEDATE:
case FILE_BELDATE:
p->l = (int32_t)
((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3]));
if (type == FILE_BELONG)
cvt_32(p, m);
return 1;
case FILE_BEQUAD:
case FILE_BEQDATE:
case FILE_BEQLDATE:
case FILE_BEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7]));
if (type == FILE_BEQUAD)
cvt_64(p, m);
return 1;
case FILE_LESHORT:
p->h = (short)((p->hs[1]<<8)|(p->hs[0]));
cvt_16(p, m);
return 1;
case FILE_LELONG:
case FILE_LEDATE:
case FILE_LELDATE:
p->l = (int32_t)
((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0]));
if (type == FILE_LELONG)
cvt_32(p, m);
return 1;
case FILE_LEQUAD:
case FILE_LEQDATE:
case FILE_LEQLDATE:
case FILE_LEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0]));
if (type == FILE_LEQUAD)
cvt_64(p, m);
return 1;
case FILE_MELONG:
case FILE_MEDATE:
case FILE_MELDATE:
p->l = (int32_t)
((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2]));
if (type == FILE_MELONG)
cvt_32(p, m);
return 1;
case FILE_FLOAT:
cvt_float(p, m);
return 1;
case FILE_BEFLOAT:
p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)|
((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]);
cvt_float(p, m);
return 1;
case FILE_LEFLOAT:
p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)|
((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]);
cvt_float(p, m);
return 1;
case FILE_DOUBLE:
cvt_double(p, m);
return 1;
case FILE_BEDOUBLE:
p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]);
cvt_double(p, m);
return 1;
case FILE_LEDOUBLE:
p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]);
cvt_double(p, m);
return 1;
case FILE_REGEX:
case FILE_SEARCH:
case FILE_DEFAULT:
case FILE_CLEAR:
case FILE_NAME:
case FILE_USE:
return 1;
default:
file_magerror(ms, "invalid type %d in mconvert()", m->type);
return 0;
}
}
| 1 | CVE-2014-9652 | 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,495 |
ImageMagick | ae04fa4be910255e5d363edebd77adeee99a525d | static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
BMPInfo
bmp_info;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
offset,
start_position;
MemoryInfo
*pixel_info;
Quantum
index;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bit,
bytes_per_line,
length;
ssize_t
count,
y;
unsigned char
magick[12],
*pixels;
unsigned int
blue,
green,
offset_bits,
red;
/*
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);
}
/*
Determine if this a BMP file.
*/
(void) memset(&bmp_info,0,sizeof(bmp_info));
bmp_info.ba_offset=0;
start_position=0;
offset_bits=0;
count=ReadBlob(image,2,magick);
if (count != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
PixelInfo
quantum_bits;
PixelPacket
shift;
/*
Verify BMP identifier.
*/
if (bmp_info.ba_offset == 0)
start_position=TellBlob(image)-2;
bmp_info.ba_offset=0;
while (LocaleNCompare((char *) magick,"BA",2) == 0)
{
bmp_info.file_size=ReadBlobLSBLong(image);
bmp_info.ba_offset=ReadBlobLSBLong(image);
bmp_info.offset_bits=ReadBlobLSBLong(image);
count=ReadBlob(image,2,magick);
if (count != 2)
break;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c",
magick[0],magick[1]);
if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) &&
(LocaleNCompare((char *) magick,"CI",2) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bmp_info.file_size=ReadBlobLSBLong(image);
(void) ReadBlobLSBLong(image);
bmp_info.offset_bits=ReadBlobLSBLong(image);
bmp_info.size=ReadBlobLSBLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u",
bmp_info.size);
if (bmp_info.size == 12)
{
/*
OS/2 BMP image file.
*/
(void) CopyMagickString(image->magick,"BMP2",MagickPathExtent);
bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image));
bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image));
bmp_info.planes=ReadBlobLSBShort(image);
bmp_info.bits_per_pixel=ReadBlobLSBShort(image);
bmp_info.x_pixels=0;
bmp_info.y_pixels=0;
bmp_info.number_colors=0;
bmp_info.compression=BI_RGB;
bmp_info.image_size=0;
bmp_info.alpha_mask=0;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format: OS/2 Bitmap");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Geometry: %.20gx%.20g",(double) bmp_info.width,(double)
bmp_info.height);
}
}
else
{
/*
Microsoft Windows BMP image file.
*/
if (bmp_info.size < 40)
ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError");
bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image);
bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image);
bmp_info.planes=ReadBlobLSBShort(image);
bmp_info.bits_per_pixel=ReadBlobLSBShort(image);
bmp_info.compression=ReadBlobLSBLong(image);
bmp_info.image_size=ReadBlobLSBLong(image);
bmp_info.x_pixels=ReadBlobLSBLong(image);
bmp_info.y_pixels=ReadBlobLSBLong(image);
bmp_info.number_colors=ReadBlobLSBLong(image);
bmp_info.colors_important=ReadBlobLSBLong(image);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format: MS Windows bitmap");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Geometry: %.20gx%.20g",(double) bmp_info.width,(double)
bmp_info.height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel);
switch (bmp_info.compression)
{
case BI_RGB:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_RGB");
break;
}
case BI_RLE4:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_RLE4");
break;
}
case BI_RLE8:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_RLE8");
break;
}
case BI_BITFIELDS:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_BITFIELDS");
break;
}
case BI_PNG:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_PNG");
break;
}
case BI_JPEG:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: BI_JPEG");
break;
}
default:
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression: UNKNOWN (%u)",bmp_info.compression);
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %u",bmp_info.number_colors);
}
bmp_info.red_mask=ReadBlobLSBLong(image);
bmp_info.green_mask=ReadBlobLSBLong(image);
bmp_info.blue_mask=ReadBlobLSBLong(image);
if (bmp_info.size > 40)
{
double
gamma;
/*
Read color management information.
*/
bmp_info.alpha_mask=ReadBlobLSBLong(image);
bmp_info.colorspace=ReadBlobLSBSignedLong(image);
/*
Decode 2^30 fixed point formatted CIE primaries.
*/
# define BMP_DENOM ((double) 0x40000000)
bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM;
bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM;
gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+
bmp_info.red_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.red_primary.x*=gamma;
bmp_info.red_primary.y*=gamma;
image->chromaticity.red_primary.x=bmp_info.red_primary.x;
image->chromaticity.red_primary.y=bmp_info.red_primary.y;
gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+
bmp_info.green_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.green_primary.x*=gamma;
bmp_info.green_primary.y*=gamma;
image->chromaticity.green_primary.x=bmp_info.green_primary.x;
image->chromaticity.green_primary.y=bmp_info.green_primary.y;
gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+
bmp_info.blue_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.blue_primary.x*=gamma;
bmp_info.blue_primary.y*=gamma;
image->chromaticity.blue_primary.x=bmp_info.blue_primary.x;
image->chromaticity.blue_primary.y=bmp_info.blue_primary.y;
/*
Decode 16^16 fixed point formatted gamma_scales.
*/
bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000;
bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000;
bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000;
/*
Compute a single gamma from the BMP 3-channel gamma.
*/
image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+
bmp_info.gamma_scale.z)/3.0;
}
else
(void) CopyMagickString(image->magick,"BMP3",MagickPathExtent);
if (bmp_info.size > 108)
{
size_t
intent;
/*
Read BMP Version 5 color management information.
*/
intent=ReadBlobLSBLong(image);
switch ((int) intent)
{
case LCS_GM_BUSINESS:
{
image->rendering_intent=SaturationIntent;
break;
}
case LCS_GM_GRAPHICS:
{
image->rendering_intent=RelativeIntent;
break;
}
case LCS_GM_IMAGES:
{
image->rendering_intent=PerceptualIntent;
break;
}
case LCS_GM_ABS_COLORIMETRIC:
{
image->rendering_intent=AbsoluteIntent;
break;
}
}
(void) ReadBlobLSBLong(image); /* Profile data */
(void) ReadBlobLSBLong(image); /* Profile size */
(void) ReadBlobLSBLong(image); /* Reserved byte */
}
}
if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"LengthAndFilesizeDoNotMatch","`%s'",image->filename);
else
if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image))
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'",
image->filename);
if (bmp_info.width <= 0)
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
if (bmp_info.height == 0)
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
if (bmp_info.planes != 1)
ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne");
if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) &&
(bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) &&
(bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32))
ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
if (bmp_info.bits_per_pixel < 16 &&
bmp_info.number_colors > (1U << bmp_info.bits_per_pixel))
ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors");
if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8))
ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4))
ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16))
ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel");
switch (bmp_info.compression)
{
case BI_RGB:
image->compression=NoCompression;
break;
case BI_RLE8:
case BI_RLE4:
image->compression=RLECompression;
break;
case BI_BITFIELDS:
break;
case BI_JPEG:
ThrowReaderException(CoderError,"JPEGCompressNotSupported");
case BI_PNG:
ThrowReaderException(CoderError,"PNGCompressNotSupported");
default:
ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression");
}
image->columns=(size_t) MagickAbsoluteValue(bmp_info.width);
image->rows=(size_t) MagickAbsoluteValue(bmp_info.height);
image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8;
image->alpha_trait=((bmp_info.alpha_mask != 0) &&
(bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait :
UndefinedPixelTrait;
if (bmp_info.bits_per_pixel < 16)
{
size_t
one;
image->storage_class=PseudoClass;
image->colors=bmp_info.number_colors;
one=1;
if (image->colors == 0)
image->colors=one << bmp_info.bits_per_pixel;
}
image->resolution.x=(double) bmp_info.x_pixels/100.0;
image->resolution.y=(double) bmp_info.y_pixels/100.0;
image->units=PixelsPerCentimeterResolution;
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));
if (image->storage_class == PseudoClass)
{
unsigned char
*bmp_colormap;
size_t
packet_size;
/*
Read BMP raster colormap.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading colormap of %.20g colors",(double) image->colors);
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t)
image->colors,4*sizeof(*bmp_colormap));
if (bmp_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if ((bmp_info.size == 12) || (bmp_info.size == 64))
packet_size=3;
else
packet_size=4;
offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET);
if (offset < 0)
{
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,packet_size*image->colors,bmp_colormap);
if (count != (ssize_t) (packet_size*image->colors))
{
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
p=bmp_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++);
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++);
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++);
if (packet_size == 4)
p++;
}
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
}
/*
Read image data.
*/
if (bmp_info.offset_bits == offset_bits)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
offset_bits=bmp_info.offset_bits;
offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (bmp_info.compression == BI_RLE4)
bmp_info.bits_per_pixel<<=1;
bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32);
length=(size_t) bytes_per_line*image->rows;
if (((MagickSizeType) length/8) > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
if ((bmp_info.compression == BI_RGB) ||
(bmp_info.compression == BI_BITFIELDS))
{
pixel_info=AcquireVirtualMemory(image->rows,
MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading pixels (%.20g bytes)",(double) length);
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
}
else
{
/*
Convert run-length encoded raster pixels.
*/
pixel_info=AcquireVirtualMemory(image->rows,
MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
status=DecodeImage(image,bmp_info.compression,pixels,
image->columns*image->rows);
if (status == MagickFalse)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnableToRunlengthDecodeImage");
}
}
/*
Convert BMP raster image to pixel packets.
*/
if (bmp_info.compression == BI_RGB)
{
/*
We should ignore the alpha value in BMP3 files but there have been
reports about 32 bit files with alpha. We do a quick check to see if
the alpha channel contains a value that is not zero (default value).
If we find a non zero value we asume the program that wrote the file
wants to use the alpha channel.
*/
if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) &&
(bmp_info.bits_per_pixel == 32))
{
bytes_per_line=4*(image->columns);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (*(p+3) != 0)
{
image->alpha_trait=BlendPixelTrait;
y=-1;
break;
}
p+=4;
}
}
}
bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ?
0xff000000U : 0U;
bmp_info.red_mask=0x00ff0000U;
bmp_info.green_mask=0x0000ff00U;
bmp_info.blue_mask=0x000000ffU;
if (bmp_info.bits_per_pixel == 16)
{
/*
RGB555.
*/
bmp_info.red_mask=0x00007c00U;
bmp_info.green_mask=0x000003e0U;
bmp_info.blue_mask=0x0000001fU;
}
}
(void) memset(&shift,0,sizeof(shift));
(void) memset(&quantum_bits,0,sizeof(quantum_bits));
if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))
{
register unsigned int
sample;
/*
Get shift and quantum bits info from bitfield masks.
*/
if (bmp_info.red_mask != 0)
while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)
{
shift.red++;
if (shift.red >= 32U)
break;
}
if (bmp_info.green_mask != 0)
while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)
{
shift.green++;
if (shift.green >= 32U)
break;
}
if (bmp_info.blue_mask != 0)
while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)
{
shift.blue++;
if (shift.blue >= 32U)
break;
}
if (bmp_info.alpha_mask != 0)
while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0)
{
shift.alpha++;
if (shift.alpha >= 32U)
break;
}
sample=shift.red;
while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.red=(MagickRealType) (sample-shift.red);
sample=shift.green;
while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.green=(MagickRealType) (sample-shift.green);
sample=shift.blue;
while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.blue=(MagickRealType) (sample-shift.blue);
sample=shift.alpha;
while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.alpha=(MagickRealType) (sample-shift.alpha);
}
switch (bmp_info.bits_per_pixel)
{
case 1:
{
/*
Convert bitmap scanline.
*/
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (image->columns % 8); bit++)
{
index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
break;
}
case 4:
{
/*
Convert PseudoColor scanline.
*/
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index,
exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 2) != 0)
{
ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index,
exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
x++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
break;
}
case 8:
{
/*
Convert PseudoColor scanline.
*/
if ((bmp_info.compression == BI_RLE8) ||
(bmp_info.compression == BI_RLE4))
bytes_per_line=image->columns;
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=(ssize_t) image->columns; x != 0; --x)
{
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
break;
}
case 16:
{
unsigned int
alpha,
pixel;
/*
Convert bitfield encoded 16-bit PseudoColor scanline.
*/
if ((bmp_info.compression != BI_RGB) &&
(bmp_info.compression != BI_BITFIELDS))
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnrecognizedImageCompression");
}
bytes_per_line=2*(image->columns+image->columns % 2);
image->storage_class=DirectClass;
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(unsigned int) (*p++);
pixel|=(*p++) << 8;
red=((pixel & bmp_info.red_mask) << shift.red) >> 16;
if (quantum_bits.red == 5)
red|=((red & 0xe000) >> 5);
if (quantum_bits.red <= 8)
red|=((red & 0xff00) >> 8);
green=((pixel & bmp_info.green_mask) << shift.green) >> 16;
if (quantum_bits.green == 5)
green|=((green & 0xe000) >> 5);
if (quantum_bits.green == 6)
green|=((green & 0xc000) >> 6);
if (quantum_bits.green <= 8)
green|=((green & 0xff00) >> 8);
blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;
if (quantum_bits.blue == 5)
blue|=((blue & 0xe000) >> 5);
if (quantum_bits.blue <= 8)
blue|=((blue & 0xff00) >> 8);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
if (quantum_bits.alpha <= 8)
alpha|=((alpha & 0xff00) >> 8);
SetPixelAlpha(image,ScaleShortToQuantum(
(unsigned short) alpha),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 24:
{
/*
Convert DirectColor scanline.
*/
bytes_per_line=4*((image->columns*24+31)/32);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case 32:
{
/*
Convert bitfield encoded DirectColor scanline.
*/
if ((bmp_info.compression != BI_RGB) &&
(bmp_info.compression != BI_BITFIELDS))
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnrecognizedImageCompression");
}
bytes_per_line=4*(image->columns);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
unsigned int
alpha,
pixel;
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(unsigned int) (*p++);
pixel|=((unsigned int) *p++ << 8);
pixel|=((unsigned int) *p++ << 16);
pixel|=((unsigned int) *p++ << 24);
red=((pixel & bmp_info.red_mask) << shift.red) >> 16;
if (quantum_bits.red == 8)
red|=(red >> 8);
green=((pixel & bmp_info.green_mask) << shift.green) >> 16;
if (quantum_bits.green == 8)
green|=(green >> 8);
blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16;
if (quantum_bits.blue == 8)
blue|=(blue >> 8);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
if (quantum_bits.alpha == 8)
alpha|=(alpha >> 8);
SetPixelAlpha(image,ScaleShortToQuantum(
(unsigned short) alpha),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=(MagickOffsetType) (image->rows-y-1);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
(image->rows-y),image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
default:
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (y > 0)
break;
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if (bmp_info.height < 0)
{
Image
*flipped_image;
/*
Correct image orientation.
*/
flipped_image=FlipImage(image,exception);
if (flipped_image != (Image *) NULL)
{
DuplicateBlob(flipped_image,image);
ReplaceImageInList(&image, flipped_image);
image=flipped_image;
}
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
*magick='\0';
if (bmp_info.ba_offset != 0)
{
offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,2,magick);
if ((count == 2) && (IsBMP(magick,2) != MagickFalse))
{
/*
Acquire 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 (IsBMP(magick,2) != MagickFalse);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,613 |
server | 9e2c26b0f6d91b3b6b0deaf9bc82f6e6ebf9a90b | int _ma_update_state_lsns(MARIA_SHARE *share, LSN lsn, TrID create_trid,
my_bool do_sync, my_bool update_create_rename_lsn)
{
int res;
DBUG_ENTER("_ma_update_state_lsns");
mysql_mutex_lock(&share->intern_lock);
res= _ma_update_state_lsns_sub(share, lsn, create_trid, do_sync,
update_create_rename_lsn);
mysql_mutex_unlock(&share->intern_lock);
DBUG_RETURN(res);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,875 |
Chrome | 783c28d59c4c748ef9b787d4717882c90c5b227b | double ScriptProcessorHandler::LatencyTime() const {
return std::numeric_limits<double>::infinity();
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,410 |
ImageMagick6 | d5df600d43c8706df513a3273d09aee6f54a9233 | static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
CubeInfo *cube_info,const unsigned int direction)
{
#define DitherImageTag "Dither/Image"
DoublePixelPacket
color,
pixel;
MagickBooleanType
proceed;
register CubeInfo
*p;
size_t
index;
p=cube_info;
if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
(p->y >= 0) && (p->y < (ssize_t) image->rows))
{
ExceptionInfo
*exception;
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
i;
/*
Distribute error.
*/
exception=(&image->exception);
q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickFalse);
indexes=GetCacheViewAuthenticIndexQueue(image_view);
AssociateAlphaPixel(cube_info,q,&pixel);
for (i=0; i < ErrorQueueLength; i++)
{
pixel.red+=p->weights[i]*p->error[i].red;
pixel.green+=p->weights[i]*p->error[i].green;
pixel.blue+=p->weights[i]*p->error[i].blue;
if (cube_info->associate_alpha != MagickFalse)
pixel.opacity+=p->weights[i]*p->error[i].opacity;
}
pixel.red=(MagickRealType) ClampPixel(pixel.red);
pixel.green=(MagickRealType) ClampPixel(pixel.green);
pixel.blue=(MagickRealType) ClampPixel(pixel.blue);
if (cube_info->associate_alpha != MagickFalse)
pixel.opacity=(MagickRealType) ClampPixel(pixel.opacity);
i=CacheOffset(cube_info,&pixel);
if (p->cache[i] < 0)
{
register NodeInfo
*node_info;
register size_t
id;
/*
Identify the deepest node containing the pixel's color.
*/
node_info=p->root;
for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
{
id=ColorToNodeId(cube_info,&pixel,index);
if (node_info->child[id] == (NodeInfo *) NULL)
break;
node_info=node_info->child[id];
}
/*
Find closest color among siblings and their children.
*/
p->target=pixel;
p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
QuantumRange+1.0)+1.0);
ClosestColor(image,p,node_info->parent);
p->cache[i]=(ssize_t) p->color_number;
}
/*
Assign pixel to closest colormap entry.
*/
index=(size_t) (1*p->cache[i]);
if (image->storage_class == PseudoClass)
*indexes=(IndexPacket) index;
if (cube_info->quantize_info->measure_error == MagickFalse)
{
SetPixelRgb(q,image->colormap+index);
if (cube_info->associate_alpha != MagickFalse)
SetPixelOpacity(q,image->colormap[index].opacity);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
return(MagickFalse);
/*
Propagate the error as the last entry of the error queue.
*/
(void) memmove(p->error,p->error+1,(ErrorQueueLength-1)*
sizeof(p->error[0]));
AssociateAlphaPixel(cube_info,image->colormap+index,&color);
p->error[ErrorQueueLength-1].red=pixel.red-color.red;
p->error[ErrorQueueLength-1].green=pixel.green-color.green;
p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
if (cube_info->associate_alpha != MagickFalse)
p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
if (proceed == MagickFalse)
return(MagickFalse);
p->offset++;
}
switch (direction)
{
case WestGravity: p->x--; break;
case EastGravity: p->x++; break;
case NorthGravity: p->y--; break;
case SouthGravity: p->y++; break;
}
return(MagickTrue);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,324 |
sfntly | de776d4ef06ca29c240de3444348894f032b03ff | int32_t FontData::BoundOffset(int32_t offset) {
return offset + bound_offset_;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,253 |
Chrome | d304b5ec1b16766ea2cb552a27dc14df848d6a0e | void FFmpegVideoDecodeEngine::Initialize(
MessageLoop* message_loop,
VideoDecodeEngine::EventHandler* event_handler,
VideoDecodeContext* context,
const VideoDecoderConfig& config) {
static const int kDecodeThreads = 2;
static const int kMaxDecodeThreads = 16;
codec_context_ = avcodec_alloc_context();
codec_context_->pix_fmt = PIX_FMT_YUV420P;
codec_context_->codec_type = AVMEDIA_TYPE_VIDEO;
codec_context_->codec_id = VideoCodecToCodecID(config.codec());
codec_context_->coded_width = config.width();
codec_context_->coded_height = config.height();
frame_rate_numerator_ = config.frame_rate_numerator();
frame_rate_denominator_ = config.frame_rate_denominator();
if (config.extra_data() != NULL) {
codec_context_->extradata_size = config.extra_data_size();
codec_context_->extradata = reinterpret_cast<uint8_t*>(
av_malloc(config.extra_data_size() + FF_INPUT_BUFFER_PADDING_SIZE));
memcpy(codec_context_->extradata, config.extra_data(),
config.extra_data_size());
memset(codec_context_->extradata + config.extra_data_size(), '\0',
FF_INPUT_BUFFER_PADDING_SIZE);
}
codec_context_->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK;
codec_context_->error_recognition = FF_ER_CAREFUL;
AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
int decode_threads = (codec_context_->codec_id == CODEC_ID_THEORA) ?
1 : kDecodeThreads;
const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads));
if ((!threads.empty() &&
!base::StringToInt(threads, &decode_threads)) ||
decode_threads < 0 || decode_threads > kMaxDecodeThreads) {
decode_threads = kDecodeThreads;
}
av_frame_.reset(avcodec_alloc_frame());
VideoCodecInfo info;
info.success = false;
info.provides_buffers = true;
info.stream_info.surface_type = VideoFrame::TYPE_SYSTEM_MEMORY;
info.stream_info.surface_format = GetSurfaceFormat();
info.stream_info.surface_width = config.surface_width();
info.stream_info.surface_height = config.surface_height();
bool buffer_allocated = true;
frame_queue_available_.clear();
for (size_t i = 0; i < Limits::kMaxVideoFrames; ++i) {
scoped_refptr<VideoFrame> video_frame;
VideoFrame::CreateFrame(VideoFrame::YV12,
config.width(),
config.height(),
kNoTimestamp,
kNoTimestamp,
&video_frame);
if (!video_frame.get()) {
buffer_allocated = false;
break;
}
frame_queue_available_.push_back(video_frame);
}
if (codec &&
avcodec_thread_init(codec_context_, decode_threads) >= 0 &&
avcodec_open(codec_context_, codec) >= 0 &&
av_frame_.get() &&
buffer_allocated) {
info.success = true;
}
event_handler_ = event_handler;
event_handler_->OnInitializeComplete(info);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,767 |
Chrome | 805eabb91d386c86bd64336c7643f6dfa864151d | size_t CancelableFileOperation(Function operation,
HANDLE file,
BufferType* buffer,
size_t length,
WaitableEvent* io_event,
WaitableEvent* cancel_event,
CancelableSyncSocket* socket,
DWORD timeout_in_ms) {
ThreadRestrictions::AssertIOAllowed();
COMPILE_ASSERT(sizeof(buffer[0]) == sizeof(char), incorrect_buffer_type);
DCHECK_GT(length, 0u);
DCHECK_LE(length, kMaxMessageLength);
DCHECK_NE(file, SyncSocket::kInvalidHandle);
TimeTicks current_time, finish_time;
if (timeout_in_ms != INFINITE) {
current_time = TimeTicks::Now();
finish_time =
current_time + base::TimeDelta::FromMilliseconds(timeout_in_ms);
}
size_t count = 0;
do {
OVERLAPPED ol = { 0 };
ol.hEvent = io_event->handle();
const DWORD chunk = GetNextChunkSize(count, length);
DWORD len = 0;
const BOOL operation_ok = operation(
file, static_cast<BufferType*>(buffer) + count, chunk, &len, &ol);
if (!operation_ok) {
if (::GetLastError() == ERROR_IO_PENDING) {
HANDLE events[] = { io_event->handle(), cancel_event->handle() };
const int wait_result = WaitForMultipleObjects(
ARRAYSIZE_UNSAFE(events), events, FALSE,
timeout_in_ms == INFINITE ?
timeout_in_ms :
static_cast<DWORD>(
(finish_time - current_time).InMilliseconds()));
if (wait_result != WAIT_OBJECT_0 + 0) {
CancelIo(file);
}
if (!GetOverlappedResult(file, &ol, &len, TRUE))
len = 0;
if (wait_result == WAIT_OBJECT_0 + 1) {
DVLOG(1) << "Shutdown was signaled. Closing socket.";
socket->Close();
return count;
}
DCHECK(wait_result == WAIT_OBJECT_0 + 0 || wait_result == WAIT_TIMEOUT);
} else {
break;
}
}
count += len;
if (len != chunk)
break;
if (timeout_in_ms != INFINITE && count < length)
current_time = base::TimeTicks::Now();
} while (count < length &&
(timeout_in_ms == INFINITE || current_time < finish_time));
return count;
}
| 1 | CVE-2013-6630 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 541 |
libarchive | eec077f52bfa2d3f7103b4b74d52572ba8a15aca | next_line(struct archive_read *a,
const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)
{
ssize_t len;
int quit;
quit = 0;
if (*avail == 0) {
*nl = 0;
len = 0;
} else
len = get_line_size(*b, *avail, nl);
/*
* Read bytes more while it does not reach the end of line.
*/
while (*nl == 0 && len == *avail && !quit) {
ssize_t diff = *ravail - *avail;
size_t nbytes_req = (*ravail+1023) & ~1023U;
ssize_t tested;
/* Increase reading bytes if it is not enough to at least
* new two lines. */
if (nbytes_req < (size_t)*ravail + 160)
nbytes_req <<= 1;
*b = __archive_read_ahead(a, nbytes_req, avail);
if (*b == NULL) {
if (*ravail >= *avail)
return (0);
/* Reading bytes reaches the end of file. */
*b = __archive_read_ahead(a, *avail, avail);
quit = 1;
}
*ravail = *avail;
*b += diff;
*avail -= diff;
tested = len;/* Skip some bytes we already determinated. */
len = get_line_size(*b, *avail, nl);
if (len >= 0)
len += tested;
}
return (len);
}
| 1 | CVE-2016-8688 | 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. | 5,437 |
Chrome | d0947db40187f4708c58e64cbd6013faf9eddeed | xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) {
int ret;
if (input == NULL) return(-1);
if (xmlParserDebugEntities) {
if ((ctxt->input != NULL) && (ctxt->input->filename))
xmlGenericError(xmlGenericErrorContext,
"%s(%d): ", ctxt->input->filename,
ctxt->input->line);
xmlGenericError(xmlGenericErrorContext,
"Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur);
}
ret = inputPush(ctxt, input);
GROW;
return(ret);
}
| 1 | CVE-2013-2877 | 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,525 |
ImageMagick | d9a8234d211da30baf9526fbebe9a8438ea7e11c | static MagickBooleanType WriteXBMImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
basename[MagickPathExtent],
buffer[MagickPathExtent];
MagickBooleanType
status;
register const Quantum
*p;
register ssize_t
x;
size_t
bit,
byte;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Write X bitmap header.
*/
GetPathComponent(image->filename,BasePath,basename);
(void) FormatLocaleString(buffer,MagickPathExtent,"#define %s_width %.20g\n",
basename,(double) image->columns);
(void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"#define %s_height %.20g\n",
basename,(double) image->rows);
(void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"static char %s_bits[] = {\n",basename);
(void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
(void) CopyMagickString(buffer," ",MagickPathExtent);
(void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
/*
Convert MIFF to X bitmap pixels.
*/
(void) SetImageType(image,BilevelType,exception);
bit=0;
byte=0;
count=0;
x=0;
y=0;
(void) CopyMagickString(buffer," ",MagickPathExtent);
(void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte>>=1;
if (GetPixelLuma(image,p) < (QuantumRange/2))
byte|=0x80;
bit++;
if (bit == 8)
{
/*
Write a bitmap byte to the image file.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,"0x%02X, ",
(unsigned int) (byte & 0xff));
(void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
count++;
if (count == 12)
{
(void) CopyMagickString(buffer,"\n ",MagickPathExtent);
(void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
count=0;
};
bit=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (bit != 0)
{
/*
Write a bitmap byte to the image file.
*/
byte>>=(8-bit);
(void) FormatLocaleString(buffer,MagickPathExtent,"0x%02X, ",
(unsigned int) (byte & 0xff));
(void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
count++;
if (count == 12)
{
(void) CopyMagickString(buffer,"\n ",MagickPathExtent);
(void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
count=0;
};
bit=0;
byte=0;
};
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) CopyMagickString(buffer,"};\n",MagickPathExtent);
(void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer);
(void) CloseBlob(image);
return(MagickTrue);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,075 |
hylafax | c6cac8d8cd0dbe313689ba77023e12bc5b3027be | FaxModem::recvEndPage(TIFF* tif, const Class2Params& params)
{
/*
* FAXRECVPARAMS is limited to a 32-bit value, and as that is quite
* limited in comparison to all possible fax parameters, FAXDCS is
* intended to be used to discern most fax parameters. The DCS
* signal, however, does not contain bitrate information when V.34-Fax
* is used, so tiffinfo, for example, will use FAXDCS for all fax
* parameters except for bitrate which comes from FAXRECVPARAMS.
*
* As FAXDCS is more recent in libtiff than is FAXRECVPARAMS some
* installations may not be able to use FAXDCS, in which case those
* installations will be limited to the 32-bit restraints.
*/
#ifdef TIFFTAG_FAXRECVPARAMS
TIFFSetField(tif, TIFFTAG_FAXRECVPARAMS, (uint32) params.encode());
#endif
#ifdef TIFFTAG_FAXDCS
FaxParams pageparams = FaxParams(params);
fxStr faxdcs = "";
pageparams.asciiEncode(faxdcs);
TIFFSetField(tif, TIFFTAG_FAXDCS, (const char*) faxdcs);
#endif
#ifdef TIFFTAG_FAXSUBADDRESS
if (sub != "")
TIFFSetField(tif, TIFFTAG_FAXSUBADDRESS, (const char*) sub);
#endif
#ifdef TIFFTAG_FAXRECVTIME
TIFFSetField(tif, TIFFTAG_FAXRECVTIME,
(uint32) server.setPageTransferTime());
#endif
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,153 |
Chrome | c59ad14fc61393a50b2ca3e89c7ecaba7028c4c4 | HeadlessPrintManager::GetPrintParamsFromSettings(
const HeadlessPrintSettings& settings) {
printing::PrintSettings print_settings;
print_settings.set_dpi(printing::kPointsPerInch);
print_settings.set_should_print_backgrounds(
settings.should_print_backgrounds);
print_settings.set_scale_factor(settings.scale);
print_settings.SetOrientation(settings.landscape);
print_settings.set_display_header_footer(settings.display_header_footer);
if (print_settings.display_header_footer()) {
url::Replacements<char> url_sanitizer;
url_sanitizer.ClearUsername();
url_sanitizer.ClearPassword();
std::string url = printing_rfh_->GetLastCommittedURL()
.ReplaceComponents(url_sanitizer)
.spec();
print_settings.set_url(base::UTF8ToUTF16(url));
}
print_settings.set_margin_type(printing::CUSTOM_MARGINS);
print_settings.SetCustomMargins(settings.margins_in_points);
gfx::Rect printable_area_device_units(settings.paper_size_in_points);
print_settings.SetPrinterPrintableArea(settings.paper_size_in_points,
printable_area_device_units, true);
auto print_params = std::make_unique<PrintMsg_PrintPages_Params>();
printing::RenderParamsFromPrintSettings(print_settings,
&print_params->params);
print_params->params.document_cookie = printing::PrintSettings::NewCookie();
return print_params;
}
| 1 | CVE-2018-6074 | 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,363 |
exim | fa32850be0d9e605da1b33305c122f7a59a24650 | handle_smtp_call(int *listen_sockets, int listen_socket_count,
int accept_socket, struct sockaddr *accepted)
{
pid_t pid;
union sockaddr_46 interface_sockaddr;
EXIM_SOCKLEN_T ifsize = sizeof(interface_sockaddr);
int dup_accept_socket = -1;
int max_for_this_host = 0;
int wfsize = 0;
int wfptr = 0;
int use_log_write_selector = log_write_selector;
uschar *whofrom = NULL;
void *reset_point = store_get(0);
/* Make the address available in ASCII representation, and also fish out
the remote port. */
sender_host_address = host_ntoa(-1, accepted, NULL, &sender_host_port);
DEBUG(D_any) debug_printf("Connection request from %s port %d\n",
sender_host_address, sender_host_port);
/* Set up the output stream, check the socket has duplicated, and set up the
input stream. These operations fail only the exceptional circumstances. Note
that never_error() won't use smtp_out if it is NULL. */
smtp_out = fdopen(accept_socket, "wb");
if (smtp_out == NULL)
{
never_error(US"daemon: fdopen() for smtp_out failed", US"", errno);
goto ERROR_RETURN;
}
dup_accept_socket = dup(accept_socket);
if (dup_accept_socket < 0)
{
never_error(US"daemon: couldn't dup socket descriptor",
US"Connection setup failed", errno);
goto ERROR_RETURN;
}
smtp_in = fdopen(dup_accept_socket, "rb");
if (smtp_in == NULL)
{
never_error(US"daemon: fdopen() for smtp_in failed",
US"Connection setup failed", errno);
goto ERROR_RETURN;
}
/* Get the data for the local interface address. Panic for most errors, but
"connection reset by peer" just means the connection went away. */
if (getsockname(accept_socket, (struct sockaddr *)(&interface_sockaddr),
&ifsize) < 0)
{
log_write(0, LOG_MAIN | ((errno == ECONNRESET)? 0 : LOG_PANIC),
"getsockname() failed: %s", strerror(errno));
smtp_printf("421 Local problem: getsockname() failed; please try again later\r\n");
goto ERROR_RETURN;
}
interface_address = host_ntoa(-1, &interface_sockaddr, NULL, &interface_port);
DEBUG(D_interface) debug_printf("interface address=%s port=%d\n",
interface_address, interface_port);
/* Build a string identifying the remote host and, if requested, the port and
the local interface data. This is for logging; at the end of this function the
memory is reclaimed. */
whofrom = string_append(whofrom, &wfsize, &wfptr, 3, "[", sender_host_address, "]");
if ((log_extra_selector & LX_incoming_port) != 0)
whofrom = string_append(whofrom, &wfsize, &wfptr, 2, ":", string_sprintf("%d",
sender_host_port));
if ((log_extra_selector & LX_incoming_interface) != 0)
whofrom = string_append(whofrom, &wfsize, &wfptr, 4, " I=[",
interface_address, "]:", string_sprintf("%d", interface_port));
whofrom[wfptr] = 0; /* Terminate the newly-built string */
/* Check maximum number of connections. We do not check for reserved
connections or unacceptable hosts here. That is done in the subprocess because
it might take some time. */
if (smtp_accept_max > 0 && smtp_accept_count >= smtp_accept_max)
{
DEBUG(D_any) debug_printf("rejecting SMTP connection: count=%d max=%d\n",
smtp_accept_count, smtp_accept_max);
smtp_printf("421 Too many concurrent SMTP connections; "
"please try again later.\r\n");
log_write(L_connection_reject,
LOG_MAIN, "Connection from %s refused: too many connections",
whofrom);
goto ERROR_RETURN;
}
/* If a load limit above which only reserved hosts are acceptable is defined,
get the load average here, and if there are in fact no reserved hosts, do
the test right away (saves a fork). If there are hosts, do the check in the
subprocess because it might take time. */
if (smtp_load_reserve >= 0)
{
load_average = OS_GETLOADAVG();
if (smtp_reserve_hosts == NULL && load_average > smtp_load_reserve)
{
DEBUG(D_any) debug_printf("rejecting SMTP connection: load average = %.2f\n",
(double)load_average/1000.0);
smtp_printf("421 Too much load; please try again later.\r\n");
log_write(L_connection_reject,
LOG_MAIN, "Connection from %s refused: load average = %.2f",
whofrom, (double)load_average/1000.0);
goto ERROR_RETURN;
}
}
/* Check that one specific host (strictly, IP address) is not hogging
resources. This is done here to prevent a denial of service attack by someone
forcing you to fork lots of times before denying service. The value of
smtp_accept_max_per_host is a string which is expanded. This makes it possible
to provide host-specific limits according to $sender_host address, but because
this is in the daemon mainline, only fast expansions (such as inline address
checks) should be used. The documentation is full of warnings. */
if (smtp_accept_max_per_host != NULL)
{
uschar *expanded = expand_string(smtp_accept_max_per_host);
if (expanded == NULL)
{
if (!expand_string_forcedfail)
log_write(0, LOG_MAIN|LOG_PANIC, "expansion of smtp_accept_max_per_host "
"failed for %s: %s", whofrom, expand_string_message);
}
/* For speed, interpret a decimal number inline here */
else
{
uschar *s = expanded;
while (isdigit(*s))
max_for_this_host = max_for_this_host * 10 + *s++ - '0';
if (*s != 0)
log_write(0, LOG_MAIN|LOG_PANIC, "expansion of smtp_accept_max_per_host "
"for %s contains non-digit: %s", whofrom, expanded);
}
}
/* If we have fewer connections than max_for_this_host, we can skip the tedious
per host_address checks. Note that at this stage smtp_accept_count contains the
count of *other* connections, not including this one. */
if ((max_for_this_host > 0) &&
(smtp_accept_count >= max_for_this_host))
{
int i;
int host_accept_count = 0;
int other_host_count = 0; /* keep a count of non matches to optimise */
for (i = 0; i < smtp_accept_max; ++i)
{
if (smtp_slots[i].host_address != NULL)
{
if (Ustrcmp(sender_host_address, smtp_slots[i].host_address) == 0)
host_accept_count++;
else
other_host_count++;
/* Testing all these strings is expensive - see if we can drop out
early, either by hitting the target, or finding there are not enough
connections left to make the target. */
if ((host_accept_count >= max_for_this_host) ||
((smtp_accept_count - other_host_count) < max_for_this_host))
break;
}
}
if (host_accept_count >= max_for_this_host)
{
DEBUG(D_any) debug_printf("rejecting SMTP connection: too many from this "
"IP address: count=%d max=%d\n",
host_accept_count, max_for_this_host);
smtp_printf("421 Too many concurrent SMTP connections "
"from this IP address; please try again later.\r\n");
log_write(L_connection_reject,
LOG_MAIN, "Connection from %s refused: too many connections "
"from that IP address", whofrom);
goto ERROR_RETURN;
}
}
/* OK, the connection count checks have been passed. Before we can fork the
accepting process, we must first log the connection if requested. This logging
used to happen in the subprocess, but doing that means that the value of
smtp_accept_count can be out of step by the time it is logged. So we have to do
the logging here and accept the performance cost. Note that smtp_accept_count
hasn't yet been incremented to take account of this connection.
In order to minimize the cost (because this is going to happen for every
connection), do a preliminary selector test here. This saves ploughing through
the generalized logging code each time when the selector is false. If the
selector is set, check whether the host is on the list for logging. If not,
arrange to unset the selector in the subprocess. */
if ((log_write_selector & L_smtp_connection) != 0)
{
uschar *list = hosts_connection_nolog;
if (list != NULL && verify_check_host(&list) == OK)
use_log_write_selector &= ~L_smtp_connection;
else
log_write(L_smtp_connection, LOG_MAIN, "SMTP connection from %s "
"(TCP/IP connection count = %d)", whofrom, smtp_accept_count + 1);
}
/* Now we can fork the accepting process; do a lookup tidy, just in case any
expansion above did a lookup. */
search_tidyup();
pid = fork();
/* Handle the child process */
if (pid == 0)
{
int i;
int queue_only_reason = 0;
int old_pool = store_pool;
int save_debug_selector = debug_selector;
BOOL local_queue_only;
BOOL session_local_queue_only;
#ifdef SA_NOCLDWAIT
struct sigaction act;
#endif
smtp_accept_count++; /* So that it includes this process */
/* May have been modified for the subprocess */
log_write_selector = use_log_write_selector;
/* Get the local interface address into permanent store */
store_pool = POOL_PERM;
interface_address = string_copy(interface_address);
store_pool = old_pool;
/* Check for a tls-on-connect port */
if (host_is_tls_on_connect_port(interface_port)) tls_on_connect = TRUE;
/* Expand smtp_active_hostname if required. We do not do this any earlier,
because it may depend on the local interface address (indeed, that is most
likely what it depends on.) */
smtp_active_hostname = primary_hostname;
if (raw_active_hostname != NULL)
{
uschar *nah = expand_string(raw_active_hostname);
if (nah == NULL)
{
if (!expand_string_forcedfail)
{
log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand \"%s\" "
"(smtp_active_hostname): %s", raw_active_hostname,
expand_string_message);
smtp_printf("421 Local configuration error; "
"please try again later.\r\n");
mac_smtp_fflush();
search_tidyup();
_exit(EXIT_FAILURE);
}
}
else if (nah[0] != 0) smtp_active_hostname = nah;
}
/* Initialize the queueing flags */
queue_check_only();
session_local_queue_only = queue_only;
/* Close the listening sockets, and set the SIGCHLD handler to SIG_IGN.
We also attempt to set things up so that children are automatically reaped,
but just in case this isn't available, there's a paranoid waitpid() in the
loop too (except for systems where we are sure it isn't needed). See the more
extensive comment before the reception loop in exim.c for a fuller
explanation of this logic. */
for (i = 0; i < listen_socket_count; i++) (void)close(listen_sockets[i]);
#ifdef SA_NOCLDWAIT
act.sa_handler = SIG_IGN;
sigemptyset(&(act.sa_mask));
act.sa_flags = SA_NOCLDWAIT;
sigaction(SIGCHLD, &act, NULL);
#else
signal(SIGCHLD, SIG_IGN);
#endif
/* Attempt to get an id from the sending machine via the RFC 1413
protocol. We do this in the sub-process in order not to hold up the
main process if there is any delay. Then set up the fullhost information
in case there is no HELO/EHLO.
If debugging is enabled only for the daemon, we must turn if off while
finding the id, but turn it on again afterwards so that information about the
incoming connection is output. */
if (debug_daemon) debug_selector = 0;
verify_get_ident(IDENT_PORT);
host_build_sender_fullhost();
debug_selector = save_debug_selector;
DEBUG(D_any)
debug_printf("Process %d is handling incoming connection from %s\n",
(int)getpid(), sender_fullhost);
/* Now disable debugging permanently if it's required only for the daemon
process. */
if (debug_daemon) debug_selector = 0;
/* If there are too many child processes for immediate delivery,
set the session_local_queue_only flag, which is initialized from the
configured value and may therefore already be TRUE. Leave logging
till later so it will have a message id attached. Note that there is no
possibility of re-calculating this per-message, because the value of
smtp_accept_count does not change in this subprocess. */
if (smtp_accept_queue > 0 && smtp_accept_count > smtp_accept_queue)
{
session_local_queue_only = TRUE;
queue_only_reason = 1;
}
/* Handle the start of the SMTP session, then loop, accepting incoming
messages from the SMTP connection. The end will come at the QUIT command,
when smtp_setup_msg() returns 0. A break in the connection causes the
process to die (see accept.c).
NOTE: We do *not* call smtp_log_no_mail() if smtp_start_session() fails,
because a log line has already been written for all its failure exists
(usually "connection refused: <reason>") and writing another one is
unnecessary clutter. */
if (!smtp_start_session())
{
mac_smtp_fflush();
search_tidyup();
_exit(EXIT_SUCCESS);
}
for (;;)
{
int rc;
message_id[0] = 0; /* Clear out any previous message_id */
reset_point = store_get(0); /* Save current store high water point */
DEBUG(D_any)
debug_printf("Process %d is ready for new message\n", (int)getpid());
/* Smtp_setup_msg() returns 0 on QUIT or if the call is from an
unacceptable host or if an ACL "drop" command was triggered, -1 on
connection lost, and +1 on validly reaching DATA. Receive_msg() almost
always returns TRUE when smtp_input is true; just retry if no message was
accepted (can happen for invalid message parameters). However, it can yield
FALSE if the connection was forcibly dropped by the DATA ACL. */
if ((rc = smtp_setup_msg()) > 0)
{
BOOL ok = receive_msg(FALSE);
search_tidyup(); /* Close cached databases */
if (!ok) /* Connection was dropped */
{
mac_smtp_fflush();
smtp_log_no_mail(); /* Log no mail if configured */
_exit(EXIT_SUCCESS);
}
if (message_id[0] == 0) continue; /* No message was accepted */
}
else
{
mac_smtp_fflush();
search_tidyup();
smtp_log_no_mail(); /* Log no mail if configured */
_exit((rc == 0)? EXIT_SUCCESS : EXIT_FAILURE);
}
/* Show the recipients when debugging */
DEBUG(D_receive)
{
int i;
if (sender_address != NULL)
debug_printf("Sender: %s\n", sender_address);
if (recipients_list != NULL)
{
debug_printf("Recipients:\n");
for (i = 0; i < recipients_count; i++)
debug_printf(" %s\n", recipients_list[i].address);
}
}
/* A message has been accepted. Clean up any previous delivery processes
that have completed and are defunct, on systems where they don't go away
by themselves (see comments when setting SIG_IGN above). On such systems
(if any) these delivery processes hang around after termination until
the next message is received. */
#ifndef SIG_IGN_WORKS
while (waitpid(-1, NULL, WNOHANG) > 0);
#endif
/* Reclaim up the store used in accepting this message */
store_reset(reset_point);
/* If queue_only is set or if there are too many incoming connections in
existence, session_local_queue_only will be TRUE. If it is not, check
whether we have received too many messages in this session for immediate
delivery. */
if (!session_local_queue_only &&
smtp_accept_queue_per_connection > 0 &&
receive_messagecount > smtp_accept_queue_per_connection)
{
session_local_queue_only = TRUE;
queue_only_reason = 2;
}
/* Initialize local_queue_only from session_local_queue_only. If it is not
true, and queue_only_load is set, check that the load average is below it.
If local_queue_only is set by this means, we also set if for the session if
queue_only_load_latch is true (the default). This means that, once set,
local_queue_only remains set for any subsequent messages on the same SMTP
connection. This is a deliberate choice; even though the load average may
fall, it doesn't seem right to deliver later messages on the same call when
not delivering earlier ones. However, the are special circumstances such as
very long-lived connections from scanning appliances where this is not the
best strategy. In such cases, queue_only_load_latch should be set false. */
local_queue_only = session_local_queue_only;
if (!local_queue_only && queue_only_load >= 0)
{
local_queue_only = (load_average = OS_GETLOADAVG()) > queue_only_load;
if (local_queue_only)
{
queue_only_reason = 3;
if (queue_only_load_latch) session_local_queue_only = TRUE;
}
}
/* Log the queueing here, when it will get a message id attached, but
not if queue_only is set (case 0). */
if (local_queue_only) switch(queue_only_reason)
{
case 1:
log_write(L_delay_delivery,
LOG_MAIN, "no immediate delivery: too many connections "
"(%d, max %d)", smtp_accept_count, smtp_accept_queue);
break;
case 2:
log_write(L_delay_delivery,
LOG_MAIN, "no immediate delivery: more than %d messages "
"received in one connection", smtp_accept_queue_per_connection);
break;
case 3:
log_write(L_delay_delivery,
LOG_MAIN, "no immediate delivery: load average %.2f",
(double)load_average/1000.0);
break;
}
/* If a delivery attempt is required, spin off a new process to handle it.
If we are not root, we have to re-exec exim unless deliveries are being
done unprivileged. */
else if (!queue_only_policy && !deliver_freeze)
{
pid_t dpid;
/* Before forking, ensure that the C output buffer is flushed. Otherwise
anything that it in it will get duplicated, leading to duplicate copies
of the pending output. */
mac_smtp_fflush();
if ((dpid = fork()) == 0)
{
(void)fclose(smtp_in);
(void)fclose(smtp_out);
/* Don't ever molest the parent's SSL connection, but do clean up
the data structures if necessary. */
#ifdef SUPPORT_TLS
tls_close(FALSE);
#endif
/* Reset SIGHUP and SIGCHLD in the child in both cases. */
signal(SIGHUP, SIG_DFL);
signal(SIGCHLD, SIG_DFL);
if (geteuid() != root_uid && !deliver_drop_privilege)
{
signal(SIGALRM, SIG_DFL);
(void)child_exec_exim(CEE_EXEC_PANIC, FALSE, NULL, FALSE, 2, US"-Mc",
message_id);
/* Control does not return here. */
}
/* No need to re-exec; SIGALRM remains set to the default handler */
(void)deliver_message(message_id, FALSE, FALSE);
search_tidyup();
_exit(EXIT_SUCCESS);
}
if (dpid > 0)
{
DEBUG(D_any) debug_printf("forked delivery process %d\n", (int)dpid);
}
else
{
log_write(0, LOG_MAIN|LOG_PANIC, "daemon: delivery process fork "
"failed: %s", strerror(errno));
}
}
}
}
/* Carrying on in the parent daemon process... Can't do much if the fork
failed. Otherwise, keep count of the number of accepting processes and
remember the pid for ticking off when the child completes. */
if (pid < 0)
{
never_error(US"daemon: accept process fork failed", US"Fork failed", errno);
}
else
{
int i;
for (i = 0; i < smtp_accept_max; ++i)
{
if (smtp_slots[i].pid <= 0)
{
smtp_slots[i].pid = pid;
if (smtp_accept_max_per_host != NULL)
smtp_slots[i].host_address = string_copy_malloc(sender_host_address);
smtp_accept_count++;
break;
}
}
DEBUG(D_any) debug_printf("%d SMTP accept process%s running\n",
smtp_accept_count, (smtp_accept_count == 1)? "" : "es");
}
/* Get here via goto in error cases */
ERROR_RETURN:
/* Close the streams associated with the socket which will also close the
socket fds in this process. We can't do anything if fclose() fails, but
logging brings it to someone's attention. However, "connection reset by peer"
isn't really a problem, so skip that one. On Solaris, a dropped connection can
manifest itself as a broken pipe, so drop that one too. If the streams don't
exist, something went wrong while setting things up. Make sure the socket
descriptors are closed, in order to drop the connection. */
if (smtp_out != NULL)
{
if (fclose(smtp_out) != 0 && errno != ECONNRESET && errno != EPIPE)
log_write(0, LOG_MAIN|LOG_PANIC, "daemon: fclose(smtp_out) failed: %s",
strerror(errno));
smtp_out = NULL;
}
else (void)close(accept_socket);
if (smtp_in != NULL)
{
if (fclose(smtp_in) != 0 && errno != ECONNRESET && errno != EPIPE)
log_write(0, LOG_MAIN|LOG_PANIC, "daemon: fclose(smtp_in) failed: %s",
strerror(errno));
smtp_in = NULL;
}
else (void)close(dup_accept_socket);
/* Release any store used in this process, including the store used for holding
the incoming host address and an expanded active_hostname. */
store_reset(reset_point);
sender_host_address = NULL;
} | 1 | CVE-2010-4345 | 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 | 2,521 |
tinyproxy | 3764b8551463b900b5b4e3ec0cd9bb9182191cb7 | static int read_request_line (struct conn_s *connptr)
{
ssize_t len;
retry:
len = readline (connptr->client_fd, &connptr->request_line);
if (len <= 0) {
log_message (LOG_ERR,
"read_request_line: Client (file descriptor: %d) "
"closed socket before read.", connptr->client_fd);
return -1;
}
/*
* Strip the new line and carriage return from the string.
*/
if (chomp (connptr->request_line, len) == len) {
/*
* If the number of characters removed is the same as the
* length then it was a blank line. Free the buffer and
* try again (since we're looking for a request line.)
*/
safefree (connptr->request_line);
goto retry;
}
log_message (LOG_CONN, "Request (file descriptor %d): %s",
connptr->client_fd, connptr->request_line);
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,481 |
linux | a8b0ca17b80e92faab46ee7179ba9e99ccb61233 | static void perf_event_task_output(struct perf_event *event,
struct perf_task_event *task_event)
{
struct perf_output_handle handle;
struct perf_sample_data sample;
struct task_struct *task = task_event->task;
int ret, size = task_event->event_id.header.size;
perf_event_header__init_id(&task_event->event_id.header, &sample, event);
ret = perf_output_begin(&handle, event,
task_event->event_id.header.size, 0, 0);
if (ret)
goto out;
task_event->event_id.pid = perf_event_pid(event, task);
task_event->event_id.ppid = perf_event_pid(event, current);
task_event->event_id.tid = perf_event_tid(event, task);
task_event->event_id.ptid = perf_event_tid(event, current);
perf_output_put(&handle, task_event->event_id);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
out:
task_event->event_id.header.size = size;
}
| 1 | CVE-2011-2918 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 4,291 |
Android | 295c883fe3105b19bcd0f9e07d54c6b589fc5bff | OMX_ERRORTYPE SoftAVCEncoder::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
int32_t indexFull = index;
switch (indexFull) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (bitRate->nPortIndex != 1 ||
bitRate->eControlRate != OMX_Video_ControlRateVariable) {
return OMX_ErrorUndefined;
}
mBitrate = bitRate->nTargetBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoAvc:
{
OMX_VIDEO_PARAM_AVCTYPE *avcType =
(OMX_VIDEO_PARAM_AVCTYPE *)params;
if (avcType->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (avcType->eProfile != OMX_VIDEO_AVCProfileBaseline ||
avcType->nRefFrames != 1 ||
avcType->nBFrames != 0 ||
avcType->bUseHadamard != OMX_TRUE ||
(avcType->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) != 0 ||
avcType->nRefIdx10ActiveMinus1 != 0 ||
avcType->nRefIdx11ActiveMinus1 != 0 ||
avcType->bWeightedPPrediction != OMX_FALSE ||
avcType->bEntropyCodingCABAC != OMX_FALSE ||
avcType->bconstIpred != OMX_FALSE ||
avcType->bDirect8x8Inference != OMX_FALSE ||
avcType->bDirectSpatialTemporal != OMX_FALSE ||
avcType->nCabacInitIdc != 0) {
return OMX_ErrorUndefined;
}
if (OK != ConvertOmxAvcLevelToAvcSpecLevel(avcType->eLevel, &mAVCEncLevel)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalSetParameter(index, params);
}
}
| 1 | CVE-2016-2476 | 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). | 7,505 |
core | f904cbdfec25582bc5e2a7435bf82ff769f2526a | static void imap_parser_save_arg(struct imap_parser *parser,
const unsigned char *data, size_t size)
{
struct imap_arg *arg;
char *str;
arg = imap_arg_create(parser);
switch (parser->cur_type) {
case ARG_PARSE_ATOM:
case ARG_PARSE_TEXT:
if (size == 3 && i_memcasecmp(data, "NIL", 3) == 0) {
/* NIL argument. it might be an actual NIL, but if
we're reading astring, it's an atom and we can't
lose its case. */
arg->type = IMAP_ARG_NIL;
} else {
/* simply save the string */
arg->type = IMAP_ARG_ATOM;
}
arg->_data.str = imap_parser_strdup(parser, data, size);
arg->str_len = size;
break;
case ARG_PARSE_STRING:
/* data is quoted and may contain escapes. */
i_assert(size > 0);
arg->type = IMAP_ARG_STRING;
str = p_strndup(parser->pool, data+1, size-1);
/* remove the escapes */
if (parser->str_first_escape >= 0 &&
(parser->flags & IMAP_PARSE_FLAG_NO_UNESCAPE) == 0) {
/* -1 because we skipped the '"' prefix */
(void)str_unescape(str + parser->str_first_escape-1);
}
arg->_data.str = str;
arg->str_len = strlen(str);
break;
case ARG_PARSE_LITERAL_DATA:
if ((parser->flags & IMAP_PARSE_FLAG_LITERAL_SIZE) != 0) {
/* save literal size */
arg->type = parser->literal_nonsync ?
IMAP_ARG_LITERAL_SIZE_NONSYNC :
IMAP_ARG_LITERAL_SIZE;
arg->_data.literal_size = parser->literal_size;
arg->literal8 = parser->literal8;
break;
}
/* fall through */
case ARG_PARSE_LITERAL_DATA_FORCED:
if ((parser->flags & IMAP_PARSE_FLAG_LITERAL_TYPE) != 0)
arg->type = IMAP_ARG_LITERAL;
else
arg->type = IMAP_ARG_STRING;
arg->_data.str = imap_parser_strdup(parser, data, size);
arg->literal8 = parser->literal8;
arg->str_len = size;
break;
default:
i_unreached();
}
parser->cur_type = ARG_PARSE_NONE;
} | 1 | CVE-2019-11500 | 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). | 5,264 |
Chrome | 2de493f4a1d48952e09230a0c32ccbd45db973b2 | xsltAttrListTemplateProcess(xsltTransformContextPtr ctxt,
xmlNodePtr target, xmlAttrPtr attrs)
{
xmlAttrPtr attr, copy, last;
xmlNodePtr oldInsert, text;
xmlNsPtr origNs = NULL, copyNs = NULL;
const xmlChar *value;
xmlChar *valueAVT;
if ((ctxt == NULL) || (target == NULL) || (attrs == NULL))
return(NULL);
oldInsert = ctxt->insert;
ctxt->insert = target;
/*
* Instantiate LRE-attributes.
*/
if (target->properties) {
last = target->properties;
while (last->next != NULL)
last = last->next;
} else {
last = NULL;
}
attr = attrs;
do {
/*
* Skip XSLT attributes.
*/
#ifdef XSLT_REFACTORED
if (attr->psvi == xsltXSLTAttrMarker) {
goto next_attribute;
}
#else
if ((attr->ns != NULL) &&
xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))
{
goto next_attribute;
}
#endif
/*
* Get the value.
*/
if (attr->children != NULL) {
if ((attr->children->type != XML_TEXT_NODE) ||
(attr->children->next != NULL))
{
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: The children of an attribute node of a "
"literal result element are not in the expected form.\n");
goto error;
}
value = attr->children->content;
if (value == NULL)
value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
} else
value = xmlDictLookup(ctxt->dict, BAD_CAST "", 0);
/*
* Create a new attribute.
*/
copy = xmlNewDocProp(target->doc, attr->name, NULL);
if (copy == NULL) {
if (attr->ns) {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to create attribute '{%s}%s'.\n",
attr->ns->href, attr->name);
} else {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to create attribute '%s'.\n",
attr->name);
}
goto error;
}
/*
* Attach it to the target element.
*/
copy->parent = target;
if (last == NULL) {
target->properties = copy;
last = copy;
} else {
last->next = copy;
copy->prev = last;
last = copy;
}
/*
* Set the namespace. Avoid lookups of same namespaces.
*/
if (attr->ns != origNs) {
origNs = attr->ns;
if (attr->ns != NULL) {
#ifdef XSLT_REFACTORED
copyNs = xsltGetSpecialNamespace(ctxt, attr->parent,
attr->ns->href, attr->ns->prefix, target);
#else
copyNs = xsltGetNamespace(ctxt, attr->parent,
attr->ns, target);
#endif
if (copyNs == NULL)
goto error;
} else
copyNs = NULL;
}
copy->ns = copyNs;
/*
* Set the value.
*/
text = xmlNewText(NULL);
if (text != NULL) {
copy->last = copy->children = text;
text->parent = (xmlNodePtr) copy;
text->doc = copy->doc;
if (attr->psvi != NULL) {
/*
* Evaluate the Attribute Value Template.
*/
valueAVT = xsltEvalAVT(ctxt, attr->psvi, attr->parent);
if (valueAVT == NULL) {
/*
* TODO: Damn, we need an easy mechanism to report
* qualified names!
*/
if (attr->ns) {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to evaluate the AVT "
"of attribute '{%s}%s'.\n",
attr->ns->href, attr->name);
} else {
xsltTransformError(ctxt, NULL, attr->parent,
"Internal error: Failed to evaluate the AVT "
"of attribute '%s'.\n",
attr->name);
}
text->content = xmlStrdup(BAD_CAST "");
goto error;
} else {
text->content = valueAVT;
}
} else if ((ctxt->internalized) &&
(target->doc != NULL) &&
(target->doc->dict == ctxt->dict))
{
text->content = (xmlChar *) value;
} else {
text->content = xmlStrdup(value);
}
if ((copy != NULL) && (text != NULL) &&
(xmlIsID(copy->doc, copy->parent, copy)))
xmlAddID(NULL, copy->doc, text->content, copy);
}
next_attribute:
attr = attr->next;
} while (attr != NULL);
/*
* Apply attribute-sets.
* The creation of such attributes will not overwrite any existing
* attribute.
*/
attr = attrs;
do {
#ifdef XSLT_REFACTORED
if ((attr->psvi == xsltXSLTAttrMarker) &&
xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets"))
{
xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL);
}
#else
if ((attr->ns != NULL) &&
xmlStrEqual(attr->name, (const xmlChar *)"use-attribute-sets") &&
xmlStrEqual(attr->ns->href, XSLT_NAMESPACE))
{
xsltApplyAttributeSet(ctxt, ctxt->node, (xmlNodePtr) attr, NULL);
}
#endif
attr = attr->next;
} while (attr != NULL);
ctxt->insert = oldInsert;
return(target->properties);
error:
ctxt->insert = oldInsert;
return(NULL);
}
| 1 | CVE-2012-2893 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 4,938 |
linux | 6d1c0f3d28f98ea2736128ed3e46821496dc3a8c | static void xdr_buf_tail_shift_left(const struct xdr_buf *buf,
unsigned int base, unsigned int len,
unsigned int shift)
{
if (!shift || !len)
return;
xdr_buf_tail_copy_left(buf, base, len, shift);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,167 |
cifs-utils | 48a654e2e763fce24c22e1b9c695b42804bbdd4a | static int parse_opt_token(const char *token)
{
if (token == NULL)
return OPT_ERROR;
/*
* token is NULL terminated and contains exactly the
* keyword so we can match exactly
*/
if (strcmp(token, "users") == 0)
return OPT_USERS;
if (strcmp(token, "user_xattr") == 0)
return OPT_USER_XATTR;
if (strcmp(token, "user") == 0 ||
strcmp(token, "username") == 0)
return OPT_USER;
if (strcmp(token, "pass") == 0 ||
strcmp(token, "password") == 0)
return OPT_PASS;
if (strcmp(token, "sec") == 0)
return OPT_SEC;
if (strcmp(token, "ip") == 0 ||
strcmp(token, "addr") == 0)
return OPT_IP;
if (strcmp(token, "unc") == 0 ||
strcmp(token, "target") == 0 ||
strcmp(token, "path") == 0)
return OPT_UNC;
if (strcmp(token, "dom") == 0 ||
strcmp(token, "domain") == 0 ||
strcmp(token, "workgroup") == 0)
return OPT_DOM;
if (strcmp(token, "cred") == 0 || /* undocumented */
strcmp(token, "credentials") == 0)
return OPT_CRED;
if (strcmp(token, "uid") == 0)
return OPT_UID;
if (strcmp(token, "cruid") == 0)
return OPT_CRUID;
if (strcmp(token, "gid") == 0)
return OPT_GID;
if (strcmp(token, "fmask") == 0)
return OPT_FMASK;
if (strcmp(token, "file_mode") == 0)
return OPT_FILE_MODE;
if (strcmp(token, "dmask") == 0)
return OPT_DMASK;
if (strcmp(token, "dir_mode") == 0 ||
strcmp(token, "dirm") == 0)
return OPT_DIR_MODE;
if (strcmp(token, "nosuid") == 0)
return OPT_NO_SUID;
if (strcmp(token, "suid") == 0)
return OPT_SUID;
if (strcmp(token, "nodev") == 0)
return OPT_NO_DEV;
if (strcmp(token, "nobrl") == 0 ||
strcmp(token, "nolock") == 0)
return OPT_NO_LOCK;
if (strcmp(token, "mand") == 0)
return OPT_MAND;
if (strcmp(token, "nomand") == 0)
return OPT_NOMAND;
if (strcmp(token, "dev") == 0)
return OPT_DEV;
if (strcmp(token, "noexec") == 0)
return OPT_NO_EXEC;
if (strcmp(token, "exec") == 0)
return OPT_EXEC;
if (strcmp(token, "guest") == 0)
return OPT_GUEST;
if (strcmp(token, "ro") == 0)
return OPT_RO;
if (strcmp(token, "rw") == 0)
return OPT_RW;
if (strcmp(token, "remount") == 0)
return OPT_REMOUNT;
if (strcmp(token, "_netdev") == 0)
return OPT_IGNORE;
if (strcmp(token, "backupuid") == 0)
return OPT_BKUPUID;
if (strcmp(token, "backupgid") == 0)
return OPT_BKUPGID;
if (strcmp(token, "nofail") == 0)
return OPT_NOFAIL;
if (strncmp(token, "x-", 2) == 0)
return OPT_IGNORE;
if (strncmp(token, "snapshot", 8) == 0)
return OPT_SNAPSHOT;
return OPT_ERROR;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,020 |
openjpeg | b2072402b7e14d22bba6fb8cde2a1e9996e9a919 | static void convert_16u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
OPJ_SIZE_T length)
{
OPJ_SIZE_T i;
for (i = 0; i < length; i++) {
OPJ_INT32 val0 = *pSrc++;
OPJ_INT32 val1 = *pSrc++;
pDst[i] = val0 << 8 | val1;
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,299 |
nagioscore | b1a92a3b52d292ccb601e77a0b29cb1e67ac9d76 | int qh_register_handler(const char *name, const char *description, unsigned int options, qh_handler handler)
{
struct query_handler *qh = NULL;
int result = 0;
if (name == NULL) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "qh: Failed to register handler with no name\n");
return -1;
}
if (handler == NULL) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "qh: Failed to register handler '%s': No handler function specified\n", name);
return -1;
}
if (strlen(name) > 128) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "qh: Failed to register handler '%s': Name too long\n", name);
return -ENAMETOOLONG;
}
/* names must be unique */
if (qh_find_handler(name)) {
logit(NSLOG_RUNTIME_WARNING, TRUE, "qh: Handler '%s' registered more than once\n", name);
return -1;
}
qh = calloc(1, sizeof(*qh));
if (qh == NULL) {
logit(NSLOG_RUNTIME_ERROR, TRUE, "qh: Failed to allocate memory for handler '%s'\n", name);
return -errno;
}
qh->name = name;
qh->description = description;
qh->handler = handler;
qh->options = options;
qh->next_qh = qhandlers;
if (qhandlers) {
qhandlers->prev_qh = qh;
}
qhandlers = qh;
result = dkhash_insert(qh_table, qh->name, NULL, qh);
if (result < 0) {
logit(NSLOG_RUNTIME_ERROR, TRUE,
"qh: Failed to insert query handler '%s' (%p) into hash table %p (%d): %s\n",
name, qh, qh_table, result, strerror(errno));
free(qh);
return result;
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,871 |
openssl | 9cb177301fdab492e4cfef376b28339afe3ef663 | fmtstr(char **sbuffer,
char **buffer,
size_t *currlen,
size_t *maxlen, const char *value, int flags, int min, int max)
{
int padlen, strln;
int cnt = 0;
if (value == 0)
value = "<NULL>";
for (strln = 0; value[strln]; ++strln) ;
padlen = min - strln;
if (padlen < 0)
padlen = 0;
if (flags & DP_F_MINUS)
padlen = -padlen;
while ((padlen > 0) && (cnt < max)) {
doapr_outch(sbuffer, buffer, currlen, maxlen, ' ');
--padlen;
++cnt;
}
while (*value && (cnt < max)) {
doapr_outch(sbuffer, buffer, currlen, maxlen, *value++);
++cnt;
}
while ((padlen < 0) && (cnt < max)) {
doapr_outch(sbuffer, buffer, currlen, maxlen, ' ');
++padlen;
++cnt;
}
} | 1 | CVE-2016-0799 | 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,664 |
linux | e8180dcaa8470ceca21109f143876fdcd9fe050a | int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *run)
{
int ret;
sigset_t sigsaved;
/* Make sure they initialize the vcpu with KVM_ARM_VCPU_INIT */
if (unlikely(vcpu->arch.target < 0))
return -ENOEXEC;
ret = kvm_vcpu_first_run_init(vcpu);
if (ret)
return ret;
if (run->exit_reason == KVM_EXIT_MMIO) {
ret = kvm_handle_mmio_return(vcpu, vcpu->run);
if (ret)
return ret;
}
if (vcpu->sigset_active)
sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
ret = 1;
run->exit_reason = KVM_EXIT_UNKNOWN;
while (ret > 0) {
/*
* Check conditions before entering the guest
*/
cond_resched();
update_vttbr(vcpu->kvm);
if (vcpu->arch.pause)
vcpu_pause(vcpu);
kvm_vgic_flush_hwstate(vcpu);
kvm_timer_flush_hwstate(vcpu);
local_irq_disable();
/*
* Re-check atomic conditions
*/
if (signal_pending(current)) {
ret = -EINTR;
run->exit_reason = KVM_EXIT_INTR;
}
if (ret <= 0 || need_new_vmid_gen(vcpu->kvm)) {
local_irq_enable();
kvm_timer_sync_hwstate(vcpu);
kvm_vgic_sync_hwstate(vcpu);
continue;
}
/**************************************************************
* Enter the guest
*/
trace_kvm_entry(*vcpu_pc(vcpu));
kvm_guest_enter();
vcpu->mode = IN_GUEST_MODE;
ret = kvm_call_hyp(__kvm_vcpu_run, vcpu);
vcpu->mode = OUTSIDE_GUEST_MODE;
vcpu->arch.last_pcpu = smp_processor_id();
kvm_guest_exit();
trace_kvm_exit(*vcpu_pc(vcpu));
/*
* We may have taken a host interrupt in HYP mode (ie
* while executing the guest). This interrupt is still
* pending, as we haven't serviced it yet!
*
* We're now back in SVC mode, with interrupts
* disabled. Enabling the interrupts now will have
* the effect of taking the interrupt again, in SVC
* mode this time.
*/
local_irq_enable();
/*
* Back from guest
*************************************************************/
kvm_timer_sync_hwstate(vcpu);
kvm_vgic_sync_hwstate(vcpu);
ret = handle_exit(vcpu, run, ret);
}
if (vcpu->sigset_active)
sigprocmask(SIG_SETMASK, &sigsaved, NULL);
return ret;
}
| 1 | CVE-2013-5634 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 3,996 |
Android | a4567c66f4764442c6cb7b5c1858810194480fb5 | void SoftHEVC::onReset() {
ALOGV("onReset called");
SoftVideoDecoderOMXComponent::onReset();
mSignalledError = false;
resetDecoder();
resetPlugin();
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,396 |
tensorflow | 0f931751fb20f565c4e94aa6df58d54a003cdb30 | void Compute(OpKernelContext* context) override {
typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>
ConstEigenMatrixMap;
typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>
EigenMatrixMap;
constexpr int tensor_in_and_out_dims = 4;
const Tensor& tensor_in = context->input(0);
OP_REQUIRES(context, tensor_in.dims() == tensor_in_and_out_dims,
errors::InvalidArgument("tensor_in must be 4-dimensional"));
std::vector<int> input_size(tensor_in_and_out_dims);
std::vector<int> output_size(tensor_in_and_out_dims);
for (int i = 0; i < tensor_in_and_out_dims; ++i) {
input_size[i] = tensor_in.dim_size(i);
OP_REQUIRES(
context, pooling_ratio_[i] <= input_size[i],
errors::InvalidArgument(
"Pooling ratio cannot be bigger than input tensor dim size."));
}
// Output size.
for (int i = 0; i < tensor_in_and_out_dims; ++i) {
output_size[i] =
static_cast<int>(std::floor(input_size[i] / pooling_ratio_[i]));
DCHECK_GT(output_size[i], 0);
}
// Generate pooling sequence.
std::vector<int64> row_cum_seq;
std::vector<int64> col_cum_seq;
GuardedPhiloxRandom generator;
generator.Init(seed_, seed2_);
row_cum_seq = GeneratePoolingSequence(input_size[1], output_size[1],
&generator, pseudo_random_);
col_cum_seq = GeneratePoolingSequence(input_size[2], output_size[2],
&generator, pseudo_random_);
// Prepare output.
Tensor* output_tensor = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(
0,
TensorShape({output_size[0], output_size[1],
output_size[2], output_size[3]}),
&output_tensor));
Tensor* output_row_seq_tensor = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(
1, TensorShape({static_cast<int64>(row_cum_seq.size())}),
&output_row_seq_tensor));
Tensor* output_col_seq_tensor = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(
2, TensorShape({static_cast<int64>(col_cum_seq.size())}),
&output_col_seq_tensor));
ConstEigenMatrixMap in_mat(tensor_in.flat<T>().data(), input_size[3],
input_size[2] * input_size[1] * input_size[0]);
EigenMatrixMap out_mat(output_tensor->flat<T>().data(), output_size[3],
output_size[2] * output_size[1] * output_size[0]);
// out_count corresponds to number of elements in each pooling cell.
Eigen::Matrix<T, Eigen::Dynamic, 1> out_count(out_mat.cols());
// Initializes the output tensor and out_count with 0.
out_mat.setZero();
out_count.setZero();
auto output_row_seq_flat = output_row_seq_tensor->flat<int64>();
auto output_col_seq_flat = output_col_seq_tensor->flat<int64>();
// Set output tensors.
for (int i = 0; i < row_cum_seq.size(); ++i) {
output_row_seq_flat(i) = row_cum_seq[i];
}
for (int i = 0; i < col_cum_seq.size(); ++i) {
output_col_seq_flat(i) = col_cum_seq[i];
}
// For both input and output,
// 0: batch
// 1: row / row
// 2: col / col
// 3: depth / channel
const int64_t row_max = input_size[1] - 1;
const int64_t col_max = input_size[2] - 1;
for (int64_t b = 0; b < input_size[0]; ++b) {
// row sequence.
for (int64_t hs = 0; hs < row_cum_seq.size() - 1; ++hs) {
// row start and end.
const int64_t row_start = row_cum_seq[hs];
int64_t row_end =
overlapping_ ? row_cum_seq[hs + 1] : row_cum_seq[hs + 1] - 1;
row_end = std::min(row_end, row_max);
// col sequence.
for (int64_t ws = 0; ws < col_cum_seq.size() - 1; ++ws) {
const int64_t out_offset =
(b * output_size[1] + hs) * output_size[2] + ws;
// col start and end.
const int64_t col_start = col_cum_seq[ws];
int64_t col_end =
overlapping_ ? col_cum_seq[ws + 1] : col_cum_seq[ws + 1] - 1;
col_end = std::min(col_end, col_max);
for (int64_t h = row_start; h <= row_end; ++h) {
for (int64_t w = col_start; w <= col_end; ++w) {
const int64_t in_offset =
(b * input_size[1] + h) * input_size[2] + w;
out_mat.col(out_offset) += in_mat.col(in_offset);
out_count(out_offset)++;
}
}
}
}
}
DCHECK_GT(out_count.minCoeff(), 0);
out_mat.array().rowwise() /= out_count.transpose().array();
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,309 |
Chrome | c1edcafcbe5b8fa20d7e1adb2d1a5322924d8df0 | bool SVGFEColorMatrixElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
supportedAttributes.add(SVGNames::typeAttr);
supportedAttributes.add(SVGNames::valuesAttr);
supportedAttributes.add(SVGNames::inAttr);
}
return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,081 |
openmpt | 7ebf02af2e90f03e0dbd0e18b8b3164f372fb97c | void CSoundFile::SendMIDINote(CHANNELINDEX chn, uint16 note, uint16 volume)
{
#ifndef NO_PLUGINS
auto &channel = m_PlayState.Chn[chn];
const ModInstrument *pIns = channel.pModInstrument;
// instro sends to a midi chan
if (pIns && pIns->HasValidMIDIChannel())
{
PLUGINDEX nPlug = pIns->nMixPlug;
if ((nPlug) && (nPlug <= MAX_MIXPLUGINS))
{
IMixPlugin *pPlug = m_MixPlugins[nPlug-1].pMixPlugin;
if (pPlug != nullptr)
{
pPlug->MidiCommand(GetBestMidiChannel(chn), pIns->nMidiProgram, pIns->wMidiBank, note, volume, chn);
if(note < NOTE_MIN_SPECIAL)
channel.nLeftVU = channel.nRightVU = 0xFF;
}
}
}
#endif // NO_PLUGINS
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,637 |
linux | 8148a73c9901a8794a50f950083c00ccf97d43b3 | static ssize_t environ_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
char *page;
unsigned long src = *ppos;
int ret = 0;
struct mm_struct *mm = file->private_data;
unsigned long env_start, env_end;
if (!mm)
return 0;
page = (char *)__get_free_page(GFP_TEMPORARY);
if (!page)
return -ENOMEM;
ret = 0;
if (!atomic_inc_not_zero(&mm->mm_users))
goto free;
down_read(&mm->mmap_sem);
env_start = mm->env_start;
env_end = mm->env_end;
up_read(&mm->mmap_sem);
while (count > 0) {
size_t this_len, max_len;
int retval;
if (src >= (env_end - env_start))
break;
this_len = env_end - (env_start + src);
max_len = min_t(size_t, PAGE_SIZE, count);
this_len = min(max_len, this_len);
retval = access_remote_vm(mm, (env_start + src),
page, this_len, 0);
if (retval <= 0) {
ret = retval;
break;
}
if (copy_to_user(buf, page, retval)) {
ret = -EFAULT;
break;
}
ret += retval;
src += retval;
buf += retval;
count -= retval;
}
*ppos = src;
mmput(mm);
free:
free_page((unsigned long) page);
return ret;
}
| 1 | CVE-2016-7916 | 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 | 8,412 |
Chrome | f7b020b3d36def118881daa4402c44ca72271482 | bool DateTimeFieldElement::isReadOnly() const
{
return fastHasAttribute(readonlyAttr);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,244 |
ImageMagick | c5402b6e0fcf8b694ae2af6a6652ebb8ce0ccf46 | static MagickBooleanType HorizontalFilter(const ResizeFilter *resize_filter,
const Image *image,Image *resize_image,const double x_factor,
const MagickSizeType span,MagickOffsetType *offset,ExceptionInfo *exception)
{
#define ResizeImageTag "Resize/Image"
CacheView
*image_view,
*resize_view;
ClassType
storage_class;
ContributionInfo
**magick_restrict contributions;
MagickBooleanType
status;
double
scale,
support;
ssize_t
x;
/*
Apply filter to resize horizontally from image to resize image.
*/
scale=MagickMax(1.0/x_factor+MagickEpsilon,1.0);
support=scale*GetResizeFilterSupport(resize_filter);
storage_class=support > 0.5 ? DirectClass : image->storage_class;
if (SetImageStorageClass(resize_image,storage_class,exception) == MagickFalse)
return(MagickFalse);
if (support < 0.5)
{
/*
Support too small even for nearest neighbour: Reduce to point sampling.
*/
support=(double) 0.5;
scale=1.0;
}
contributions=AcquireContributionThreadSet((size_t) (2.0*support+3.0));
if (contributions == (ContributionInfo **) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
status=MagickTrue;
scale=PerceptibleReciprocal(scale);
image_view=AcquireVirtualCacheView(image,exception);
resize_view=AcquireAuthenticCacheView(resize_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,resize_image,resize_image->columns,1)
#endif
for (x=0; x < (ssize_t) resize_image->columns; x++)
{
const int
id = GetOpenMPThreadId();
double
bisect,
density;
register const Quantum
*magick_restrict p;
register ContributionInfo
*magick_restrict contribution;
register Quantum
*magick_restrict q;
register ssize_t
y;
ssize_t
n,
start,
stop;
if (status == MagickFalse)
continue;
bisect=(double) (x+0.5)/x_factor+MagickEpsilon;
start=(ssize_t) MagickMax(bisect-support+0.5,0.0);
stop=(ssize_t) MagickMin(bisect+support+0.5,(double) image->columns);
density=0.0;
contribution=contributions[id];
for (n=0; n < (stop-start); n++)
{
contribution[n].pixel=start+n;
contribution[n].weight=GetResizeFilterWeight(resize_filter,scale*
((double) (start+n)-bisect+0.5));
density+=contribution[n].weight;
}
if (n == 0)
continue;
if ((density != 0.0) && (density != 1.0))
{
register ssize_t
i;
/*
Normalize.
*/
density=PerceptibleReciprocal(density);
for (i=0; i < n; i++)
contribution[i].weight*=density;
}
p=GetCacheViewVirtualPixels(image_view,contribution[0].pixel,0,(size_t)
(contribution[n-1].pixel-contribution[0].pixel+1),image->rows,exception);
q=QueueCacheViewAuthenticPixels(resize_view,x,0,1,resize_image->rows,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (y=0; y < (ssize_t) resize_image->rows; y++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
alpha,
gamma,
pixel;
PixelChannel
channel;
PixelTrait
resize_traits,
traits;
register ssize_t
j;
ssize_t
k;
channel=GetPixelChannelChannel(image,i);
traits=GetPixelChannelTraits(image,channel);
resize_traits=GetPixelChannelTraits(resize_image,channel);
if ((traits == UndefinedPixelTrait) ||
(resize_traits == UndefinedPixelTrait))
continue;
if (((resize_traits & CopyPixelTrait) != 0) ||
(GetPixelWriteMask(resize_image,q) <= (QuantumRange/2)))
{
j=(ssize_t) (MagickMin(MagickMax(bisect,(double) start),(double)
stop-1.0)+0.5);
k=y*(contribution[n-1].pixel-contribution[0].pixel+1)+
(contribution[j-start].pixel-contribution[0].pixel);
SetPixelChannel(resize_image,channel,p[k*GetPixelChannels(image)+i],
q);
continue;
}
pixel=0.0;
if ((resize_traits & BlendPixelTrait) == 0)
{
/*
No alpha blending.
*/
for (j=0; j < n; j++)
{
k=y*(contribution[n-1].pixel-contribution[0].pixel+1)+
(contribution[j].pixel-contribution[0].pixel);
alpha=contribution[j].weight;
pixel+=alpha*p[k*GetPixelChannels(image)+i];
}
SetPixelChannel(resize_image,channel,ClampToQuantum(pixel),q);
continue;
}
/*
Alpha blending.
*/
gamma=0.0;
for (j=0; j < n; j++)
{
k=y*(contribution[n-1].pixel-contribution[0].pixel+1)+
(contribution[j].pixel-contribution[0].pixel);
alpha=contribution[j].weight*QuantumScale*
GetPixelAlpha(image,p+k*GetPixelChannels(image));
pixel+=alpha*p[k*GetPixelChannels(image)+i];
gamma+=alpha;
}
gamma=PerceptibleReciprocal(gamma);
SetPixelChannel(resize_image,channel,ClampToQuantum(gamma*pixel),q);
}
q+=GetPixelChannels(resize_image);
}
if (SyncCacheViewAuthenticPixels(resize_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_HorizontalFilter)
#endif
proceed=SetImageProgress(image,ResizeImageTag,(*offset)++,span);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
resize_view=DestroyCacheView(resize_view);
image_view=DestroyCacheView(image_view);
contributions=DestroyContributionThreadSet(contributions);
return(status);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,981 |
php-src | 760ff841a14160f25348f7969985cb8a2c4da3cc | ZEND_API int ZEND_FASTCALL bitwise_not_function(zval *result, zval *op1) /* {{{ */
{
try_again:
switch (Z_TYPE_P(op1)) {
case IS_LONG:
ZVAL_LONG(result, ~Z_LVAL_P(op1));
return SUCCESS;
case IS_DOUBLE:
ZVAL_LONG(result, ~zend_dval_to_lval(Z_DVAL_P(op1)));
return SUCCESS;
case IS_STRING: {
size_t i;
if (Z_STRLEN_P(op1) == 1) {
zend_uchar not = (zend_uchar) ~*Z_STRVAL_P(op1);
ZVAL_INTERNED_STR(result, ZSTR_CHAR(not));
} else {
ZVAL_NEW_STR(result, zend_string_alloc(Z_STRLEN_P(op1), 0));
for (i = 0; i < Z_STRLEN_P(op1); i++) {
Z_STRVAL_P(result)[i] = ~Z_STRVAL_P(op1)[i];
}
Z_STRVAL_P(result)[i] = 0;
}
return SUCCESS;
}
case IS_REFERENCE:
op1 = Z_REFVAL_P(op1);
goto try_again;
default:
ZEND_TRY_UNARY_OBJECT_OPERATION(ZEND_BW_NOT);
if (result != op1) {
ZVAL_UNDEF(result);
}
zend_throw_error(NULL, "Unsupported operand types");
return FAILURE;
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,117 |
linux | 635682a14427d241bab7bbdeebb48a7d7b91638e | static void sctp_cmd_assoc_failed(sctp_cmd_seq_t *commands,
struct sctp_association *asoc,
sctp_event_t event_type,
sctp_subtype_t subtype,
struct sctp_chunk *chunk,
unsigned int error)
{
struct sctp_ulpevent *event;
struct sctp_chunk *abort;
/* Cancel any partial delivery in progress. */
sctp_ulpq_abort_pd(&asoc->ulpq, GFP_ATOMIC);
if (event_type == SCTP_EVENT_T_CHUNK && subtype.chunk == SCTP_CID_ABORT)
event = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_COMM_LOST,
(__u16)error, 0, 0, chunk,
GFP_ATOMIC);
else
event = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_COMM_LOST,
(__u16)error, 0, 0, NULL,
GFP_ATOMIC);
if (event)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(event));
if (asoc->overall_error_count >= asoc->max_retrans) {
abort = sctp_make_violation_max_retrans(asoc, chunk);
if (abort)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
/* SEND_FAILED sent later when cleaning up the association. */
asoc->outqueue.error = error;
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,014 |
linux | 637b58c2887e5e57850865839cc75f59184b23d1 | pipe_write(struct kiocb *iocb, const struct iovec *_iov,
unsigned long nr_segs, loff_t ppos)
{
struct file *filp = iocb->ki_filp;
struct pipe_inode_info *pipe = filp->private_data;
ssize_t ret;
int do_wakeup;
struct iovec *iov = (struct iovec *)_iov;
size_t total_len;
ssize_t chars;
total_len = iov_length(iov, nr_segs);
/* Null write succeeds. */
if (unlikely(total_len == 0))
return 0;
do_wakeup = 0;
ret = 0;
__pipe_lock(pipe);
if (!pipe->readers) {
send_sig(SIGPIPE, current, 0);
ret = -EPIPE;
goto out;
}
/* We try to merge small writes */
chars = total_len & (PAGE_SIZE-1); /* size of the last buffer */
if (pipe->nrbufs && chars != 0) {
int lastbuf = (pipe->curbuf + pipe->nrbufs - 1) &
(pipe->buffers - 1);
struct pipe_buffer *buf = pipe->bufs + lastbuf;
const struct pipe_buf_operations *ops = buf->ops;
int offset = buf->offset + buf->len;
if (ops->can_merge && offset + chars <= PAGE_SIZE) {
int error, atomic = 1;
void *addr;
error = ops->confirm(pipe, buf);
if (error)
goto out;
iov_fault_in_pages_read(iov, chars);
redo1:
if (atomic)
addr = kmap_atomic(buf->page);
else
addr = kmap(buf->page);
error = pipe_iov_copy_from_user(offset + addr, iov,
chars, atomic);
if (atomic)
kunmap_atomic(addr);
else
kunmap(buf->page);
ret = error;
do_wakeup = 1;
if (error) {
if (atomic) {
atomic = 0;
goto redo1;
}
goto out;
}
buf->len += chars;
total_len -= chars;
ret = chars;
if (!total_len)
goto out;
}
}
for (;;) {
int bufs;
if (!pipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
bufs = pipe->nrbufs;
if (bufs < pipe->buffers) {
int newbuf = (pipe->curbuf + bufs) & (pipe->buffers-1);
struct pipe_buffer *buf = pipe->bufs + newbuf;
struct page *page = pipe->tmp_page;
char *src;
int error, atomic = 1;
if (!page) {
page = alloc_page(GFP_HIGHUSER);
if (unlikely(!page)) {
ret = ret ? : -ENOMEM;
break;
}
pipe->tmp_page = page;
}
/* Always wake up, even if the copy fails. Otherwise
* we lock up (O_NONBLOCK-)readers that sleep due to
* syscall merging.
* FIXME! Is this really true?
*/
do_wakeup = 1;
chars = PAGE_SIZE;
if (chars > total_len)
chars = total_len;
iov_fault_in_pages_read(iov, chars);
redo2:
if (atomic)
src = kmap_atomic(page);
else
src = kmap(page);
error = pipe_iov_copy_from_user(src, iov, chars,
atomic);
if (atomic)
kunmap_atomic(src);
else
kunmap(page);
if (unlikely(error)) {
if (atomic) {
atomic = 0;
goto redo2;
}
if (!ret)
ret = error;
break;
}
ret += chars;
/* Insert it into the buffer array */
buf->page = page;
buf->ops = &anon_pipe_buf_ops;
buf->offset = 0;
buf->len = chars;
buf->flags = 0;
if (is_packetized(filp)) {
buf->ops = &packet_pipe_buf_ops;
buf->flags = PIPE_BUF_FLAG_PACKET;
}
pipe->nrbufs = ++bufs;
pipe->tmp_page = NULL;
total_len -= chars;
if (!total_len)
break;
}
if (bufs < pipe->buffers)
continue;
if (filp->f_flags & O_NONBLOCK) {
if (!ret)
ret = -EAGAIN;
break;
}
if (signal_pending(current)) {
if (!ret)
ret = -ERESTARTSYS;
break;
}
if (do_wakeup) {
wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLRDNORM);
kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
do_wakeup = 0;
}
pipe->waiting_writers++;
pipe_wait(pipe);
pipe->waiting_writers--;
}
out:
__pipe_unlock(pipe);
if (do_wakeup) {
wake_up_interruptible_sync_poll(&pipe->wait, POLLIN | POLLRDNORM);
kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
}
if (ret > 0 && sb_start_write_trylock(file_inode(filp)->i_sb)) {
int err = file_update_time(filp);
if (err)
ret = err;
sb_end_write(file_inode(filp)->i_sb);
}
return ret;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,652 |
w3m | e458def067859615ce4bc7170733d368f49d63c2 | feed_table_block_tag(struct table *tbl,
char *line, struct table_mode *mode, int indent, int cmd)
{
int offset;
if (mode->indent_level <= 0 && indent == -1)
return;
setwidth(tbl, mode);
feed_table_inline_tag(tbl, line, mode, -1);
clearcontentssize(tbl, mode);
if (indent == 1) {
mode->indent_level++;
if (mode->indent_level <= MAX_INDENT_LEVEL)
tbl->indent += INDENT_INCR;
}
else if (indent == -1) {
mode->indent_level--;
if (mode->indent_level < MAX_INDENT_LEVEL)
tbl->indent -= INDENT_INCR;
}
offset = tbl->indent;
if (cmd == HTML_DT) {
if (mode->indent_level > 0 && mode->indent_level <= MAX_INDENT_LEVEL)
offset -= INDENT_INCR;
}
if (tbl->indent > 0) {
check_minimum0(tbl, 0);
addcontentssize(tbl, offset);
}
} | 1 | CVE-2016-9626 | 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,662 |
libgcrypt | 35cd81f134c0da4e7e6fcfe40d270ee1251f52c2 | generate ( ELG_secret_key *sk, unsigned int nbits, gcry_mpi_t **ret_factors )
{
gcry_mpi_t p; /* the prime */
gcry_mpi_t p_min1;
gcry_mpi_t g;
gcry_mpi_t x; /* the secret exponent */
gcry_mpi_t y;
unsigned int qbits;
unsigned int xbits;
byte *rndbuf;
p_min1 = gcry_mpi_new ( nbits );
qbits = wiener_map( nbits );
if( qbits & 1 ) /* better have a even one */
qbits++;
g = mpi_alloc(1);
p = _gcry_generate_elg_prime( 0, nbits, qbits, g, ret_factors );
mpi_sub_ui(p_min1, p, 1);
/* Select a random number which has these properties:
* 0 < x < p-1
* This must be a very good random number because this is the
* secret part. The prime is public and may be shared anyway,
* so a random generator level of 1 is used for the prime.
*
* I don't see a reason to have a x of about the same size
* as the p. It should be sufficient to have one about the size
* of q or the later used k plus a large safety margin. Decryption
* will be much faster with such an x.
*/
xbits = qbits * 3 / 2;
if( xbits >= nbits )
BUG();
x = gcry_mpi_snew ( xbits );
if( DBG_CIPHER )
log_debug("choosing a random x of size %u", xbits );
rndbuf = NULL;
do
{
if( DBG_CIPHER )
progress('.');
if( rndbuf )
{ /* Change only some of the higher bits */
if( xbits < 16 ) /* should never happen ... */
{
gcry_free(rndbuf);
rndbuf = gcry_random_bytes_secure( (xbits+7)/8,
GCRY_VERY_STRONG_RANDOM );
}
else
{
char *r = gcry_random_bytes_secure( 2,
GCRY_VERY_STRONG_RANDOM );
memcpy(rndbuf, r, 2 );
gcry_free(r);
}
}
else
{
rndbuf = gcry_random_bytes_secure( (xbits+7)/8,
GCRY_VERY_STRONG_RANDOM );
}
_gcry_mpi_set_buffer( x, rndbuf, (xbits+7)/8, 0 );
mpi_clear_highbit( x, xbits+1 );
}
while( !( mpi_cmp_ui( x, 0 )>0 && mpi_cmp( x, p_min1 )<0 ) );
gcry_free(rndbuf);
y = gcry_mpi_new (nbits);
gcry_mpi_powm( y, g, x, p );
if( DBG_CIPHER )
{
progress('\n');
log_mpidump("elg p= ", p );
log_mpidump("elg g= ", g );
log_mpidump("elg y= ", y );
log_mpidump("elg x= ", x );
}
/* Copy the stuff to the key structures */
sk->p = p;
sk->g = g;
sk->y = y;
sk->x = x;
gcry_mpi_release ( p_min1 );
/* Now we can test our keys (this should never fail!) */
test_keys ( sk, nbits - 64, 0 );
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,768 |
quassel | a4ca568cdf68cf4a0343eb161518dc8e50cea87d | QByteArray CtcpHandler::xdelimQuote(const QByteArray &message) {
QByteArray quotedMessage = message;
QHash<QByteArray, QByteArray>::const_iterator quoteIter = ctcpXDelimDequoteHash.constBegin();
while(quoteIter != ctcpXDelimDequoteHash.constEnd()) {
quotedMessage.replace(quoteIter.value(), quoteIter.key());
quoteIter++;
}
return quotedMessage;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,960 |
linux | 05a974efa4bdf6e2a150e3f27dc6fcf0a9ad5655 | static int atusb_get_and_clear_error(struct atusb *atusb)
{
int err = atusb->err;
atusb->err = 0;
return err;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,128 |
oniguruma | cbe9f8bd9cfc6c3c87a60fbae58fa1a85db59df0 | concat_opt_exact_str(OptStr* to, UChar* s, UChar* end, OnigEncoding enc)
{
int i, j, len;
UChar *p;
for (i = to->len, p = s; p < end && i < OPT_EXACT_MAXLEN; ) {
len = enclen(enc, p);
if (i + len > OPT_EXACT_MAXLEN) break;
for (j = 0; j < len && p < end; j++)
to->s[i++] = *p++;
}
to->len = i;
if (p >= end)
to->reach_end = 1;
} | 1 | CVE-2020-26159 | 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). | 5,940 |
Chrome | 3c8e4852477d5b1e2da877808c998dc57db9460f | void SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(std::make_unique<protocol::InspectorHandler>());
session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId()));
session->AddHandler(std::make_unique<protocol::SchemaHandler>());
session->SetRenderer(GetProcess(), nullptr);
if (state_ == WORKER_READY)
session->AttachToAgent(EnsureAgent());
}
| 1 | CVE-2018-6111 | 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. | 7,324 |
libass | 017137471d0043e0321e377ed8da48e45a3ec632 | static int resize_read_order_bitmap(ASS_Track *track, int max_id)
{
// Don't allow malicious files to OOM us easily. Also avoids int overflows.
if (max_id < 0 || max_id >= 10 * 1024 * 1024 * 8)
goto fail;
assert(track->parser_priv->read_order_bitmap || !track->parser_priv->read_order_elems);
if (max_id >= track->parser_priv->read_order_elems * 32) {
int oldelems = track->parser_priv->read_order_elems;
int elems = ((max_id + 31) / 32 + 1) * 2;
assert(elems >= oldelems);
track->parser_priv->read_order_elems = elems;
void *new_bitmap =
realloc(track->parser_priv->read_order_bitmap, elems * 4);
if (!new_bitmap)
goto fail;
track->parser_priv->read_order_bitmap = new_bitmap;
memset(track->parser_priv->read_order_bitmap + oldelems, 0,
(elems - oldelems) * 4);
}
return 0;
fail:
free(track->parser_priv->read_order_bitmap);
track->parser_priv->read_order_bitmap = NULL;
track->parser_priv->read_order_elems = 0;
return -1;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,387 |
Espruino | ce1924193862d58cb43d3d4d9dada710a8361b89 | size_t jsvGetString(const JsVar *v, char *str, size_t len) {
assert(len>0);
const char *s = jsvGetConstString(v);
if (s) {
/* don't use strncpy here because we don't
* want to pad the entire buffer with zeros */
len--;
int l = 0;
while (*s && l<len) {
str[l] = s[l];
l++;
}
str[l] = 0;
return l;
} else if (jsvIsInt(v)) {
itostr(v->varData.integer, str, 10);
return strlen(str);
} else if (jsvIsFloat(v)) {
ftoa_bounded(v->varData.floating, str, len);
return strlen(str);
} else if (jsvHasCharacterData(v)) {
assert(!jsvIsStringExt(v));
size_t l = len;
JsvStringIterator it;
jsvStringIteratorNewConst(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
if (l--<=1) {
*str = 0;
jsvStringIteratorFree(&it);
return len;
}
*(str++) = jsvStringIteratorGetChar(&it);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
*str = 0;
return len-l;
} else {
JsVar *stringVar = jsvAsString((JsVar*)v, false); // we know we're casting to non-const here
if (stringVar) {
size_t l = jsvGetString(stringVar, str, len); // call again - but this time with converted var
jsvUnLock(stringVar);
return l;
} else {
str[0] = 0;
jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string");
return 0;
}
}
}
| 1 | CVE-2018-11596 | 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). | 7,064 |
linux | a4780adeefd042482f624f5e0d577bf9cdcbb760 | static int get_tp_trap(struct pt_regs *regs, unsigned int instr)
{
int reg = (instr >> 12) & 15;
if (reg == 15)
return 1;
regs->uregs[reg] = current_thread_info()->tp_value;
regs->ARM_pc += 4;
return 0;
}
| 1 | CVE-2014-9870 | 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 | 982 |
thor | 18de8f9f0762c3a542b1122589edb8af859d9813 | static void decode_and_reconstruct_block_intra_uv (SAMPLE *rec_u, SAMPLE *rec_v, int stride, int size, int qp, SAMPLE *pblock_u, SAMPLE *pblock_v, int16_t *coeffq_u, int16_t *coeffq_v,
int tb_split, int upright_available,int downleft_available, intra_mode_t intra_mode,int ypos,int xpos,int width,int comp, int bitdepth,
qmtx_t ** iwmatrix, SAMPLE *pblock_y, SAMPLE *rec_y, int rec_stride, int sub){
int16_t *rcoeff = thor_alloc(2*MAX_TR_SIZE*MAX_TR_SIZE, 32);
int16_t *rblock = thor_alloc(2*MAX_TR_SIZE*MAX_TR_SIZE, 32);
int16_t *rblock2 = thor_alloc(2*MAX_TR_SIZE*MAX_TR_SIZE, 32);
SAMPLE* left_data = (SAMPLE*)thor_alloc((2*MAX_TR_SIZE+2)*sizeof(SAMPLE),32)+1;
SAMPLE* top_data = (SAMPLE*)thor_alloc((2*MAX_TR_SIZE+2)*sizeof(SAMPLE),32)+1;
SAMPLE top_left;
if (tb_split){
int size2 = size/2;
int i,j,index;
for (i=0;i<size;i+=size2){
for (j=0;j<size;j+=size2){
TEMPLATE(make_top_and_left)(left_data,top_data,&top_left,rec_u,stride,&rec_u[i*stride+j],stride,i,j,ypos,xpos,size2,upright_available,downleft_available,1,bitdepth);
TEMPLATE(get_intra_prediction)(left_data,top_data,top_left,ypos+i,xpos+j,size2,&pblock_u[i*size+j],size,intra_mode,bitdepth);
TEMPLATE(make_top_and_left)(left_data,top_data,&top_left,rec_v,stride,&rec_v[i*stride+j],stride,i,j,ypos,xpos,size2,upright_available,downleft_available,1,bitdepth);
TEMPLATE(get_intra_prediction)(left_data,top_data,top_left,ypos+i,xpos+j,size2,&pblock_v[i*size+j],size,intra_mode,bitdepth);
if (pblock_y)
TEMPLATE(improve_uv_prediction)(&pblock_y[i*size+j], &pblock_u[i*size+j], &pblock_v[i*size+j], &rec_y[(i<<sub)*rec_stride+(j<<sub)], size2 << sub, size << sub, rec_stride, sub, bitdepth);
index = 2*(i/size2) + (j/size2);
TEMPLATE(dequantize)(coeffq_u+index*size2*size2, rcoeff, qp, size2, iwmatrix ? iwmatrix[log2i(size2/4)] : NULL);
inverse_transform (rcoeff, rblock2, size2, bitdepth);
TEMPLATE(reconstruct_block)(rblock2,&pblock_u[i*size+j],&rec_u[i*stride+j],size2,size,stride,bitdepth);
TEMPLATE(dequantize)(coeffq_v+index*size2*size2, rcoeff, qp, size2, iwmatrix ? iwmatrix[log2i(size2/4)] : NULL);
inverse_transform (rcoeff, rblock2, size2, bitdepth);
TEMPLATE(reconstruct_block)(rblock2,&pblock_v[i*size+j],&rec_v[i*stride+j],size2,size,stride,bitdepth);
}
}
}
else{
TEMPLATE(make_top_and_left)(left_data,top_data,&top_left,rec_u,stride,NULL,0,0,0,ypos,xpos,size,upright_available,downleft_available,0,bitdepth);
TEMPLATE(get_intra_prediction)(left_data,top_data,top_left,ypos,xpos,size,pblock_u,size,intra_mode,bitdepth);
TEMPLATE(make_top_and_left)(left_data,top_data,&top_left,rec_v,stride,NULL,0,0,0,ypos,xpos,size,upright_available,downleft_available,0,bitdepth);
TEMPLATE(get_intra_prediction)(left_data,top_data,top_left,ypos,xpos,size,pblock_v,size,intra_mode,bitdepth);
if (pblock_y)
TEMPLATE(improve_uv_prediction)(pblock_y, pblock_u, pblock_v, rec_y, size << sub, size << sub, rec_stride, sub, bitdepth);
TEMPLATE(dequantize)(coeffq_u, rcoeff, qp, size, iwmatrix ? iwmatrix[log2i(size/4)] : NULL);
inverse_transform (rcoeff, rblock, size, bitdepth);
TEMPLATE(reconstruct_block)(rblock,pblock_u,rec_u,size,size,stride,bitdepth);
TEMPLATE(dequantize)(coeffq_v, rcoeff, qp, size, iwmatrix ? iwmatrix[log2i(size/4)] : NULL);
inverse_transform (rcoeff, rblock, size, bitdepth);
TEMPLATE(reconstruct_block)(rblock,pblock_v,rec_v,size,size,stride,bitdepth);
}
thor_free(top_data - 1);
thor_free(left_data - 1);
thor_free(rcoeff);
thor_free(rblock);
thor_free(rblock2);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,310 |
linux | 8e2d61e0aed2b7c4ecb35844fe07e0b2b762dee4 | static __exit void sctp_exit(void)
{
/* BUG. This should probably do something useful like clean
* up all the remaining associations and all that memory.
*/
/* Unregister with inet6/inet layers. */
sctp_v6_del_protocol();
sctp_v4_del_protocol();
unregister_pernet_subsys(&sctp_net_ops);
/* Free protosw registrations */
sctp_v6_protosw_exit();
sctp_v4_protosw_exit();
/* Unregister with socket layer. */
sctp_v6_pf_exit();
sctp_v4_pf_exit();
sctp_sysctl_unregister();
free_pages((unsigned long)sctp_assoc_hashtable,
get_order(sctp_assoc_hashsize *
sizeof(struct sctp_hashbucket)));
kfree(sctp_ep_hashtable);
free_pages((unsigned long)sctp_port_hashtable,
get_order(sctp_port_hashsize *
sizeof(struct sctp_bind_hashbucket)));
percpu_counter_destroy(&sctp_sockets_allocated);
rcu_barrier(); /* Wait for completion of call_rcu()'s */
kmem_cache_destroy(sctp_chunk_cachep);
kmem_cache_destroy(sctp_bucket_cachep);
}
| 1 | CVE-2015-5283 | 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,097 |
Chrome | d616695bd68610e75b90d734d72d42534bf01b82 | bool LookupMatchInTopDomains(const icu::UnicodeString& ustr_skeleton) {
std::string skeleton;
ustr_skeleton.toUTF8String(skeleton);
DCHECK_NE(skeleton.back(), '.');
auto labels = base::SplitStringPiece(skeleton, ".", base::KEEP_WHITESPACE,
base::SPLIT_WANT_ALL);
if (labels.size() > kNumberOfLabelsToCheck) {
labels.erase(labels.begin(),
labels.begin() + labels.size() - kNumberOfLabelsToCheck);
}
while (labels.size() > 1) {
std::string partial_skeleton = base::JoinString(labels, ".");
if (net::LookupStringInFixedSet(
g_graph, g_graph_length, partial_skeleton.data(),
partial_skeleton.length()) != net::kDafsaNotFound)
return true;
labels.erase(labels.begin());
}
return false;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,546 |
linux-2.6 | 8a47077a0b5aa2649751c46e7a27884e6686ccbf | static __inline__ int cbq_dump_ovl(struct sk_buff *skb, struct cbq_class *cl)
{
unsigned char *b = skb->tail;
struct tc_cbq_ovl opt;
opt.strategy = cl->ovl_strategy;
opt.priority2 = cl->priority2+1;
opt.penalty = (cl->penalty*1000)/HZ;
RTA_PUT(skb, TCA_CBQ_OVL_STRATEGY, sizeof(opt), &opt);
return skb->len;
rtattr_failure:
skb_trim(skb, b - skb->data);
return -1;
} | 1 | CVE-2005-4881 | 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. | 4,536 |
Chrome | e741149a6b7872a2bf1f2b6cc0a56e836592fb77 | xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){
xmlNodePtr cur = NULL;
long val;
xmlChar str[30];
xmlDocPtr doc;
if (nargs == 0) {
cur = ctxt->context->node;
} else if (nargs == 1) {
xmlXPathObjectPtr obj;
xmlNodeSetPtr nodelist;
int i, ret;
if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) {
ctxt->error = XPATH_INVALID_TYPE;
xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,
"generate-id() : invalid arg expecting a node-set\n");
return;
}
obj = valuePop(ctxt);
nodelist = obj->nodesetval;
if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) {
xmlXPathFreeObject(obj);
valuePush(ctxt, xmlXPathNewCString(""));
return;
}
cur = nodelist->nodeTab[0];
for (i = 1;i < nodelist->nodeNr;i++) {
ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]);
if (ret == -1)
cur = nodelist->nodeTab[i];
}
xmlXPathFreeObject(obj);
} else {
xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,
"generate-id() : invalid number of args %d\n", nargs);
ctxt->error = XPATH_INVALID_ARITY;
return;
}
/*
* Okay this is ugly but should work, use the NodePtr address
* to forge the ID
*/
if (cur->type != XML_NAMESPACE_DECL)
doc = cur->doc;
else {
xmlNsPtr ns = (xmlNsPtr) cur;
if (ns->context != NULL)
doc = ns->context;
else
doc = ctxt->context->doc;
}
val = (long)((char *)cur - (char *)doc);
if (val >= 0) {
sprintf((char *)str, "idp%ld", val);
} else {
sprintf((char *)str, "idm%ld", -val);
}
valuePush(ctxt, xmlXPathNewString(str));
}
| 1 | CVE-2012-2870 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 794 |
Chrome | ba1513223e47b62ed53b61518b7f7b82ad1d8ccd | void ServerWrapper::OnHttpRequest(int connection_id,
const net::HttpServerRequestInfo& info) {
server_->SetSendBufferSize(connection_id, kSendBufferSizeForDevTools);
if (base::StartsWith(info.path, "/json", base::CompareCase::SENSITIVE)) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::BindOnce(&DevToolsHttpHandler::OnJsonRequest,
handler_, connection_id, info));
return;
}
if (info.path.empty() || info.path == "/") {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&DevToolsHttpHandler::OnDiscoveryPageRequest, handler_,
connection_id));
return;
}
if (!base::StartsWith(info.path, "/devtools/",
base::CompareCase::SENSITIVE)) {
server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation);
return;
}
std::string filename = PathWithoutParams(info.path.substr(10));
std::string mime_type = GetMimeType(filename);
if (!debug_frontend_dir_.empty()) {
base::FilePath path = debug_frontend_dir_.AppendASCII(filename);
std::string data;
base::ReadFileToString(path, &data);
server_->Send200(connection_id, data, mime_type,
kDevtoolsHttpHandlerTrafficAnnotation);
return;
}
if (bundles_resources_) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&DevToolsHttpHandler::OnFrontendResourceRequest,
handler_, connection_id, filename));
return;
}
server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation);
}
| 1 | CVE-2018-6101 | 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. | 5,792 |
enlightment | 666df815cd86a50343859bce36c5cf968c5f38b0 | main(int argc,
char **argv)
{
int i, gn;
int test = 0;
char *action = NULL, *cmd;
char *output = NULL;
#ifdef HAVE_EEZE_MOUNT
Eina_Bool mnt = EINA_FALSE;
const char *act;
#endif
gid_t gid, gl[65536], egid;
for (i = 1; i < argc; i++)
{
if ((!strcmp(argv[i], "-h")) ||
(!strcmp(argv[i], "-help")) ||
(!strcmp(argv[i], "--help")))
{
printf(
"This is an internal tool for Enlightenment.\n"
"do not use it.\n"
);
exit(0);
}
}
if (argc >= 3)
{
if ((argc == 3) && (!strcmp(argv[1], "-t")))
{
test = 1;
action = argv[2];
}
else if (!strcmp(argv[1], "l2ping"))
{
action = argv[1];
output = argv[2];
}
#ifdef HAVE_EEZE_MOUNT
else
{
const char *s;
s = strrchr(argv[1], '/');
if ((!s) || (!s[1])) exit(1); /* eeze always uses complete path */
s++;
if (strcmp(s, "mount") && strcmp(s, "umount") && strcmp(s, "eject")) exit(1);
mnt = EINA_TRUE;
act = s;
action = argv[1];
}
#endif
}
else if (argc == 2)
{
action = argv[1];
}
else
{
exit(1);
}
if (!action) exit(1);
fprintf(stderr, "action %s %i\n", action, argc);
uid = getuid();
gid = getgid();
egid = getegid();
gn = getgroups(65536, gl);
if (gn < 0)
{
printf("ERROR: MEMBER OF MORE THAN 65536 GROUPS\n");
exit(3);
}
if (setuid(0) != 0)
{
printf("ERROR: UNABLE TO ASSUME ROOT PRIVILEGES\n");
exit(5);
}
if (setgid(0) != 0)
{
printf("ERROR: UNABLE TO ASSUME ROOT GROUP PRIVILEGES\n");
exit(7);
}
eina_init();
if (!auth_action_ok(action, gid, gl, gn, egid))
{
printf("ERROR: ACTION NOT ALLOWED: %s\n", action);
exit(10);
}
/* we can add more levels of auth here */
/* when mounting, this will match the exact path to the exe,
* as required in sysactions.conf
* this is intentionally pedantic for security
*/
cmd = eina_hash_find(actions, action);
if (!cmd)
{
printf("ERROR: UNDEFINED ACTION: %s\n", action);
exit(20);
}
if (!test && !strcmp(action, "l2ping"))
{
char tmp[128];
double latency;
latency = e_sys_l2ping(output);
eina_convert_dtoa(latency, tmp);
fputs(tmp, stdout);
return (latency < 0) ? 1 : 0;
}
/* sanitize environment */
#ifdef HAVE_UNSETENV
# define NOENV(x) unsetenv(x)
#else
# define NOENV(x)
#endif
NOENV("IFS");
/* sanitize environment */
#ifdef HAVE_UNSETENV
# define NOENV(x) unsetenv(x)
/* pass 1 - just nuke known dangerous env vars brutally if possible via
* unsetenv(). if you don't have unsetenv... there's pass 2 and 3 */
NOENV("IFS");
NOENV("CDPATH");
NOENV("LOCALDOMAIN");
NOENV("RES_OPTIONS");
NOENV("HOSTALIASES");
NOENV("NLSPATH");
NOENV("PATH_LOCALE");
NOENV("COLORTERM");
NOENV("LANG");
NOENV("LANGUAGE");
NOENV("LINGUAS");
NOENV("TERM");
NOENV("LD_PRELOAD");
NOENV("LD_LIBRARY_PATH");
NOENV("SHLIB_PATH");
NOENV("LIBPATH");
NOENV("AUTHSTATE");
NOENV("DYLD_*");
NOENV("KRB_CONF*");
NOENV("KRBCONFDIR");
NOENV("KRBTKFILE");
NOENV("KRB5_CONFIG*");
NOENV("KRB5_KTNAME");
NOENV("VAR_ACE");
NOENV("USR_ACE");
NOENV("DLC_ACE");
NOENV("TERMINFO");
NOENV("TERMINFO_DIRS");
NOENV("TERMPATH");
NOENV("TERMCAP");
NOENV("ENV");
NOENV("BASH_ENV");
NOENV("PS4");
NOENV("GLOBIGNORE");
NOENV("SHELLOPTS");
NOENV("JAVA_TOOL_OPTIONS");
NOENV("PERLIO_DEBUG");
NOENV("PERLLIB");
NOENV("PERL5LIB");
NOENV("PERL5OPT");
NOENV("PERL5DB");
NOENV("FPATH");
NOENV("NULLCMD");
NOENV("READNULLCMD");
NOENV("ZDOTDIR");
NOENV("TMPPREFIX");
NOENV("PYTHONPATH");
NOENV("PYTHONHOME");
NOENV("PYTHONINSPECT");
NOENV("RUBYLIB");
NOENV("RUBYOPT");
# ifdef HAVE_ENVIRON
if (environ)
{
int again;
char *tmp, *p;
/* go over environment array again and again... safely */
do
{
again = 0;
/* walk through and find first entry that we don't like */
for (i = 0; environ[i]; i++)
{
/* if it begins with any of these, it's possibly nasty */
if ((!strncmp(environ[i], "LD_", 3)) ||
(!strncmp(environ[i], "_RLD_", 5)) ||
(!strncmp(environ[i], "LC_", 3)) ||
(!strncmp(environ[i], "LDR_", 3)))
{
/* unset it */
tmp = strdup(environ[i]);
if (!tmp) abort();
p = strchr(tmp, '=');
if (!p) abort();
*p = 0;
NOENV(p);
free(tmp);
/* and mark our do to try again from the start in case
* unsetenv changes environ ptr */
again = 1;
break;
}
}
}
while (again);
}
# endif
#endif
/* pass 2 - clear entire environment so it doesn't exist at all. if you
* can't do this... you're possibly in trouble... but the worst is still
* fixed in pass 3 */
#ifdef HAVE_CLEARENV
clearenv();
#else
# ifdef HAVE_ENVIRON
environ = NULL;
# endif
#endif
/* pass 3 - set path and ifs to minimal defaults */
putenv("PATH=/bin:/usr/bin");
putenv("IFS= \t\n");
const char *p;
char *end;
unsigned long muid;
Eina_Bool nosuid, nodev, noexec, nuid;
nosuid = nodev = noexec = nuid = EINA_FALSE;
/* these are the only possible options which can be present here; check them strictly */
if (eina_strlcpy(buf, opts, sizeof(buf)) >= sizeof(buf)) return EINA_FALSE;
for (p = buf; p && p[1]; p = strchr(p + 1, ','))
{
if (p[0] == ',') p++;
#define CMP(OPT) \
if (!strncmp(p, OPT, sizeof(OPT) - 1))
CMP("nosuid,")
{
nosuid = EINA_TRUE;
continue;
}
CMP("nodev,")
{
nodev = EINA_TRUE;
continue;
}
CMP("noexec,")
{
noexec = EINA_TRUE;
continue;
}
CMP("utf8,") continue;
CMP("utf8=0,") continue;
CMP("utf8=1,") continue;
CMP("iocharset=utf8,") continue;
CMP("uid=")
{
p += 4;
errno = 0;
muid = strtoul(p, &end, 10);
if (muid == ULONG_MAX) return EINA_FALSE;
if (errno) return EINA_FALSE;
if (end[0] != ',') return EINA_FALSE;
if (muid != uid) return EINA_FALSE;
nuid = EINA_TRUE;
continue;
}
return EINA_FALSE;
}
if ((!nosuid) || (!nodev) || (!noexec) || (!nuid)) return EINA_FALSE;
return EINA_TRUE;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,861 |
Subsets and Splits