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
|
---|---|---|---|---|---|---|---|---|---|
hhvm | 7135ec229882370a00411aa50030eada6034cc1b | explicit HashContext(const HashContext* ctx) {
assert(ctx->ops);
assert(ctx->ops->context_size >= 0);
ops = ctx->ops;
context = malloc(ops->context_size);
ops->hash_copy(context, ctx->context);
options = ctx->options;
key = ctx->key ? strdup(ctx->key) : nullptr;
} | 1 | CVE-2014-6229 | 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. | 8,577 |
gpac | 77ed81c069e10b3861d88f72e1c6be1277ee7eae | GF_Err stbl_AppendSize(GF_SampleTableBox *stbl, u32 size, u32 nb_pack)
{
u32 i;
if (!nb_pack) nb_pack = 1;
if (!stbl->SampleSize->sampleCount) {
stbl->SampleSize->sampleSize = size;
stbl->SampleSize->sampleCount += nb_pack;
return GF_OK;
}
if (stbl->SampleSize->sampleSize && (stbl->SampleSize->sampleSize==size)) {
stbl->SampleSize->sampleCount += nb_pack;
return GF_OK;
}
if (!stbl->SampleSize->sizes || (stbl->SampleSize->sampleCount+nb_pack > stbl->SampleSize->alloc_size)) {
Bool init_table = (stbl->SampleSize->sizes==NULL) ? 1 : 0;
ALLOC_INC(stbl->SampleSize->alloc_size);
if (stbl->SampleSize->sampleCount+nb_pack > stbl->SampleSize->alloc_size)
stbl->SampleSize->alloc_size = stbl->SampleSize->sampleCount+nb_pack;
stbl->SampleSize->sizes = (u32 *)gf_realloc(stbl->SampleSize->sizes, sizeof(u32)*stbl->SampleSize->alloc_size);
if (!stbl->SampleSize->sizes) return GF_OUT_OF_MEM;
memset(&stbl->SampleSize->sizes[stbl->SampleSize->sampleCount], 0, sizeof(u32) * (stbl->SampleSize->alloc_size - stbl->SampleSize->sampleCount) );
if (init_table) {
for (i=0; i<stbl->SampleSize->sampleCount; i++)
stbl->SampleSize->sizes[i] = stbl->SampleSize->sampleSize;
}
}
stbl->SampleSize->sampleSize = 0;
for (i=0; i<nb_pack; i++) {
stbl->SampleSize->sizes[stbl->SampleSize->sampleCount+i] = size;
}
stbl->SampleSize->sampleCount += nb_pack;
if (size > stbl->SampleSize->max_size)
stbl->SampleSize->max_size = size;
stbl->SampleSize->total_size += size;
stbl->SampleSize->total_samples += nb_pack;
return GF_OK;
} | 1 | CVE-2021-32439 | 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,574 |
quassel | 8b5ecd226f9208af3074b33d3b7cf5e14f55b138 | QByteArray Cipher::decrypt(QByteArray cipherText)
{
QByteArray pfx = "";
bool error = false; // used to flag non cbc, seems like good practice not to parse w/o regard for set encryption type
//if we get cbc
if (cipherText.mid(0, 5) == "+OK *")
{
//if we have cbc
if (m_cbc)
cipherText = cipherText.mid(5);
//if we don't
else
{
cipherText = cipherText.mid(5);
pfx = "ERROR_NONECB: ";
error = true;
}
}
//if we get ecb
else if (cipherText.mid(0, 4) == "+OK " || cipherText.mid(0, 5) == "mcps ")
{
//if we had cbc
if (m_cbc)
{
cipherText = (cipherText.mid(0, 4) == "+OK ") ? cipherText.mid(4) : cipherText.mid(5);
pfx = "ERROR_NONCBC: ";
error = true;
}
//if we don't
else
{
if (cipherText.mid(0, 4) == "+OK ")
cipherText = cipherText.mid(4);
else
cipherText = cipherText.mid(5);
}
}
//all other cases we fail
else
return cipherText;
QByteArray temp;
// (if cbc and no error we parse cbc) || (if ecb and error we parse cbc)
if ((m_cbc && !error) || (!m_cbc && error))
{
cipherText = cipherText;
temp = blowfishCBC(cipherText, false);
if (temp == cipherText)
{
// kDebug("Decryption from CBC Failed");
return cipherText+' '+'\n';
}
else
cipherText = temp;
}
else
{
temp = blowfishECB(cipherText, false);
if (temp == cipherText)
{
// kDebug("Decryption from ECB Failed");
return cipherText+' '+'\n';
}
else
cipherText = temp;
}
// TODO FIXME the proper fix for this is to show encryption differently e.g. [nick] instead of <nick>
// don't hate me for the mircryption reference there.
if (cipherText.at(0) == 1)
pfx = "\x0";
cipherText = pfx+cipherText+' '+'\n'; // FIXME(??) why is there an added space here?
return cipherText;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,642 |
Chrome | 0720b02e4f303ea6b114d4ae9453e3a7ff55f8dc | void WebContentsImpl::RunBeforeUnloadConfirm(
RenderFrameHost* render_frame_host,
bool is_reload,
IPC::Message* reply_msg) {
RenderFrameHostImpl* rfhi =
static_cast<RenderFrameHostImpl*>(render_frame_host);
if (delegate_)
delegate_->WillRunBeforeUnloadConfirm();
bool suppress_this_message =
!rfhi->is_active() ||
ShowingInterstitialPage() || !delegate_ ||
delegate_->ShouldSuppressDialogs(this) ||
!delegate_->GetJavaScriptDialogManager(this);
if (suppress_this_message) {
rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16());
return;
}
is_showing_before_unload_dialog_ = true;
dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
dialog_manager_->RunBeforeUnloadDialog(
this, is_reload,
base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID(), reply_msg,
false));
}
| 1 | CVE-2017-5093 | 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,336 |
mongo | 07b8851825836911265e909d6842d4586832f9bb | void DocumentSourceGroup::addAccumulator(AccumulationStatement accumulationStatement) {
_accumulatedFields.push_back(accumulationStatement);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,515 |
openssl | 76343947ada960b6269090638f5391068daee88d | static int tls1_get_curvelist(SSL *s, int sess,
const unsigned char **pcurves,
size_t *num_curves)
{
size_t pcurveslen = 0;
if (sess) {
*pcurves = s->session->tlsext_ellipticcurvelist;
pcurveslen = s->session->tlsext_ellipticcurvelist_length;
} else {
/* For Suite B mode only include P-256, P-384 */
switch (tls1_suiteb(s)) {
case SSL_CERT_FLAG_SUITEB_128_LOS:
*pcurves = suiteb_curves;
pcurveslen = sizeof(suiteb_curves);
break;
case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
*pcurves = suiteb_curves;
pcurveslen = 2;
break;
case SSL_CERT_FLAG_SUITEB_192_LOS:
*pcurves = suiteb_curves + 2;
pcurveslen = 2;
break;
default:
*pcurves = s->tlsext_ellipticcurvelist;
pcurveslen = s->tlsext_ellipticcurvelist_length;
}
if (!*pcurves) {
# ifdef OPENSSL_FIPS
if (FIPS_mode()) {
*pcurves = fips_curves_default;
pcurveslen = sizeof(fips_curves_default);
} else
# endif
{
*pcurves = eccurves_default;
pcurveslen = sizeof(eccurves_default);
}
}
}
/* We do not allow odd length arrays to enter the system. */
if (pcurveslen & 1) {
SSLerr(SSL_F_TLS1_GET_CURVELIST, ERR_R_INTERNAL_ERROR);
*num_curves = 0;
return 0;
} else {
*num_curves = pcurveslen / 2;
return 1;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,450 |
ImageMagick | 1f450bb5ba53d275de6d1cd086c98a0b549ad393 | static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info,
const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception)
{
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
Image
*image;
ImageInfo
*image_info;
char
*name,
s[2];
const char
*property,
*value;
const StringInfo
*profile;
int
num_passes,
pass,
ping_wrote_caNv;
png_byte
ping_trans_alpha[256];
png_color
palette[257];
png_color_16
ping_background,
ping_trans_color;
png_info
*ping_info;
png_struct
*ping;
png_uint_32
ping_height,
ping_width;
ssize_t
y;
MagickBooleanType
image_matte,
logging,
matte,
ping_have_blob,
ping_have_cheap_transparency,
ping_have_color,
ping_have_non_bw,
ping_have_PLTE,
ping_have_bKGD,
ping_have_eXIf,
ping_have_iCCP,
ping_have_pHYs,
ping_have_sRGB,
ping_have_tRNS,
ping_exclude_bKGD,
ping_exclude_cHRM,
ping_exclude_date,
/* ping_exclude_EXIF, */
ping_exclude_eXIf,
ping_exclude_gAMA,
ping_exclude_iCCP,
/* ping_exclude_iTXt, */
ping_exclude_oFFs,
ping_exclude_pHYs,
ping_exclude_sRGB,
ping_exclude_tEXt,
ping_exclude_tIME,
/* ping_exclude_tRNS, */
ping_exclude_caNv,
ping_exclude_zCCP, /* hex-encoded iCCP */
ping_exclude_zTXt,
ping_preserve_colormap,
ping_preserve_iCCP,
ping_need_colortype_warning,
status,
tried_332,
tried_333,
tried_444;
MemoryInfo
*volatile pixel_info;
QuantumInfo
*quantum_info;
PNGErrorInfo
error_info;
register ssize_t
i,
x;
unsigned char
*ping_pixels;
volatile int
image_colors,
ping_bit_depth,
ping_color_type,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans;
volatile size_t
image_depth,
old_bit_depth;
size_t
quality,
rowbytes,
save_image_depth;
int
j,
number_colors,
number_opaque,
number_semitransparent,
number_transparent,
ping_pHYs_unit_type;
png_uint_32
ping_pHYs_x_resolution,
ping_pHYs_y_resolution;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter WriteOnePNGImage()");
image = CloneImage(IMimage,0,0,MagickFalse,exception);
if (image == (Image *) NULL)
return(MagickFalse);
image_info=(ImageInfo *) CloneImageInfo(IMimage_info);
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,MagickPathExtent);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,MagickPathExtent);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" IM version = %s", im_vers);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Libpng version = %s", libpng_vers);
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" running with %s", libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Zlib version = %s", zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" running with %s", zlib_runv);
}
}
/* Initialize some stuff */
ping_bit_depth=0,
ping_color_type=0,
ping_interlace_method=0,
ping_compression_method=0,
ping_filter_method=0,
ping_num_trans = 0;
ping_background.red = 0;
ping_background.green = 0;
ping_background.blue = 0;
ping_background.gray = 0;
ping_background.index = 0;
ping_trans_color.red=0;
ping_trans_color.green=0;
ping_trans_color.blue=0;
ping_trans_color.gray=0;
ping_pHYs_unit_type = 0;
ping_pHYs_x_resolution = 0;
ping_pHYs_y_resolution = 0;
ping_have_blob=MagickFalse;
ping_have_cheap_transparency=MagickFalse;
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
ping_have_PLTE=MagickFalse;
ping_have_bKGD=MagickFalse;
ping_have_eXIf=MagickTrue;
ping_have_iCCP=MagickFalse;
ping_have_pHYs=MagickFalse;
ping_have_sRGB=MagickFalse;
ping_have_tRNS=MagickFalse;
ping_exclude_bKGD=mng_info->ping_exclude_bKGD;
ping_exclude_caNv=mng_info->ping_exclude_caNv;
ping_exclude_cHRM=mng_info->ping_exclude_cHRM;
ping_exclude_date=mng_info->ping_exclude_date;
ping_exclude_eXIf=mng_info->ping_exclude_eXIf;
ping_exclude_gAMA=mng_info->ping_exclude_gAMA;
ping_exclude_iCCP=mng_info->ping_exclude_iCCP;
/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */
ping_exclude_oFFs=mng_info->ping_exclude_oFFs;
ping_exclude_pHYs=mng_info->ping_exclude_pHYs;
ping_exclude_sRGB=mng_info->ping_exclude_sRGB;
ping_exclude_tEXt=mng_info->ping_exclude_tEXt;
ping_exclude_tIME=mng_info->ping_exclude_tIME;
/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */
ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */
ping_exclude_zTXt=mng_info->ping_exclude_zTXt;
ping_preserve_colormap = mng_info->ping_preserve_colormap;
ping_preserve_iCCP = mng_info->ping_preserve_iCCP;
ping_need_colortype_warning = MagickFalse;
/* Recognize the ICC sRGB profile and convert it to the sRGB chunk,
* i.e., eliminate the ICC profile and set image->rendering_intent.
* Note that this will not involve any changes to the actual pixels
* but merely passes information to applications that read the resulting
* PNG image.
*
* To do: recognize other variants of the sRGB profile, using the CRC to
* verify all recognized variants including the 7 already known.
*
* Work around libpng16+ rejecting some "known invalid sRGB profiles".
*
* Use something other than image->rendering_intent to record the fact
* that the sRGB profile was found.
*
* Record the ICC version (currently v2 or v4) of the incoming sRGB ICC
* profile. Record the Blackpoint Compensation, if any.
*/
if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse)
{
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
ping_exclude_iCCP = MagickTrue;
ping_exclude_zCCP = MagickTrue;
ping_have_sRGB = MagickTrue;
break;
}
}
}
if (sRGB_info[icheck].len == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
}
}
name=GetNextImageProfile(image);
}
}
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
if (logging != MagickFalse)
{
if (image->storage_class == UndefinedClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=UndefinedClass");
if (image->storage_class == DirectClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=DirectClass");
if (image->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=PseudoClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ?
" image->taint=MagickTrue":
" image->taint=MagickFalse");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->gamma=%g", image->gamma);
}
if (image->storage_class == PseudoClass &&
(mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(mng_info->write_png_colortype != 1 &&
mng_info->write_png_colortype != 5)))
{
(void) SyncImage(image,exception);
image->storage_class = DirectClass;
}
if (ping_preserve_colormap == MagickFalse)
{
if ((image->storage_class != PseudoClass) &&
(image->colormap != (PixelInfo *) NULL))
{
/* Free the bogus colormap; it can cause trouble later */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Freeing bogus colormap");
image->colormap=(PixelInfo *) RelinquishMagickMemory(
image->colormap);
}
}
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Sometimes we get PseudoClass images whose RGB values don't match
the colors in the colormap. This code syncs the RGB values.
*/
image->depth=GetImageQuantumDepth(image,MagickFalse);
if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->depth > 8)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reducing PNG bit depth to 8 since this is a Q8 build.");
image->depth=8;
}
#endif
/* Respect the -depth option */
if (image->depth < 4)
{
register Quantum
*r;
if (image->depth > 2)
{
/* Scale to 4-bit */
LBR04PacketRGBA(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR04PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR04PacketRGBA(image->colormap[i]);
}
}
}
else if (image->depth > 1)
{
/* Scale to 2-bit */
LBR02PacketRGBA(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR02PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR02PacketRGBA(image->colormap[i]);
}
}
}
else
{
/* Scale to 1-bit */
LBR01PacketRGBA(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR01PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR01PacketRGBA(image->colormap[i]);
}
}
}
}
/* To do: set to next higher multiple of 8 */
if (image->depth < 8)
image->depth=8;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy
*/
if (image->depth > 8)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (image->depth == 16 && mng_info->write_png_depth != 16)
if (mng_info->write_png8 ||
LosslessReduceDepthOK(image,exception) != MagickFalse)
image->depth = 8;
#endif
image_colors = (int) image->colors;
number_opaque = (int) image->colors;
number_transparent = 0;
number_semitransparent = 0;
if (mng_info->write_png_colortype &&
(mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 &&
mng_info->write_png_colortype < 4 &&
image->alpha_trait == UndefinedPixelTrait)))
{
/* Avoid the expensive BUILD_PALETTE operation if we're sure that we
* are not going to need the result.
*/
if (mng_info->write_png_colortype == 1 ||
mng_info->write_png_colortype == 5)
ping_have_color=MagickFalse;
if (image->alpha_trait != UndefinedPixelTrait)
{
number_transparent = 2;
number_semitransparent = 1;
}
}
if (mng_info->write_png_colortype < 7)
{
/* BUILD_PALETTE
*
* Normally we run this just once, but in the case of writing PNG8
* we reduce the transparency to binary and run again, then if there
* are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1
* RGBA palette and run again, and then to a simple 3-3-2-1 RGBA
* palette. Then (To do) we take care of a final reduction that is only
* needed if there are still 256 colors present and one of them has both
* transparent and opaque instances.
*/
tried_332 = MagickFalse;
tried_333 = MagickFalse;
tried_444 = MagickFalse;
if (image->depth != GetImageDepth(image,exception))
(void) SetImageDepth(image,image->depth,exception);
for (j=0; j<6; j++)
{
/*
* Sometimes we get DirectClass images that have 256 colors or fewer.
* This code will build a colormap.
*
* Also, sometimes we get PseudoClass images with an out-of-date
* colormap. This code will replace the colormap with a new one.
* Sometimes we get PseudoClass images that have more than 256 colors.
* This code will delete the colormap and change the image to
* DirectClass.
*
* If image->alpha_trait is MagickFalse, we ignore the alpha channel
* even though it sometimes contains left-over non-opaque values.
*
* Also we gather some information (number of opaque, transparent,
* and semitransparent pixels, and whether the image has any non-gray
* pixels or only black-and-white pixels) that we might need later.
*
* Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6)
* we need to check for bogus non-opaque values, at least.
*/
int
n;
PixelInfo
opaque[260],
semitransparent[260],
transparent[260];
register const Quantum
*r;
register Quantum
*q;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter BUILD_PALETTE:");
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->columns=%.20g",(double) image->columns);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->rows=%.20g",(double) image->rows);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->alpha_trait=%.20g",(double) image->alpha_trait);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Original colormap:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,alpha)");
for (i=0; i < MagickMin(image->colors,256); i++)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
for (i=image->colors - 10; i < (ssize_t) image->colors; i++)
{
if (i > 255)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d",(int) image->colors);
if (image->colors == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" (zero means unknown)");
if (ping_preserve_colormap == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Regenerate the colormap");
}
image_colors=0;
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (r == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait == UndefinedPixelTrait ||
GetPixelAlpha(image,r) == OpaqueAlpha)
{
if (number_opaque < 259)
{
if (number_opaque == 0)
{
GetPixelInfoPixel(image,r,opaque);
opaque[0].alpha=OpaqueAlpha;
number_opaque=1;
}
for (i=0; i< (ssize_t) number_opaque; i++)
{
if (IsColorEqual(image,r,opaque+i))
break;
}
if (i == (ssize_t) number_opaque && number_opaque < 259)
{
number_opaque++;
GetPixelInfoPixel(image,r,opaque+i);
opaque[i].alpha=OpaqueAlpha;
}
}
}
else if (GetPixelAlpha(image,r) == TransparentAlpha)
{
if (number_transparent < 259)
{
if (number_transparent == 0)
{
GetPixelInfoPixel(image,r,transparent);
ping_trans_color.red=(unsigned short)
GetPixelRed(image,r);
ping_trans_color.green=(unsigned short)
GetPixelGreen(image,r);
ping_trans_color.blue=(unsigned short)
GetPixelBlue(image,r);
ping_trans_color.gray=(unsigned short)
GetPixelGray(image,r);
number_transparent = 1;
}
for (i=0; i< (ssize_t) number_transparent; i++)
{
if (IsColorEqual(image,r,transparent+i))
break;
}
if (i == (ssize_t) number_transparent &&
number_transparent < 259)
{
number_transparent++;
GetPixelInfoPixel(image,r,transparent+i);
}
}
}
else
{
if (number_semitransparent < 259)
{
if (number_semitransparent == 0)
{
GetPixelInfoPixel(image,r,semitransparent);
number_semitransparent = 1;
}
for (i=0; i< (ssize_t) number_semitransparent; i++)
{
if (IsColorEqual(image,r,semitransparent+i)
&& GetPixelAlpha(image,r) ==
semitransparent[i].alpha)
break;
}
if (i == (ssize_t) number_semitransparent &&
number_semitransparent < 259)
{
number_semitransparent++;
GetPixelInfoPixel(image,r,semitransparent+i);
}
}
}
r+=GetPixelChannels(image);
}
}
if (mng_info->write_png8 == MagickFalse &&
ping_exclude_bKGD == MagickFalse)
{
/* Add the background color to the palette, if it
* isn't already there.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Check colormap for background (%d,%d,%d)",
(int) image->background_color.red,
(int) image->background_color.green,
(int) image->background_color.blue);
}
if (number_opaque < 259)
{
for (i=0; i<number_opaque; i++)
{
if (opaque[i].red == image->background_color.red &&
opaque[i].green == image->background_color.green &&
opaque[i].blue == image->background_color.blue)
break;
}
if (i == number_opaque)
{
opaque[i] = image->background_color;
ping_background.index = i;
number_opaque++;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",(int) i);
}
}
}
else if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in the colormap to add background color");
}
image_colors=number_opaque+number_transparent+number_semitransparent;
if (logging != MagickFalse)
{
if (image_colors > 256)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has more than 256 colors");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has %d colors",image_colors);
}
if (ping_preserve_colormap != MagickFalse)
break;
if (mng_info->write_png_colortype != 7) /* We won't need this info */
{
ping_have_color=MagickFalse;
ping_have_non_bw=MagickFalse;
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"incompatible colorspace");
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
}
if(image_colors > 256)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
r=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(image,r) != GetPixelGreen(image,r) ||
GetPixelRed(image,r) != GetPixelBlue(image,r))
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
r+=GetPixelChannels(image);
}
if (ping_have_color != MagickFalse)
break;
/* Worst case is black-and-white; we are looking at every
* pixel twice.
*/
if (ping_have_non_bw == MagickFalse)
{
r=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(image,r) != 0 &&
GetPixelRed(image,r) != QuantumRange)
{
ping_have_non_bw=MagickTrue;
break;
}
r+=GetPixelChannels(image);
}
}
}
}
}
if (image_colors < 257)
{
PixelInfo
colormap[260];
/*
* Initialize image colormap.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Sort the new colormap");
/* Sort palette, transparent first */;
n = 0;
for (i=0; i<number_transparent; i++)
colormap[n++] = transparent[i];
for (i=0; i<number_semitransparent; i++)
colormap[n++] = semitransparent[i];
for (i=0; i<number_opaque; i++)
colormap[n++] = opaque[i];
ping_background.index +=
(number_transparent + number_semitransparent);
/* image_colors < 257; search the colormap instead of the pixels
* to get ping_have_color and ping_have_non_bw
*/
for (i=0; i<n; i++)
{
if (ping_have_color == MagickFalse)
{
if (colormap[i].red != colormap[i].green ||
colormap[i].red != colormap[i].blue)
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
}
if (ping_have_non_bw == MagickFalse)
{
if (colormap[i].red != 0 && colormap[i].red != QuantumRange)
ping_have_non_bw=MagickTrue;
}
}
if ((mng_info->ping_exclude_tRNS == MagickFalse ||
(number_transparent == 0 && number_semitransparent == 0)) &&
(((mng_info->write_png_colortype-1) ==
PNG_COLOR_TYPE_PALETTE) ||
(mng_info->write_png_colortype == 0)))
{
if (logging != MagickFalse)
{
if (n != (ssize_t) image_colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_colors (%d) and n (%d) don't match",
image_colors, n);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireImageColormap");
}
image->colors = image_colors;
if (AcquireImageColormap(image,image_colors,exception) == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
for (i=0; i< (ssize_t) image_colors; i++)
image->colormap[i] = colormap[i];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d (%d)",
(int) image->colors, image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Update the pixel indexes");
}
/* Sync the pixel indices with the new colormap */
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i< (ssize_t) image_colors; i++)
{
if ((image->alpha_trait == UndefinedPixelTrait ||
image->colormap[i].alpha == GetPixelAlpha(image,q)) &&
image->colormap[i].red == GetPixelRed(image,q) &&
image->colormap[i].green == GetPixelGreen(image,q) &&
image->colormap[i].blue == GetPixelBlue(image,q))
{
SetPixelIndex(image,i,q);
break;
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d", (int) image->colors);
if (image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,alpha)");
for (i=0; i < (ssize_t) image->colors; i++)
{
if (i < 300 || i >= (ssize_t) image->colors - 10)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
}
}
if (number_transparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent = %d",
number_transparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent > 256");
if (number_opaque < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque = %d",
number_opaque);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque > 256");
if (number_semitransparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent = %d",
number_semitransparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent > 256");
if (ping_have_non_bw == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are black or white");
else if (ping_have_color == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are gray");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" At least one pixel or the background is non-gray");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Exit BUILD_PALETTE:");
}
if (mng_info->write_png8 == MagickFalse)
break;
/* Make any reductions necessary for the PNG8 format */
if (image_colors <= 256 &&
image_colors != 0 && image->colormap != NULL &&
number_semitransparent == 0 &&
number_transparent <= 1)
break;
/* PNG8 can't have semitransparent colors so we threshold the
* opacity to 0 or OpaqueOpacity, and PNG8 can only have one
* transparent color so if more than one is transparent we merge
* them into image->background_color.
*/
if (number_semitransparent != 0 || number_transparent > 1)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Thresholding the alpha channel to binary");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,q) < OpaqueAlpha/2)
{
SetPixelViaPixelInfo(image,&image->background_color,q);
SetPixelAlpha(image,TransparentAlpha,q);
}
else
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image_colors != 0 && image_colors <= 256 &&
image->colormap != NULL)
for (i=0; i<image_colors; i++)
image->colormap[i].alpha =
(image->colormap[i].alpha > TransparentAlpha/2 ?
TransparentAlpha : OpaqueAlpha);
}
continue;
}
/* PNG8 can't have more than 256 colors so we quantize the pixels and
* background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the
* image is mostly gray, the 4-4-4-1 palette is likely to end up with 256
* colors or less.
*/
if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 4-4-4");
tried_444 = MagickTrue;
LBR04PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 4-4-4");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,q) == OpaqueAlpha)
LBR04PixelRGB(q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 4-4-4");
for (i=0; i<image_colors; i++)
{
LBR04PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-3");
tried_333 = MagickTrue;
LBR03PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-3-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,q) == OpaqueAlpha)
LBR03RGB(q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-3-1");
for (i=0; i<image_colors; i++)
{
LBR03PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-2");
tried_332 = MagickTrue;
/* Red and green were already done so we only quantize the blue
* channel
*/
LBR02PacketBlue(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,q) == OpaqueAlpha)
LBR02PixelBlue(q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-2-1");
for (i=0; i<image_colors; i++)
{
LBR02PacketBlue(image->colormap[i]);
}
}
continue;
}
if (image_colors == 0 || image_colors > 256)
{
/* Take care of special case with 256 opaque colors + 1 transparent
* color. We don't need to quantize to 2-3-2-1; we only need to
* eliminate one color, so we'll merge the two darkest red
* colors (0x49, 0, 0) -> (0x24, 0, 0).
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red background colors to 3-3-2-1");
if (ScaleQuantumToChar(image->background_color.red) == 0x49 &&
ScaleQuantumToChar(image->background_color.green) == 0x00 &&
ScaleQuantumToChar(image->background_color.blue) == 0x00)
{
image->background_color.red=ScaleCharToQuantum(0x24);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ScaleQuantumToChar(GetPixelRed(image,q)) == 0x49 &&
ScaleQuantumToChar(GetPixelGreen(image,q)) == 0x00 &&
ScaleQuantumToChar(GetPixelBlue(image,q)) == 0x00 &&
GetPixelAlpha(image,q) == OpaqueAlpha)
{
SetPixelRed(image,ScaleCharToQuantum(0x24),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else
{
for (i=0; i<image_colors; i++)
{
if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 &&
ScaleQuantumToChar(image->colormap[i].green) == 0x00 &&
ScaleQuantumToChar(image->colormap[i].blue) == 0x00)
{
image->colormap[i].red=ScaleCharToQuantum(0x24);
}
}
}
}
}
}
/* END OF BUILD_PALETTE */
/* If we are excluding the tRNS chunk and there is transparency,
* then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6)
* PNG.
*/
if (mng_info->ping_exclude_tRNS != MagickFalse &&
(number_transparent != 0 || number_semitransparent != 0))
{
unsigned int colortype=mng_info->write_png_colortype;
if (ping_have_color == MagickFalse)
mng_info->write_png_colortype = 5;
else
mng_info->write_png_colortype = 7;
if (colortype != 0 &&
mng_info->write_png_colortype != colortype)
ping_need_colortype_warning=MagickTrue;
}
/* See if cheap transparency is possible. It is only possible
* when there is a single transparent color, no semitransparent
* color, and no opaque color that has the same RGB components
* as the transparent color. We only need this information if
* we are writing a PNG with colortype 0 or 2, and we have not
* excluded the tRNS chunk.
*/
if (number_transparent == 1 &&
mng_info->write_png_colortype < 4)
{
ping_have_cheap_transparency = MagickTrue;
if (number_semitransparent != 0)
ping_have_cheap_transparency = MagickFalse;
else if (image_colors == 0 || image_colors > 256 ||
image->colormap == NULL)
{
register const Quantum
*q;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,q) != TransparentAlpha &&
(unsigned short) GetPixelRed(image,q) ==
ping_trans_color.red &&
(unsigned short) GetPixelGreen(image,q) ==
ping_trans_color.green &&
(unsigned short) GetPixelBlue(image,q) ==
ping_trans_color.blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
q+=GetPixelChannels(image);
}
if (ping_have_cheap_transparency == MagickFalse)
break;
}
}
else
{
/* Assuming that image->colormap[0] is the one transparent color
* and that all others are opaque.
*/
if (image_colors > 1)
for (i=1; i<image_colors; i++)
if (image->colormap[i].red == image->colormap[0].red &&
image->colormap[i].green == image->colormap[0].green &&
image->colormap[i].blue == image->colormap[0].blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
}
if (logging != MagickFalse)
{
if (ping_have_cheap_transparency == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is not possible.");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is possible.");
}
}
else
ping_have_cheap_transparency = MagickFalse;
image_depth=image->depth;
quantum_info = (QuantumInfo *) NULL;
number_colors=0;
image_colors=(int) image->colors;
image_matte=image->alpha_trait !=
UndefinedPixelTrait ? MagickTrue : MagickFalse;
if (mng_info->write_png_colortype < 5)
mng_info->IsPalette=image->storage_class == PseudoClass &&
image_colors <= 256 && image->colormap != NULL;
else
mng_info->IsPalette = MagickFalse;
if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) &&
(image->colors == 0 || image->colormap == NULL))
{
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"Cannot write PNG8 or color-type 3; colormap is NULL",
"`%s'",IMimage->filename);
return(MagickFalse);
}
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
error_info.image=image;
error_info.exception=exception;
ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_write_struct(&ping,(png_info **) NULL);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
png_set_write_fn(ping,image,png_put_data,png_flush_data);
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG write failed.
*/
#ifdef PNG_DEBUG
if (image_info->verbose)
(void) printf("PNG write has failed.\n");
#endif
png_destroy_write_struct(&ping,&ping_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (ping_have_blob != MagickFalse)
(void) CloseBlob(image);
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
return(MagickFalse);
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for writing.
*/
#if defined(PNG_MNG_FEATURES_SUPPORTED)
if (mng_info->write_mng)
{
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature when writing a MNG because
* zero-length PLTE is OK
*/
png_set_check_for_invalid_index (ping, 0);
# endif
}
#else
# ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
if (mng_info->write_mng)
png_permit_empty_plte(ping,MagickTrue);
# endif
#endif
x=0;
ping_width=(png_uint_32) image->columns;
ping_height=(png_uint_32) image->rows;
if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32)
image_depth=8;
if (mng_info->write_png48 || mng_info->write_png64)
image_depth=16;
if (mng_info->write_png_depth != 0)
image_depth=mng_info->write_png_depth;
/* Adjust requested depth to next higher valid depth if necessary */
if (image_depth > 8)
image_depth=16;
if ((image_depth > 4) && (image_depth < 8))
image_depth=8;
if (image_depth == 3)
image_depth=4;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" width=%.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" height=%.20g",(double) ping_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_matte=%.20g",(double) image->alpha_trait);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative ping_bit_depth=%.20g",(double) image_depth);
}
save_image_depth=image_depth;
ping_bit_depth=(png_byte) save_image_depth;
#if defined(PNG_pHYs_SUPPORTED)
if (ping_exclude_pHYs == MagickFalse)
{
if ((image->resolution.x != 0) && (image->resolution.y != 0) &&
(!mng_info->write_mng || !mng_info->equal_physs))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
if (image->units == PixelsPerInchResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=
(png_uint_32) ((100.0*image->resolution.x+0.5)/2.54);
ping_pHYs_y_resolution=
(png_uint_32) ((100.0*image->resolution.y+0.5)/2.54);
}
else if (image->units == PixelsPerCentimeterResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5);
ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5);
}
else
{
ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN;
ping_pHYs_x_resolution=(png_uint_32) image->resolution.x;
ping_pHYs_y_resolution=(png_uint_32) image->resolution.y;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution,
(int) ping_pHYs_unit_type);
ping_have_pHYs = MagickTrue;
}
}
#endif
if (ping_exclude_bKGD == MagickFalse)
{
if ((!mng_info->adjoin || !mng_info->equal_backgrounds))
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_background.red=(png_uint_16)
(ScaleQuantumToShort(image->background_color.red) & mask);
ping_background.green=(png_uint_16)
(ScaleQuantumToShort(image->background_color.green) & mask);
ping_background.blue=(png_uint_16)
(ScaleQuantumToShort(image->background_color.blue) & mask);
ping_background.gray=(png_uint_16) ping_background.green;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (1)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth=%d",ping_bit_depth);
}
ping_have_bKGD = MagickTrue;
}
/*
Select the color type.
*/
matte=image_matte;
old_bit_depth=0;
if (mng_info->IsPalette && mng_info->write_png8)
{
/* To do: make this a function cause it's used twice, except
for reducing the sample depth from 8. */
number_colors=image_colors;
ping_have_tRNS=MagickFalse;
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors (%d)",
number_colors, image_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
#if MAGICKCORE_QUANTUM_DEPTH == 8
" %3ld (%3d,%3d,%3d)",
#else
" %5ld (%5d,%5d,%5d)",
#endif
(long) i,palette[i].red,palette[i].green,palette[i].blue);
}
ping_have_PLTE=MagickTrue;
image_depth=ping_bit_depth;
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
Identify which colormap entry is transparent.
*/
assert(number_colors <= 256);
assert(image->colormap != NULL);
for (i=0; i < (ssize_t) number_transparent; i++)
ping_trans_alpha[i]=0;
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
ping_have_tRNS=MagickTrue;
}
if (ping_exclude_bKGD == MagickFalse)
{
/*
* Identify which colormap entry is the background color.
*/
for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++)
if (IsPNGColorEqual(ping_background,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
}
}
} /* end of write_png8 */
else if (mng_info->write_png_colortype == 1)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
}
else if (mng_info->write_png24 || mng_info->write_png48 ||
mng_info->write_png_colortype == 3)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
}
else if (mng_info->write_png32 || mng_info->write_png64 ||
mng_info->write_png_colortype == 7)
{
image_matte=MagickTrue;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
}
else /* mng_info->write_pngNN not specified */
{
image_depth=ping_bit_depth;
if (mng_info->write_png_colortype != 0)
{
ping_color_type=(png_byte) mng_info->write_png_colortype-1;
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
image_matte=MagickTrue;
else
image_matte=MagickFalse;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG colortype %d was specified:",(int) ping_color_type);
}
else /* write_png_colortype not specified */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selecting PNG colortype:");
if (image_info->type == TrueColorType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
else if (image_info->type == TrueColorAlphaType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
image_matte=MagickTrue;
}
else if (image_info->type == PaletteType ||
image_info->type == PaletteAlphaType)
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
else
{
if (ping_have_color == MagickFalse)
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA;
image_matte=MagickTrue;
}
}
else
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA;
image_matte=MagickTrue;
}
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selected PNG colortype=%d",ping_color_type);
if (ping_bit_depth < 8)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
ping_bit_depth=8;
}
old_bit_depth=ping_bit_depth;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->alpha_trait == UndefinedPixelTrait &&
ping_have_non_bw == MagickFalse)
ping_bit_depth=1;
}
if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
size_t one = 1;
ping_bit_depth=1;
if (image->colors == 0)
{
/* DO SOMETHING */
png_error(ping,"image has 0 colors");
}
while ((int) (one << ping_bit_depth) < (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %.20g",(double) image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG bit depth: %d",ping_bit_depth);
}
if (ping_bit_depth < (int) mng_info->write_png_depth)
ping_bit_depth = mng_info->write_png_depth;
}
(void) old_bit_depth;
image_depth=ping_bit_depth;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG color type: %s (%.20g)",
PngColorTypeToString(ping_color_type),
(double) ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_info->type: %.20g",(double) image_info->type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_depth: %.20g",(double) image_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth: %.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth: %.20g",(double) ping_bit_depth);
}
if (matte != MagickFalse)
{
if (mng_info->IsPalette)
{
if (mng_info->write_png_colortype == 0)
{
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
if (ping_have_color != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_RGBA;
}
/*
* Determine if there is any transparent color.
*/
if (number_transparent + number_semitransparent == 0)
{
/*
No transparent pixels are present. Change 4 or 6 to 0 or 2.
*/
image_matte=MagickFalse;
if (mng_info->write_png_colortype == 0)
ping_color_type&=0x03;
}
else
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_trans_color.red=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].red) & mask);
ping_trans_color.green=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].green) & mask);
ping_trans_color.blue=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].blue) & mask);
ping_trans_color.gray=(png_uint_16)
(ScaleQuantumToShort(GetPixelInfoIntensity(image,
image->colormap)) & mask);
ping_trans_color.index=(png_byte) 0;
ping_have_tRNS=MagickTrue;
}
if (ping_have_tRNS != MagickFalse)
{
/*
* Determine if there is one and only one transparent color
* and if so if it is fully transparent.
*/
if (ping_have_cheap_transparency == MagickFalse)
ping_have_tRNS=MagickFalse;
}
if (ping_have_tRNS != MagickFalse)
{
if (mng_info->write_png_colortype == 0)
ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
else
{
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
matte=image_matte;
if (ping_have_tRNS != MagickFalse)
image_matte=MagickFalse;
if ((mng_info->IsPalette) &&
mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE &&
ping_have_color == MagickFalse &&
(image_matte == MagickFalse || image_depth >= 8))
{
size_t one=1;
if (image_matte != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA)
{
ping_color_type=PNG_COLOR_TYPE_GRAY;
if (save_image_depth == 16 && image_depth == 8)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (0)");
}
ping_trans_color.gray*=0x0101;
}
}
if (image_depth > MAGICKCORE_QUANTUM_DEPTH)
image_depth=MAGICKCORE_QUANTUM_DEPTH;
if ((image_colors == 0) ||
((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize))
image_colors=(int) (one << image_depth);
if (image_depth > 8)
ping_bit_depth=16;
else
{
ping_bit_depth=8;
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
if(!mng_info->write_png_depth)
{
ping_bit_depth=1;
while ((int) (one << ping_bit_depth)
< (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
}
else if (ping_color_type ==
PNG_COLOR_TYPE_GRAY && image_colors < 17 &&
mng_info->IsPalette)
{
/* Check if grayscale is reducible */
int
depth_4_ok=MagickTrue,
depth_2_ok=MagickTrue,
depth_1_ok=MagickTrue;
for (i=0; i < (ssize_t) image_colors; i++)
{
unsigned char
intensity;
intensity=ScaleQuantumToChar(image->colormap[i].red);
if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4))
depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2))
depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x01) != ((intensity & 0x02) >> 1))
depth_1_ok=MagickFalse;
}
if (depth_1_ok && mng_info->write_png_depth <= 1)
ping_bit_depth=1;
else if (depth_2_ok && mng_info->write_png_depth <= 2)
ping_bit_depth=2;
else if (depth_4_ok && mng_info->write_png_depth <= 4)
ping_bit_depth=4;
}
}
image_depth=ping_bit_depth;
}
else
if (mng_info->IsPalette)
{
number_colors=image_colors;
if (image_depth <= 8)
{
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (!(mng_info->have_write_global_plte && matte == MagickFalse))
{
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=
ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors",
number_colors);
ping_have_PLTE=MagickTrue;
}
/* color_type is PNG_COLOR_TYPE_PALETTE */
if (mng_info->write_png_depth == 0)
{
size_t
one;
ping_bit_depth=1;
one=1;
while ((one << ping_bit_depth) < (size_t) number_colors)
ping_bit_depth <<= 1;
}
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
* Set up trans_colors array.
*/
assert(number_colors <= 256);
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (1)");
}
ping_have_tRNS=MagickTrue;
for (i=0; i < ping_num_trans; i++)
{
ping_trans_alpha[i]= (png_byte)
ScaleQuantumToChar(image->colormap[i].alpha);
}
}
}
}
}
else
{
if (image_depth < 8)
image_depth=8;
if ((save_image_depth == 16) && (image_depth == 8))
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color from (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
ping_trans_color.red*=0x0101;
ping_trans_color.green*=0x0101;
ping_trans_color.blue*=0x0101;
ping_trans_color.gray*=0x0101;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
if (ping_bit_depth < (ssize_t) mng_info->write_png_depth)
ping_bit_depth = (ssize_t) mng_info->write_png_depth;
/*
Adjust background and transparency samples in sub-8-bit grayscale files.
*/
if (ping_bit_depth < 8 && ping_color_type ==
PNG_COLOR_TYPE_GRAY)
{
png_uint_16
maxval;
size_t
one=1;
maxval=(png_uint_16) ((one << ping_bit_depth)-1);
if (ping_exclude_bKGD == MagickFalse)
{
ping_background.gray=(png_uint_16) ((maxval/65535.)*
(ScaleQuantumToShort(((GetPixelInfoIntensity(image,
&image->background_color))) +.5)));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (2)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
ping_have_bKGD = MagickTrue;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color.gray from %d",
(int)ping_trans_color.gray);
ping_trans_color.gray=(png_uint_16) ((maxval/255.)*(
ping_trans_color.gray)+.5);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to %d", (int)ping_trans_color.gray);
}
if (ping_exclude_bKGD == MagickFalse)
{
if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
/*
Identify which colormap entry is the background color.
*/
number_colors=image_colors;
for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++)
if (IsPNGColorEqual(image->background_color,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk with index=%d",(int) i);
}
if (i < (ssize_t) number_colors)
{
ping_have_bKGD = MagickTrue;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background =(%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
}
}
else /* Can't happen */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in PLTE to add bKGD color");
ping_have_bKGD = MagickFalse;
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color type: %s (%d)", PngColorTypeToString(ping_color_type),
ping_color_type);
/*
Initialize compression level and filtering.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up deflate compression");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression buffer size: 32768");
}
png_set_compression_buffer_size(ping,32768L);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression mem level: 9");
png_set_compression_mem_level(ping, 9);
/* Untangle the "-quality" setting:
Undefined is 0; the default is used.
Default is 75
10's digit:
0 or omitted: Use Z_HUFFMAN_ONLY strategy with the
zlib default compression level
1-9: the zlib compression level
1's digit:
0-4: the PNG filter method
5: libpng adaptive filtering if compression level > 5
libpng filter type "none" if compression level <= 5
or if image is grayscale or palette
6: libpng adaptive filtering
7: "LOCO" filtering (intrapixel differing) if writing
a MNG, otherwise "none". Did not work in IM-6.7.0-9
and earlier because of a missing "else".
8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive
filtering. Unused prior to IM-6.7.0-10, was same as 6
9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters
Unused prior to IM-6.7.0-10, was same as 6
Note that using the -quality option, not all combinations of
PNG filter type, zlib compression level, and zlib compression
strategy are possible. This will be addressed soon in a
release that accomodates "-define png:compression-strategy", etc.
*/
quality=image_info->quality == UndefinedCompressionQuality ? 75UL :
image_info->quality;
if (quality <= 9)
{
if (mng_info->write_png_compression_strategy == 0)
mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;
}
else if (mng_info->write_png_compression_level == 0)
{
int
level;
level=(int) MagickMin((ssize_t) quality/10,9);
mng_info->write_png_compression_level = level+1;
}
if (mng_info->write_png_compression_strategy == 0)
{
if ((quality %10) == 8 || (quality %10) == 9)
#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */
mng_info->write_png_compression_strategy=Z_RLE+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
}
if (mng_info->write_png_compression_filter == 0)
mng_info->write_png_compression_filter=((int) quality % 10) + 1;
if (logging != MagickFalse)
{
if (mng_info->write_png_compression_level)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression level: %d",
(int) mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_strategy)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression strategy: %d",
(int) mng_info->write_png_compression_strategy-1);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up filtering");
if (mng_info->write_png_compression_filter == 6)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: ADAPTIVE");
else if (mng_info->write_png_compression_filter == 0 ||
mng_info->write_png_compression_filter == 1)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: NONE");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: %d",
(int) mng_info->write_png_compression_filter-1);
}
if (mng_info->write_png_compression_level != 0)
png_set_compression_level(ping,mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_filter == 6)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
(quality < 50))
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
}
else if (mng_info->write_png_compression_filter == 7 ||
mng_info->write_png_compression_filter == 10)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
else if (mng_info->write_png_compression_filter == 8)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING)
if (mng_info->write_mng)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) ||
((int) ping_color_type == PNG_COLOR_TYPE_RGBA))
ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING;
}
#endif
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
}
else if (mng_info->write_png_compression_filter == 9)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else if (mng_info->write_png_compression_filter != 0)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,
mng_info->write_png_compression_filter-1);
if (mng_info->write_png_compression_strategy != 0)
png_set_compression_strategy(ping,
mng_info->write_png_compression_strategy-1);
ping_interlace_method=image_info->interlace != NoInterlace;
if (mng_info->write_mng)
png_set_sig_bytes(ping,8);
/* Bail out if cannot meet defined png:bit-depth or png:color-type */
if (mng_info->write_png_colortype != 0)
{
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY)
if (ping_have_color != MagickFalse)
{
ping_color_type = PNG_COLOR_TYPE_RGB;
if (ping_bit_depth < 8)
ping_bit_depth=8;
}
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA)
if (ping_have_color != MagickFalse)
ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
}
if (ping_need_colortype_warning != MagickFalse ||
((mng_info->write_png_depth &&
(int) mng_info->write_png_depth != ping_bit_depth) ||
(mng_info->write_png_colortype &&
((int) mng_info->write_png_colortype-1 != ping_color_type &&
mng_info->write_png_colortype != 7 &&
!(mng_info->write_png_colortype == 5 && ping_color_type == 0)))))
{
if (logging != MagickFalse)
{
if (ping_need_colortype_warning != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image has transparency but tRNS chunk was excluded");
}
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth=%u, Computed depth=%u",
mng_info->write_png_depth,
ping_bit_depth);
}
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type=%u, Computed color type=%u",
mng_info->write_png_colortype-1,
ping_color_type);
}
}
png_warning(ping,
"Cannot write image with defined png:bit-depth or png:color-type.");
}
if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait)
{
/* Add an opaque matte channel */
image->alpha_trait = BlendPixelTrait;
(void) SetImageAlpha(image,OpaqueAlpha,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Added an opaque matte channel");
}
if (number_transparent != 0 || number_semitransparent != 0)
{
if (ping_color_type < 4)
{
ping_have_tRNS=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting ping_have_tRNS=MagickTrue.");
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG header chunks");
png_set_IHDR(ping,ping_info,ping_width,ping_height,
ping_bit_depth,ping_color_type,
ping_interlace_method,ping_compression_method,
ping_filter_method);
if (ping_color_type == 3 && ping_have_PLTE != MagickFalse)
{
png_set_PLTE(ping,ping_info,palette,number_colors);
if (logging != MagickFalse)
{
for (i=0; i< (ssize_t) number_colors; i++)
{
if (i < ping_num_trans)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue,
(int) i,
(int) ping_trans_alpha[i]);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue);
}
}
}
/* Only write the iCCP chunk if we are not writing the sRGB chunk. */
if (ping_exclude_sRGB != MagickFalse ||
(!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if ((ping_exclude_tEXt == MagickFalse ||
ping_exclude_zTXt == MagickFalse) &&
(ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse))
{
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
#ifdef PNG_WRITE_iCCP_SUPPORTED
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
ping_have_iCCP = MagickTrue;
if (ping_exclude_iCCP == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up iCCP chunk");
png_set_iCCP(ping,ping_info,(png_charp) name,0,
#if (PNG_LIBPNG_VER < 10500)
(png_charp) GetStringInfoDatum(profile),
#else
(const png_byte *) GetStringInfoDatum(profile),
#endif
(png_uint_32) GetStringInfoLength(profile));
}
else
{
/* Do not write hex-encoded ICC chunk */
name=GetNextImageProfile(image);
continue;
}
}
#endif /* WRITE_iCCP */
if (LocaleCompare(name,"exif") == 0)
{
/* Do not write hex-encoded ICC chunk; we will
write it later as an eXIf chunk */
name=GetNextImageProfile(image);
continue;
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up zTXt chunk with uuencoded %s profile",
name);
Magick_png_write_raw_profile(image_info,ping,ping_info,
(unsigned char *) name,(unsigned char *) name,
GetStringInfoDatum(profile),
(png_uint_32) GetStringInfoLength(profile));
}
name=GetNextImageProfile(image);
}
}
}
#if defined(PNG_WRITE_sRGB_SUPPORTED)
if ((mng_info->have_write_global_srgb == 0) &&
ping_have_iCCP != MagickTrue &&
(ping_have_sRGB != MagickFalse ||
png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if (ping_exclude_sRGB == MagickFalse)
{
/*
Note image rendering intent.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up sRGB chunk");
(void) png_set_sRGB(ping,ping_info,(
Magick_RenderingIntent_to_PNG_RenderingIntent(
image->rendering_intent)));
ping_have_sRGB = MagickTrue;
}
}
if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
#endif
{
if (ping_exclude_gAMA == MagickFalse &&
ping_have_iCCP == MagickFalse &&
ping_have_sRGB == MagickFalse &&
(ping_exclude_sRGB == MagickFalse ||
(image->gamma < .45 || image->gamma > .46)))
{
if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0))
{
/*
Note image gamma.
To do: check for cHRM+gAMA == sRGB, and write sRGB instead.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up gAMA chunk");
png_set_gAMA(ping,ping_info,image->gamma);
}
}
if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse)
{
if ((mng_info->have_write_global_chrm == 0) &&
(image->chromaticity.red_primary.x != 0.0))
{
/*
Note image chromaticity.
Note: if cHRM+gAMA == sRGB write sRGB instead.
*/
PrimaryInfo
bp,
gp,
rp,
wp;
wp=image->chromaticity.white_point;
rp=image->chromaticity.red_primary;
gp=image->chromaticity.green_primary;
bp=image->chromaticity.blue_primary;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up cHRM chunk");
png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y,
bp.x,bp.y);
}
}
}
if (ping_exclude_bKGD == MagickFalse)
{
if (ping_have_bKGD != MagickFalse)
{
png_set_bKGD(ping,ping_info,&ping_background);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background color = (%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" index = %d, gray=%d",
(int) ping_background.index,
(int) ping_background.gray);
}
}
}
if (ping_exclude_pHYs == MagickFalse)
{
if (ping_have_pHYs != MagickFalse)
{
png_set_pHYs(ping,ping_info,
ping_pHYs_x_resolution,
ping_pHYs_y_resolution,
ping_pHYs_unit_type);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_resolution=%lu",
(unsigned long) ping_pHYs_x_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" y_resolution=%lu",
(unsigned long) ping_pHYs_y_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" unit_type=%lu",
(unsigned long) ping_pHYs_unit_type);
}
}
}
#if defined(PNG_tIME_SUPPORTED)
if (ping_exclude_tIME == MagickFalse)
{
const char
*timestamp;
if (image->taint == MagickFalse)
{
timestamp=GetImageOption(image_info,"png:tIME");
if (timestamp == (const char *) NULL)
timestamp=GetImageProperty(image,"png:tIME",exception);
}
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reset tIME in tainted image");
timestamp=GetImageProperty(image,"date:modify",exception);
}
if (timestamp != (const char *) NULL)
write_tIME_chunk(image,ping,ping_info,timestamp,exception);
}
#endif
if (mng_info->need_blob != MagickFalse)
{
if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) ==
MagickFalse)
png_error(ping,"WriteBlob Failed");
ping_have_blob=MagickTrue;
}
png_write_info_before_PLTE(ping, ping_info);
if (ping_have_tRNS != MagickFalse && ping_color_type < 4)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Calling png_set_tRNS with num_trans=%d",ping_num_trans);
}
if (ping_color_type == 3)
(void) png_set_tRNS(ping, ping_info,
ping_trans_alpha,
ping_num_trans,
NULL);
else
{
(void) png_set_tRNS(ping, ping_info,
NULL,
0,
&ping_trans_color);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tRNS color =(%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
png_write_info(ping,ping_info);
/* write orNT if image->orientation is defined */
if (image->orientation != UndefinedOrientation)
{
unsigned char
chunk[6];
(void) WriteBlobMSBULong(image,1L); /* data length=1 */
PNGType(chunk,mng_orNT);
LogPNGChunk(logging,mng_orNT,1L);
/* PNG uses Exif orientation values */
chunk[4]=Magick_Orientation_to_Exif_Orientation(image->orientation);
(void) WriteBlob(image,5,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,5));
}
ping_wrote_caNv = MagickFalse;
/* write caNv chunk */
if (ping_exclude_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
image->page.x != 0 || image->page.y != 0)
{
unsigned char
chunk[20];
(void) WriteBlobMSBULong(image,16L); /* data length=8 */
PNGType(chunk,mng_caNv);
LogPNGChunk(logging,mng_caNv,16L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
PNGsLong(chunk+12,(png_int_32) image->page.x);
PNGsLong(chunk+16,(png_int_32) image->page.y);
(void) WriteBlob(image,20,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,20));
ping_wrote_caNv = MagickTrue;
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if (image->page.x || image->page.y)
{
png_set_oFFs(ping,ping_info,(png_int_32) image->page.x,
(png_int_32) image->page.y, 0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up oFFs chunk with x=%d, y=%d, units=0",
(int) image->page.x, (int) image->page.y);
}
}
#endif
#if (PNG_LIBPNG_VER == 10206)
/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */
#define PNG_HAVE_IDAT 0x04
ping->mode |= PNG_HAVE_IDAT;
#undef PNG_HAVE_IDAT
#endif
png_set_packing(ping);
/*
Allocate memory.
*/
rowbytes=image->columns;
if (image_depth > 8)
rowbytes*=2;
switch (ping_color_type)
{
case PNG_COLOR_TYPE_RGB:
rowbytes*=3;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
rowbytes*=2;
break;
case PNG_COLOR_TYPE_RGBA:
rowbytes*=4;
break;
default:
break;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocating %.20g bytes of memory for pixels",(double) rowbytes);
}
pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Allocation of memory for pixels failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
(void) memset(ping_pixels,0,rowbytes*sizeof(*ping_pixels));
/*
Initialize image scanlines.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Memory allocation for quantum_info failed");
quantum_info->format=UndefinedQuantumFormat;
SetQuantumDepth(image,quantum_info,image_depth);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
num_passes=png_set_interlace_handling(ping);
if ((mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE) ||
((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) &&
(mng_info->IsPalette ||
(image_info->type == BilevelType)) &&
image_matte == MagickFalse &&
ping_have_non_bw == MagickFalse))
{
/* Palette, Bilevel, or Opaque Monochrome */
QuantumType
quantum_type;
register const Quantum
*p;
quantum_type=RedQuantum;
if (mng_info->IsPalette)
{
quantum_type=GrayQuantum;
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE)
quantum_type=IndexQuantum;
}
SetQuantumDepth(image,quantum_info,8);
for (pass=0; pass < num_passes; pass++)
{
/*
Convert PseudoClass image to a PNG monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (0)");
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,quantum_type,ping_pixels,exception);
if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE)
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ?
255 : 0);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (1)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else /* Not Palette, Bilevel, or Opaque Monochrome */
{
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) && (image_matte != MagickFalse ||
(ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) &&
(mng_info->IsPalette) && ping_have_color == MagickFalse)
{
register const Quantum
*p;
for (pass=0; pass < num_passes; pass++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (mng_info->IsPalette)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY PNG pixels (2)");
}
else /* PNG_COLOR_TYPE_GRAY_ALPHA */
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (2)");
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,exception);
}
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (2)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
register const Quantum
*p;
for (pass=0; pass < num_passes; pass++)
{
if ((image_depth > 8) ||
mng_info->write_png24 ||
mng_info->write_png32 ||
mng_info->write_png48 ||
mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->storage_class == DirectClass)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (3)");
}
else if (image_matte != MagickFalse)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RGBAQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RGBQuantum,ping_pixels,exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (3)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
else
/* not ((image_depth > 8) ||
mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
*/
{
if ((ping_color_type != PNG_COLOR_TYPE_GRAY) &&
(ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is not GRAY or GRAY_ALPHA",pass);
SetQuantumDepth(image,quantum_info,8);
image_depth=8;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",
pass);
p=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
SetQuantumDepth(image,quantum_info,image->depth);
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (4)");
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
exception);
}
else
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,IndexQuantum,ping_pixels,exception);
if (logging != MagickFalse && y <= 2)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of non-gray pixels (4)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_pixels[0]=%d,ping_pixels[1]=%d",
(int)ping_pixels[0],(int)ping_pixels[1]);
}
}
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
}
}
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Wrote PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Width: %.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Height: %.20g",(double) ping_height);
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth: %d",mng_info->write_png_depth);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG bit-depth written: %d",ping_bit_depth);
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type: %d",mng_info->write_png_colortype-1);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color-type written: %d",ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG Interlace method: %d",ping_interlace_method);
}
/*
Generate text chunks after IDAT.
*/
if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
png_textp
text;
value=GetImageProperty(image,property,exception);
/* Don't write any "png:" or "jpeg:" properties; those are just for
* "identify" or for passing through to another JPEG
*/
if ((LocaleNCompare(property,"png:",4) != 0 &&
LocaleNCompare(property,"jpeg:",5) != 0) &&
/* Suppress density and units if we wrote a pHYs chunk */
(ping_exclude_pHYs != MagickFalse ||
LocaleCompare(property,"density") != 0 ||
LocaleCompare(property,"units") != 0) &&
/* Suppress the IM-generated Date:create and Date:modify */
(ping_exclude_date == MagickFalse ||
LocaleNCompare(property, "Date:",5) != 0))
{
if (value != (const char *) NULL)
{
#if PNG_LIBPNG_VER >= 10400
text=(png_textp) png_malloc(ping,
(png_alloc_size_t) sizeof(png_text));
#else
text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));
#endif
text[0].key=(char *) property;
text[0].text=(char *) value;
text[0].text_length=strlen(value);
if (ping_exclude_tEXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_zTXt;
else if (ping_exclude_zTXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_NONE;
else
{
text[0].compression=image_info->compression == NoCompression ||
(image_info->compression == UndefinedCompression &&
text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE :
PNG_TEXT_COMPRESSION_zTXt ;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up text chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" keyword: '%s'",text[0].key);
}
png_set_text(ping,ping_info,text,1);
png_free(ping,text);
}
}
property=GetNextImageProperty(image);
}
}
/* write eXIf profile */
if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse)
{
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (char *) NULL; )
{
if (LocaleCompare(name,"exif") == 0)
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
png_uint_32
length;
unsigned char
chunk[4],
*data;
StringInfo
*ping_profile;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Have eXIf profile");
ping_profile=CloneStringInfo(profile);
data=GetStringInfoDatum(ping_profile),
length=(png_uint_32) GetStringInfoLength(ping_profile);
PNGType(chunk,mng_eXIf);
if (length < 7)
{
ping_profile=DestroyStringInfo(ping_profile);
break; /* otherwise crashes */
}
if (*data == 'E' && *(data+1) == 'x' && *(data+2) == 'i' &&
*(data+3) == 'f' && *(data+4) == '\0' && *(data+5) == '\0')
{
/* skip the "Exif\0\0" JFIF Exif Header ID */
length -= 6;
data += 6;
}
LogPNGChunk(logging,chunk,length);
(void) WriteBlobMSBULong(image,length);
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,data);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4), data,
(uInt) length));
ping_profile=DestroyStringInfo(ping_profile);
break;
}
}
name=GetNextImageProfile(image);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG end info");
png_write_end(ping,ping_info);
if (mng_info->need_fram && (int) image->dispose == BackgroundDispose)
{
if (mng_info->page.x || mng_info->page.y ||
(ping_width != mng_info->page.width) ||
(ping_height != mng_info->page.height))
{
unsigned char
chunk[32];
/*
Write FRAM 4 with clipping boundaries followed by FRAM 1.
*/
(void) WriteBlobMSBULong(image,27L); /* data length=27 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,27L);
chunk[4]=4;
chunk[5]=0; /* frame name separator (no name) */
chunk[6]=1; /* flag for changing delay, for next frame only */
chunk[7]=0; /* flag for changing frame timeout */
chunk[8]=1; /* flag for changing frame clipping for next frame */
chunk[9]=0; /* flag for changing frame sync_id */
PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */
chunk[14]=0; /* clipping boundaries delta type */
PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */
PNGLong(chunk+19,
(png_uint_32) (mng_info->page.x + ping_width));
PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */
PNGLong(chunk+27,
(png_uint_32) (mng_info->page.y + ping_height));
(void) WriteBlob(image,31,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,31));
mng_info->old_framing_mode=4;
mng_info->framing_mode=1;
}
else
mng_info->framing_mode=3;
}
if (mng_info->write_mng && !mng_info->need_fram &&
((int) image->dispose == 3))
png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC");
/*
Free PNG resources.
*/
png_destroy_write_struct(&ping,&ping_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (ping_have_blob != MagickFalse)
(void) CloseBlob(image);
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
/* Store bit depth actually written */
s[0]=(char) ping_bit_depth;
s[1]='\0';
(void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block. Revert to
* Throwing an Exception when an error occurs.
*/
return(MagickTrue);
/* End write one PNG image */
} | 1 | CVE-2020-25664 | 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). | 83 |
qemu | 1e7aed70144b4673fc26e73062064b6724795e5f | static bool virtio_device_endian_needed(void *opaque)
{
VirtIODevice *vdev = opaque;
assert(vdev->device_endian != VIRTIO_DEVICE_ENDIAN_UNKNOWN);
if (!virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
return vdev->device_endian != virtio_default_endian();
}
/* Devices conforming to VIRTIO 1.0 or later are always LE. */
return vdev->device_endian != VIRTIO_DEVICE_ENDIAN_LITTLE;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,097 |
linux | 3c0c5cfdcd4d69ffc4b9c0907cec99039f30a50a | static int pvc_getname(struct socket *sock, struct sockaddr *sockaddr,
int *sockaddr_len, int peer)
{
struct sockaddr_atmpvc *addr;
struct atm_vcc *vcc = ATM_SD(sock);
if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags))
return -ENOTCONN;
*sockaddr_len = sizeof(struct sockaddr_atmpvc);
addr = (struct sockaddr_atmpvc *)sockaddr;
addr->sap_family = AF_ATMPVC;
addr->sap_addr.itf = vcc->dev->number;
addr->sap_addr.vpi = vcc->vpi;
addr->sap_addr.vci = vcc->vci;
return 0;
}
| 1 | CVE-2012-6546 | 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. | 6,256 |
clamav-devel | dfc00cd3301a42b571454b51a6102eecf58407bc | int wwunpack(uint8_t *exe, uint32_t exesz, uint8_t *wwsect, struct cli_exe_section *sects, uint16_t scount, uint32_t pe, int desc) {
uint8_t *structs = wwsect + 0x2a1, *compd, *ccur, *unpd, *ucur, bc;
uint32_t src, srcend, szd, bt, bits;
int error=0, i;
cli_dbgmsg("in wwunpack\n");
while (1) {
if (!CLI_ISCONTAINED(wwsect, sects[scount].rsz, structs, 17)) {
cli_dbgmsg("WWPack: Array of structs out of section\n");
break;
}
src = sects[scount].rva - cli_readint32(structs); /* src delta / dst delta - not used / dwords / end of src */
structs+=8;
szd = cli_readint32(structs) * 4;
structs+=4;
srcend = cli_readint32(structs);
structs+=4;
unpd = ucur = exe+src+srcend+4-szd;
if (!szd || !CLI_ISCONTAINED(exe, exesz, unpd, szd)) {
cli_dbgmsg("WWPack: Compressed data out of file\n");
break;
}
cli_dbgmsg("WWP: src: %x, szd: %x, srcend: %x - %x\n", src, szd, srcend, srcend+4-szd);
if (!(compd = cli_malloc(szd))) {
cli_dbgmsg("WWPack: Unable to allocate memory for compd\n");
break;
}
memcpy(compd, unpd, szd);
memset(unpd, -1, szd); /*FIXME*/
ccur=compd;
RESEED;
while(!error) {
uint32_t backbytes, backsize;
uint8_t saved;
BIT;
if (!bits) { /* BYTE copy */
if(ccur-compd>=szd || !CLI_ISCONTAINED(exe, exesz, ucur, 1))
error=1;
else
*ucur++=*ccur++;
continue;
}
BITS(2);
if(bits==3) { /* WORD backcopy */
uint8_t shifted, subbed = 31;
BITS(2);
shifted = bits + 5;
if(bits>=2) {
shifted++;
subbed += 0x80;
}
backbytes = (1<<shifted)-subbed; /* 1h, 21h, 61h, 161h */
BITS(shifted); /* 5, 6, 8, 9 */
if(error || bits == 0x1ff) break;
backbytes+=bits;
if(!CLI_ISCONTAINED(exe, exesz, ucur, 2) || !CLI_ISCONTAINED(exe, exesz, ucur-backbytes, 2)) {
error=1;
} else {
ucur[0]=*(ucur-backbytes);
ucur[1]=*(ucur-backbytes+1);
ucur+=2;
}
continue;
}
/* BLOCK backcopy */
saved = bits; /* cmp al, 1 / pushf */
BITS(3);
if (bits<6) {
backbytes = bits;
switch(bits) {
case 4: /* 10,11 */
backbytes++;
case 3: /* 8,9 */
BIT;
backbytes+=bits;
case 0: case 1: case 2: /* 5,6,7 */
backbytes+=5;
break;
case 5: /* 12 */
backbytes=12;
break;
}
BITS(backbytes);
bits+=(1<<backbytes)-31;
} else if(bits==6) {
BITS(0x0e);
bits+=0x1fe1;
} else {
BITS(0x0f);
bits+=0x5fe1;
}
backbytes = bits;
/* popf / jb */
if (!saved) {
BIT;
if(!bits) {
BIT;
bits+=5;
} else {
BITS(3);
if(bits) {
bits+=6;
} else {
BITS(4);
if(bits) {
bits+=13;
} else {
uint8_t cnt = 4;
uint16_t shifted = 0x0d;
do {
if(cnt==7) { cnt = 0x0e; shifted = 0; break; }
shifted=((shifted+2)<<1)-1;
BIT;
cnt++;
} while(!bits);
BITS(cnt);
bits+=shifted;
}
}
}
backsize = bits;
} else {
backsize = saved+2;
}
if(!CLI_ISCONTAINED(exe, exesz, ucur, backsize) || !CLI_ISCONTAINED(exe, exesz, ucur-backbytes, backsize)) error=1;
else while(backsize--) {
*ucur=*(ucur-backbytes);
ucur++;
}
}
free(compd);
if(error) {
cli_dbgmsg("WWPack: decompression error\n");
break;
}
if (error || !*structs++) break;
}
if(!error) {
if (pe+6 > exesz || pe+7 > exesz || pe+0x28 > exesz ||
pe+0x50 > exesz || pe+0x14 > exesz)
return CL_EFORMAT;
exe[pe+6]=(uint8_t)scount;
exe[pe+7]=(uint8_t)(scount>>8);
cli_writeint32(&exe[pe+0x28], cli_readint32(wwsect+0x295)+sects[scount].rva+0x299);
cli_writeint32(&exe[pe+0x50], cli_readint32(&exe[pe+0x50])-sects[scount].vsz);
structs = &exe[(0xffff&cli_readint32(&exe[pe+0x14]))+pe+0x18];
for(i=0 ; i<scount ; i++) {
if (!CLI_ISCONTAINED(exe, exesz, structs, 0x28)) {
cli_dbgmsg("WWPack: structs pointer out of bounds\n");
return CL_EFORMAT;
}
cli_writeint32(structs+8, sects[i].vsz);
cli_writeint32(structs+12, sects[i].rva);
cli_writeint32(structs+16, sects[i].vsz);
cli_writeint32(structs+20, sects[i].rva);
structs+=0x28;
}
if (!CLI_ISCONTAINED(exe, exesz, structs, 0x28)) {
cli_dbgmsg("WWPack: structs pointer out of bounds\n");
return CL_EFORMAT;
}
memset(structs, 0, 0x28);
error = (uint32_t)cli_writen(desc, exe, exesz)!=exesz;
}
return error;
} | 1 | CVE-2017-6420 | CWE-416 | Use After Free | The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
Phase: Architecture and Design
Strategy: Language Selection
Choose a language that provides automatic memory management.
Phase: Implementation
Strategy: Attack Surface Reduction
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.
Effectiveness: Defense in Depth
Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution. | 6,495 |
FreeRDP | 7b1d4b49391b4512402840431757703a96946820 | static INLINE UINT32 ExtractRunLength(UINT32 code, const BYTE* pbOrderHdr, UINT32* advance)
{
UINT32 runLength;
UINT32 ladvance;
ladvance = 1;
runLength = 0;
switch (code)
{
case REGULAR_FGBG_IMAGE:
runLength = (*pbOrderHdr) & g_MaskRegularRunLength;
if (runLength == 0)
{
runLength = (*(pbOrderHdr + 1)) + 1;
ladvance += 1;
}
else
{
runLength = runLength * 8;
}
break;
case LITE_SET_FG_FGBG_IMAGE:
runLength = (*pbOrderHdr) & g_MaskLiteRunLength;
if (runLength == 0)
{
runLength = (*(pbOrderHdr + 1)) + 1;
ladvance += 1;
}
else
{
runLength = runLength * 8;
}
break;
case REGULAR_BG_RUN:
case REGULAR_FG_RUN:
case REGULAR_COLOR_RUN:
case REGULAR_COLOR_IMAGE:
runLength = (*pbOrderHdr) & g_MaskRegularRunLength;
if (runLength == 0)
{
/* An extended (MEGA) run. */
runLength = (*(pbOrderHdr + 1)) + 32;
ladvance += 1;
}
break;
case LITE_SET_FG_FG_RUN:
case LITE_DITHERED_RUN:
runLength = (*pbOrderHdr) & g_MaskLiteRunLength;
if (runLength == 0)
{
/* An extended (MEGA) run. */
runLength = (*(pbOrderHdr + 1)) + 16;
ladvance += 1;
}
break;
case MEGA_MEGA_BG_RUN:
case MEGA_MEGA_FG_RUN:
case MEGA_MEGA_SET_FG_RUN:
case MEGA_MEGA_DITHERED_RUN:
case MEGA_MEGA_COLOR_RUN:
case MEGA_MEGA_FGBG_IMAGE:
case MEGA_MEGA_SET_FGBG_IMAGE:
case MEGA_MEGA_COLOR_IMAGE:
runLength = ((UINT16)pbOrderHdr[1]) | ((UINT16)(pbOrderHdr[2] << 8));
ladvance += 2;
break;
}
*advance = ladvance;
return runLength;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,337 |
jasper | 8f62b4761711d036fd8964df256b938c809b7fca | jas_image_t *bmp_decode(jas_stream_t *in, char *optstr)
{
jas_image_t *image;
bmp_hdr_t hdr;
bmp_info_t *info;
uint_fast16_t cmptno;
jas_image_cmptparm_t cmptparms[3];
jas_image_cmptparm_t *cmptparm;
uint_fast16_t numcmpts;
long n;
if (optstr) {
jas_eprintf("warning: ignoring BMP decoder options\n");
}
jas_eprintf(
"THE BMP FORMAT IS NOT FULLY SUPPORTED!\n"
"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n"
"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n"
"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n"
);
/* Read the bitmap header. */
if (bmp_gethdr(in, &hdr)) {
jas_eprintf("cannot get header\n");
return 0;
}
/* Read the bitmap information. */
if (!(info = bmp_getinfo(in))) {
jas_eprintf("cannot get info\n");
return 0;
}
/* Ensure that we support this type of BMP file. */
if (!bmp_issupported(&hdr, info)) {
jas_eprintf("error: unsupported BMP encoding\n");
bmp_info_destroy(info);
return 0;
}
/* Skip over any useless data between the end of the palette
and start of the bitmap data. */
if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) {
jas_eprintf("error: possibly bad bitmap offset?\n");
return 0;
}
if (n > 0) {
jas_eprintf("skipping unknown data in BMP file\n");
if (bmp_gobble(in, n)) {
bmp_info_destroy(info);
return 0;
}
}
/* Get the number of components. */
numcmpts = bmp_numcmpts(info);
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
cmptparm->tlx = 0;
cmptparm->tly = 0;
cmptparm->hstep = 1;
cmptparm->vstep = 1;
cmptparm->width = info->width;
cmptparm->height = info->height;
cmptparm->prec = 8;
cmptparm->sgnd = false;
}
/* Create image object. */
if (!(image = jas_image_create(numcmpts, cmptparms,
JAS_CLRSPC_UNKNOWN))) {
bmp_info_destroy(info);
return 0;
}
if (numcmpts == 3) {
jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
jas_image_setcmpttype(image, 1,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
jas_image_setcmpttype(image, 2,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
} else {
jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
}
/* Read the bitmap data. */
if (bmp_getdata(in, info, image)) {
bmp_info_destroy(info);
jas_image_destroy(image);
return 0;
}
bmp_info_destroy(info);
return image;
}
| 1 | CVE-2016-8690 | 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. | 3,229 |
tensorflow | 00302787b788c5ff04cb6f62aed5a74d936e86c0 | const TfLiteTensor* GetOptionalInputTensor(const TfLiteContext* context,
const TfLiteNode* node, int index) {
const bool use_tensor = index < node->inputs->size &&
node->inputs->data[index] != kTfLiteOptionalTensor;
if (use_tensor) {
return GetMutableInput(context, node, index);
}
return nullptr;
} | 1 | CVE-2020-15211 | 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,593 |
Chrome | 744c2a2d90c3c9a33c818e1ea4b7ccb5010663a0 | virtual void TearDown() {
content::GetContentClient()->set_browser(old_browser_client_);
}
| 1 | CVE-2011-3084 | 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 | 7,727 |
php | bf58162ddf970f63502837f366930e44d6a992cf | PHP_METHOD(Phar, webPhar)
{
zval *mimeoverride = NULL, *rewrite = NULL;
char *alias = NULL, *error, *index_php = NULL, *f404 = NULL, *ru = NULL;
int alias_len = 0, ret, f404_len = 0, free_pathinfo = 0, ru_len = 0;
char *fname, *path_info, *mime_type = NULL, *entry, *pt;
const char *basename;
int fname_len, entry_len, code, index_php_len = 0, not_cgi;
phar_archive_data *phar = NULL;
phar_entry_info *info = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!s!saz", &alias, &alias_len, &index_php, &index_php_len, &f404, &f404_len, &mimeoverride, &rewrite) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
fname = (char*)zend_get_executed_filename(TSRMLS_C);
fname_len = strlen(fname);
if (phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) != SUCCESS) {
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
return;
}
/* retrieve requested file within phar */
if (!(SG(request_info).request_method && SG(request_info).request_uri && (!strcmp(SG(request_info).request_method, "GET") || !strcmp(SG(request_info).request_method, "POST")))) {
return;
}
#ifdef PHP_WIN32
fname = estrndup(fname, fname_len);
phar_unixify_path_separators(fname, fname_len);
#endif
basename = zend_memrchr(fname, '/', fname_len);
if (!basename) {
basename = fname;
} else {
++basename;
}
if ((strlen(sapi_module.name) == sizeof("cgi-fcgi")-1 && !strncmp(sapi_module.name, "cgi-fcgi", sizeof("cgi-fcgi")-1))
|| (strlen(sapi_module.name) == sizeof("fpm-fcgi")-1 && !strncmp(sapi_module.name, "fpm-fcgi", sizeof("fpm-fcgi")-1))
|| (strlen(sapi_module.name) == sizeof("cgi")-1 && !strncmp(sapi_module.name, "cgi", sizeof("cgi")-1))) {
if (PG(http_globals)[TRACK_VARS_SERVER]) {
HashTable *_server = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]);
zval **z_script_name, **z_path_info;
if (SUCCESS != zend_hash_find(_server, "SCRIPT_NAME", sizeof("SCRIPT_NAME"), (void**)&z_script_name) ||
IS_STRING != Z_TYPE_PP(z_script_name) ||
!strstr(Z_STRVAL_PP(z_script_name), basename)) {
return;
}
if (SUCCESS == zend_hash_find(_server, "PATH_INFO", sizeof("PATH_INFO"), (void**)&z_path_info) &&
IS_STRING == Z_TYPE_PP(z_path_info)) {
entry_len = Z_STRLEN_PP(z_path_info);
entry = estrndup(Z_STRVAL_PP(z_path_info), entry_len);
path_info = emalloc(Z_STRLEN_PP(z_script_name) + entry_len + 1);
memcpy(path_info, Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name));
memcpy(path_info + Z_STRLEN_PP(z_script_name), entry, entry_len + 1);
free_pathinfo = 1;
} else {
entry_len = 0;
entry = estrndup("", 0);
path_info = Z_STRVAL_PP(z_script_name);
}
pt = estrndup(Z_STRVAL_PP(z_script_name), Z_STRLEN_PP(z_script_name));
} else {
char *testit;
testit = sapi_getenv("SCRIPT_NAME", sizeof("SCRIPT_NAME")-1 TSRMLS_CC);
if (!(pt = strstr(testit, basename))) {
efree(testit);
return;
}
path_info = sapi_getenv("PATH_INFO", sizeof("PATH_INFO")-1 TSRMLS_CC);
if (path_info) {
entry = path_info;
entry_len = strlen(entry);
spprintf(&path_info, 0, "%s%s", testit, path_info);
free_pathinfo = 1;
} else {
path_info = testit;
free_pathinfo = 1;
entry = estrndup("", 0);
entry_len = 0;
}
pt = estrndup(testit, (pt - testit) + (fname_len - (basename - fname)));
}
not_cgi = 0;
} else {
path_info = SG(request_info).request_uri;
if (!(pt = strstr(path_info, basename))) {
/* this can happen with rewrite rules - and we have no idea what to do then, so return */
return;
}
entry_len = strlen(path_info);
entry_len -= (pt - path_info) + (fname_len - (basename - fname));
entry = estrndup(pt + (fname_len - (basename - fname)), entry_len);
pt = estrndup(path_info, (pt - path_info) + (fname_len - (basename - fname)));
not_cgi = 1;
}
if (rewrite) {
zend_fcall_info fci;
zend_fcall_info_cache fcc;
zval *params, *retval_ptr, **zp[1];
MAKE_STD_ZVAL(params);
ZVAL_STRINGL(params, entry, entry_len, 1);
zp[0] = ¶ms;
#if PHP_VERSION_ID < 50300
if (FAILURE == zend_fcall_info_init(rewrite, &fci, &fcc TSRMLS_CC)) {
#else
if (FAILURE == zend_fcall_info_init(rewrite, 0, &fci, &fcc, NULL, NULL TSRMLS_CC)) {
#endif
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: invalid rewrite callback");
if (free_pathinfo) {
efree(path_info);
}
return;
}
fci.param_count = 1;
fci.params = zp;
#if PHP_VERSION_ID < 50300
++(params->refcount);
#else
Z_ADDREF_P(params);
#endif
fci.retval_ptr_ptr = &retval_ptr;
if (FAILURE == zend_call_function(&fci, &fcc TSRMLS_CC)) {
if (!EG(exception)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: failed to call rewrite callback");
}
if (free_pathinfo) {
efree(path_info);
}
return;
}
if (!fci.retval_ptr_ptr || !retval_ptr) {
if (free_pathinfo) {
efree(path_info);
}
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false");
return;
}
switch (Z_TYPE_P(retval_ptr)) {
#if PHP_VERSION_ID >= 60000
case IS_UNICODE:
zval_unicode_to_string(retval_ptr TSRMLS_CC);
/* break intentionally omitted */
#endif
case IS_STRING:
efree(entry);
if (fci.retval_ptr_ptr != &retval_ptr) {
entry = estrndup(Z_STRVAL_PP(fci.retval_ptr_ptr), Z_STRLEN_PP(fci.retval_ptr_ptr));
entry_len = Z_STRLEN_PP(fci.retval_ptr_ptr);
} else {
entry = Z_STRVAL_P(retval_ptr);
entry_len = Z_STRLEN_P(retval_ptr);
}
break;
case IS_BOOL:
phar_do_403(entry, entry_len TSRMLS_CC);
if (free_pathinfo) {
efree(path_info);
}
zend_bailout();
return;
default:
efree(retval_ptr);
if (free_pathinfo) {
efree(path_info);
}
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar error: rewrite callback must return a string or false");
return;
}
}
if (entry_len) {
phar_postprocess_ru_web(fname, fname_len, &entry, &entry_len, &ru, &ru_len TSRMLS_CC);
}
if (!entry_len || (entry_len == 1 && entry[0] == '/')) {
efree(entry);
/* direct request */
if (index_php_len) {
entry = index_php;
entry_len = index_php_len;
if (entry[0] != '/') {
spprintf(&entry, 0, "/%s", index_php);
++entry_len;
}
} else {
/* assume "index.php" is starting point */
entry = estrndup("/index.php", sizeof("/index.php"));
entry_len = sizeof("/index.php")-1;
}
if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) ||
(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) {
phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC);
if (free_pathinfo) {
efree(path_info);
}
zend_bailout();
} else {
char *tmp = NULL, sa = '\0';
sapi_header_line ctr = {0};
ctr.response_code = 301;
ctr.line_len = sizeof("HTTP/1.1 301 Moved Permanently")-1;
ctr.line = "HTTP/1.1 301 Moved Permanently";
sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
if (not_cgi) {
tmp = strstr(path_info, basename) + fname_len;
sa = *tmp;
*tmp = '\0';
}
ctr.response_code = 0;
if (path_info[strlen(path_info)-1] == '/') {
ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry + 1);
} else {
ctr.line_len = spprintf(&(ctr.line), 4096, "Location: %s%s", path_info, entry);
}
if (not_cgi) {
*tmp = sa;
}
if (free_pathinfo) {
efree(path_info);
}
sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC);
sapi_send_headers(TSRMLS_C);
efree(ctr.line);
zend_bailout();
}
}
if (FAILURE == phar_get_archive(&phar, fname, fname_len, NULL, 0, NULL TSRMLS_CC) ||
(info = phar_get_entry_info(phar, entry, entry_len, NULL, 0 TSRMLS_CC)) == NULL) {
phar_do_404(phar, fname, fname_len, f404, f404_len, entry, entry_len TSRMLS_CC);
#ifdef PHP_WIN32
efree(fname);
#endif
zend_bailout();
}
if (mimeoverride && zend_hash_num_elements(Z_ARRVAL_P(mimeoverride))) {
const char *ext = zend_memrchr(entry, '.', entry_len);
zval **val;
if (ext) {
++ext;
if (SUCCESS == zend_hash_find(Z_ARRVAL_P(mimeoverride), ext, strlen(ext)+1, (void **) &val)) {
switch (Z_TYPE_PP(val)) {
case IS_LONG:
if (Z_LVAL_PP(val) == PHAR_MIME_PHP || Z_LVAL_PP(val) == PHAR_MIME_PHPS) {
mime_type = "";
code = Z_LVAL_PP(val);
} else {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used, only Phar::PHP, Phar::PHPS and a mime type string are allowed");
#ifdef PHP_WIN32
efree(fname);
#endif
RETURN_FALSE;
}
break;
case IS_STRING:
mime_type = Z_STRVAL_PP(val);
code = PHAR_MIME_OTHER;
break;
default:
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown mime type specifier used (not a string or int), only Phar::PHP, Phar::PHPS and a mime type string are allowed");
#ifdef PHP_WIN32
efree(fname);
#endif
RETURN_FALSE;
}
}
}
}
if (!mime_type) {
code = phar_file_type(&PHAR_G(mime_types), entry, &mime_type TSRMLS_CC);
}
ret = phar_file_action(phar, info, mime_type, code, entry, entry_len, fname, pt, ru, ru_len TSRMLS_CC);
}
/* }}} */
/* {{{ proto void Phar::mungServer(array munglist)
* Defines a list of up to 4 $_SERVER variables that should be modified for execution
* to mask the presence of the phar archive. This should be used in conjunction with
* Phar::webPhar(), and has no effect otherwise
* SCRIPT_NAME, PHP_SELF, REQUEST_URI and SCRIPT_FILENAME
*/
PHP_METHOD(Phar, mungServer)
{
zval *mungvalues;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &mungvalues) == FAILURE) {
return;
}
if (!zend_hash_num_elements(Z_ARRVAL_P(mungvalues))) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "No values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
if (zend_hash_num_elements(Z_ARRVAL_P(mungvalues)) > 4) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Too many values passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
phar_request_initialize(TSRMLS_C);
for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(mungvalues)); SUCCESS == zend_hash_has_more_elements(Z_ARRVAL_P(mungvalues)); zend_hash_move_forward(Z_ARRVAL_P(mungvalues))) {
zval **data = NULL;
if (SUCCESS != zend_hash_get_current_data(Z_ARRVAL_P(mungvalues), (void **) &data)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to retrieve array value in Phar::mungServer()");
return;
}
if (Z_TYPE_PP(data) != IS_STRING) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Non-string value passed to Phar::mungServer(), expecting an array of any of these strings: PHP_SELF, REQUEST_URI, SCRIPT_FILENAME, SCRIPT_NAME");
return;
}
if (Z_STRLEN_PP(data) == sizeof("PHP_SELF")-1 && !strncmp(Z_STRVAL_PP(data), "PHP_SELF", sizeof("PHP_SELF")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_PHP_SELF;
}
if (Z_STRLEN_PP(data) == sizeof("REQUEST_URI")-1) {
if (!strncmp(Z_STRVAL_PP(data), "REQUEST_URI", sizeof("REQUEST_URI")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_REQUEST_URI;
}
if (!strncmp(Z_STRVAL_PP(data), "SCRIPT_NAME", sizeof("SCRIPT_NAME")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_NAME;
}
}
if (Z_STRLEN_PP(data) == sizeof("SCRIPT_FILENAME")-1 && !strncmp(Z_STRVAL_PP(data), "SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME")-1)) {
PHAR_GLOBALS->phar_SERVER_mung_list |= PHAR_MUNG_SCRIPT_FILENAME;
}
}
}
/* }}} */
/* {{{ proto void Phar::interceptFileFuncs()
* instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
* and return stat on files within the phar for relative paths
*
* Once called, this cannot be reversed, and continue until the end of the request.
*
* This allows legacy scripts to be pharred unmodified
*/
PHP_METHOD(Phar, interceptFileFuncs)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
phar_intercept_functions(TSRMLS_C);
}
/* }}} */
/* {{{ proto array Phar::createDefaultStub([string indexfile[, string webindexfile]])
* Return a stub that can be used to run a phar-based archive without the phar extension
* indexfile is the CLI startup filename, which defaults to "index.php", webindexfile
* is the web startup filename, and also defaults to "index.php"
*/
PHP_METHOD(Phar, createDefaultStub)
{
char *index = NULL, *webindex = NULL, *stub, *error;
int index_len = 0, webindex_len = 0;
size_t stub_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ss", &index, &index_len, &webindex, &webindex_len) == FAILURE) {
return;
}
stub = phar_create_default_stub(index, webindex, &stub_len, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
return;
}
RETURN_STRINGL(stub, stub_len, 0);
}
/* }}} */
/* {{{ proto mixed Phar::mapPhar([string alias, [int dataoffset]])
* Reads the currently executed file (a phar) and registers its manifest */
PHP_METHOD(Phar, mapPhar)
{
char *alias = NULL, *error;
int alias_len = 0;
long dataoffset = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!l", &alias, &alias_len, &dataoffset) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
RETVAL_BOOL(phar_open_executed_filename(alias, alias_len, &error TSRMLS_CC) == SUCCESS);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} /* }}} */
/* {{{ proto mixed Phar::loadPhar(string filename [, string alias])
* Loads any phar archive with an alias */
PHP_METHOD(Phar, loadPhar)
{
char *fname, *alias = NULL, *error;
int fname_len, alias_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error TSRMLS_CC) == SUCCESS);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} /* }}} */
/* {{{ proto string Phar::apiVersion()
* Returns the api version */
PHP_METHOD(Phar, apiVersion)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_STRINGL(PHP_PHAR_API_VERSION, sizeof(PHP_PHAR_API_VERSION)-1, 1);
}
/* }}}*/
/* {{{ proto bool Phar::canCompress([int method])
* Returns whether phar extension supports compression using zlib/bzip2 */
PHP_METHOD(Phar, canCompress)
{
long method = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &method) == FAILURE) {
return;
}
phar_request_initialize(TSRMLS_C);
switch (method) {
case PHAR_ENT_COMPRESSED_GZ:
if (PHAR_G(has_zlib)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
case PHAR_ENT_COMPRESSED_BZ2:
if (PHAR_G(has_bz2)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
default:
if (PHAR_G(has_zlib) || PHAR_G(has_bz2)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
}
/* }}} */
/* {{{ proto bool Phar::canWrite()
* Returns whether phar extension supports writing and creating phars */
PHP_METHOD(Phar, canWrite)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(!PHAR_G(readonly));
}
/* }}} */
/* {{{ proto bool Phar::isValidPharFilename(string filename[, bool executable = true])
* Returns whether the given filename is a valid phar filename */
PHP_METHOD(Phar, isValidPharFilename)
{
char *fname;
const char *ext_str;
int fname_len, ext_len, is_executable;
zend_bool executable = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|b", &fname, &fname_len, &executable) == FAILURE) {
return;
}
is_executable = executable;
RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1 TSRMLS_CC) == SUCCESS);
}
/* }}} */
#if HAVE_SPL
/**
* from spl_directory
*/
static void phar_spl_foreign_dtor(spl_filesystem_object *object TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar = (phar_archive_data *) object->oth;
if (!phar->is_persistent) {
phar_archive_delref(phar TSRMLS_CC);
}
object->oth = NULL;
}
/* }}} */
/**
* from spl_directory
*/
static void phar_spl_foreign_clone(spl_filesystem_object *src, spl_filesystem_object *dst TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar_data = (phar_archive_data *) dst->oth;
if (!phar_data->is_persistent) {
++(phar_data->refcount);
}
}
/* }}} */
static spl_other_handler phar_spl_foreign_handler = {
phar_spl_foreign_dtor,
phar_spl_foreign_clone
};
#endif /* HAVE_SPL */
/* {{{ proto void Phar::__construct(string fname [, int flags [, string alias]])
* Construct a Phar archive object
*
* proto void PharData::__construct(string fname [[, int flags [, string alias]], int file format = Phar::TAR])
* Construct a PharData archive object
*
* This function is used as the constructor for both the Phar and PharData
* classes, hence the two prototypes above.
*/
PHP_METHOD(Phar, __construct)
{
#if !HAVE_SPL
zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Cannot instantiate Phar object without SPL extension");
#else
char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname;
int fname_len, alias_len = 0, arch_len, entry_len, is_data;
#if PHP_VERSION_ID < 50300
long flags = 0;
#else
long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS;
#endif
long format = 0;
phar_archive_object *phar_obj;
phar_archive_data *phar_data;
zval *zobj = getThis(), arg1, arg2;
phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC);
if (is_data) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) {
return;
}
} else {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) {
return;
}
}
if (phar_obj->arc.archive) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Cannot call constructor twice");
return;
}
save_fname = fname;
if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) {
/* use arch (the basename for the archive) for fname instead of fname */
/* this allows support for RecursiveDirectoryIterator of subdirectories */
#ifdef PHP_WIN32
phar_unixify_path_separators(arch, arch_len);
#endif
fname = arch;
fname_len = arch_len;
#ifdef PHP_WIN32
} else {
arch = estrndup(fname, fname_len);
arch_len = fname_len;
fname = arch;
phar_unixify_path_separators(arch, arch_len);
#endif
}
if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) {
if (fname == arch && fname != save_fname) {
efree(arch);
fname = save_fname;
}
if (entry) {
efree(entry);
}
if (error) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"%s", error);
efree(error);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar creation or opening failed");
}
return;
}
if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) {
phar_data->is_zip = 1;
phar_data->is_tar = 0;
}
if (fname == arch) {
efree(arch);
fname = save_fname;
}
if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) {
if (is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"PharData class can only be used for non-executable tar and zip archives");
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Phar class can only be used for executable tar and zip archives");
}
efree(entry);
return;
}
is_data = phar_data->is_data;
if (!phar_data->is_persistent) {
++(phar_data->refcount);
}
phar_obj->arc.archive = phar_data;
phar_obj->spl.oth_handler = &phar_spl_foreign_handler;
if (entry) {
fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry);
efree(entry);
} else {
fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname);
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, fname, fname_len, 0);
INIT_PZVAL(&arg2);
ZVAL_LONG(&arg2, flags);
zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj),
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2);
if (!phar_data->is_persistent) {
phar_obj->arc.archive->is_data = is_data;
} else if (!EG(exception)) {
/* register this guy so we can modify if necessary */
zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL);
}
phar_obj->spl.info_class = phar_ce_entry;
efree(fname);
#endif /* HAVE_SPL */
}
/* }}} */
/* {{{ proto array Phar::getSupportedSignatures()
* Return array of supported signature types
*/
PHP_METHOD(Phar, getSupportedSignatures)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
add_next_index_stringl(return_value, "MD5", 3, 1);
add_next_index_stringl(return_value, "SHA-1", 5, 1);
#ifdef PHAR_HASH_OK
add_next_index_stringl(return_value, "SHA-256", 7, 1);
add_next_index_stringl(return_value, "SHA-512", 7, 1);
#endif
#if PHAR_HAVE_OPENSSL
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
#else
if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) {
add_next_index_stringl(return_value, "OpenSSL", 7, 1);
}
#endif
}
/* }}} */
/* {{{ proto array Phar::getSupportedCompression()
* Return array of supported comparession algorithms
*/
PHP_METHOD(Phar, getSupportedCompression)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
phar_request_initialize(TSRMLS_C);
if (PHAR_G(has_zlib)) {
add_next_index_stringl(return_value, "GZ", 2, 1);
}
if (PHAR_G(has_bz2)) {
add_next_index_stringl(return_value, "BZIP2", 5, 1);
}
}
/* }}} */
/* {{{ proto array Phar::unlinkArchive(string archive)
* Completely remove a phar archive from memory and disk
*/
PHP_METHOD(Phar, unlinkArchive)
{
char *fname, *error, *zname, *arch, *entry;
int fname_len, zname_len, arch_len, entry_len;
phar_archive_data *phar;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &fname, &fname_len) == FAILURE) {
RETURN_FALSE;
}
if (!fname_len) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"\"");
return;
}
if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error TSRMLS_CC)) {
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\": %s", fname, error);
efree(error);
} else {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown phar archive \"%s\"", fname);
}
return;
}
zname = (char*)zend_get_executed_filename(TSRMLS_C);
zname_len = strlen(zname);
if (zname_len > 7 && !memcmp(zname, "phar://", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0 TSRMLS_CC)) {
if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" cannot be unlinked from within itself", fname);
efree(arch);
efree(entry);
return;
}
efree(arch);
efree(entry);
}
if (phar->is_persistent) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" is in phar.cache_list, cannot unlinkArchive()", fname);
return;
}
if (phar->refcount) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar archive \"%s\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()", fname);
return;
}
fname = estrndup(phar->fname, phar->fname_len);
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
phar_archive_delref(phar TSRMLS_CC);
unlink(fname);
efree(fname);
RETURN_TRUE;
}
/* }}} */
#if HAVE_SPL
#define PHAR_ARCHIVE_OBJECT() \
phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \
if (!phar_obj->arc.archive) { \
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \
"Cannot call method on an uninitialized Phar object"); \
return; \
}
/* {{{ proto void Phar::__destruct()
* if persistent, remove from the cache
*/
PHP_METHOD(Phar, __destruct)
{
phar_archive_object *phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (phar_obj->arc.archive && phar_obj->arc.archive->is_persistent) {
zend_hash_del(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive));
}
}
/* }}} */
struct _phar_t {
phar_archive_object *p;
zend_class_entry *c;
char *b;
uint l;
zval *ret;
int count;
php_stream *fp;
};
static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) /* {{{ */
{
zval **value;
zend_uchar key_type;
zend_bool close_fp = 1;
ulong int_key;
struct _phar_t *p_obj = (struct _phar_t*) puser;
uint str_key_len, base_len = p_obj->l, fname_len;
phar_entry_data *data;
php_stream *fp;
size_t contents_len;
char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL;
phar_zstr key;
char *str_key;
zend_class_entry *ce = p_obj->c;
phar_archive_object *phar_obj = p_obj->p;
char *str = "[stream]";
iter->funcs->get_current_data(iter, &value TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (!value) {
/* failure in get_current_data */
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned no value", ce->name);
return ZEND_HASH_APPLY_STOP;
}
switch (Z_TYPE_PP(value)) {
#if PHP_VERSION_ID >= 60000
case IS_UNICODE:
zval_unicode_to_string(*(value) TSRMLS_CC);
/* break intentionally omitted */
#endif
case IS_STRING:
break;
case IS_RESOURCE:
php_stream_from_zval_no_verify(fp, value);
if (!fp) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returned an invalid stream handle", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (iter->funcs->get_current_key) {
key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (key_type == HASH_KEY_IS_LONG) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (key_type > 9) { /* IS_UNICODE == 10 */
#if PHP_VERSION_ID < 60000
/* this can never happen, but fixes a compile warning */
spprintf(&str_key, 0, "%s", key);
#else
spprintf(&str_key, 0, "%v", key);
ezfree(key);
#endif
} else {
PHAR_STR(key, str_key);
}
save = str_key;
if (str_key[str_key_len - 1] == '\0') {
str_key_len--;
}
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
close_fp = 0;
opened = (char *) estrndup(str, sizeof("[stream]") - 1);
goto after_open_fp;
case IS_OBJECT:
if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) {
char *test = NULL;
zval dummy;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC);
if (!base_len) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Iterator %v returns an SplFileInfo object, so base directory must be specified", ce->name);
return ZEND_HASH_APPLY_STOP;
}
switch (intern->type) {
case SPL_FS_DIR:
#if PHP_VERSION_ID >= 60000
test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s;
#elif PHP_VERSION_ID >= 50300
test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC);
#else
test = intern->path;
#endif
fname_len = spprintf(&fname, 0, "%s%c%s", test, DEFAULT_SLASH, intern->u.dir.entry.d_name);
php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC);
if (Z_BVAL(dummy)) {
/* ignore directories */
efree(fname);
return ZEND_HASH_APPLY_KEEP;
}
test = expand_filepath(fname, NULL TSRMLS_CC);
efree(fname);
if (test) {
fname = test;
fname_len = strlen(fname);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
return ZEND_HASH_APPLY_STOP;
}
save = fname;
goto phar_spl_fileinfo;
case SPL_FS_INFO:
case SPL_FS_FILE:
#if PHP_VERSION_ID >= 60000
if (intern->file_name_type == IS_UNICODE) {
zval zv;
INIT_ZVAL(zv);
Z_UNIVAL(zv) = intern->file_name;
Z_UNILEN(zv) = intern->file_name_len;
Z_TYPE(zv) = IS_UNICODE;
zval_copy_ctor(&zv);
zval_unicode_to_string(&zv TSRMLS_CC);
fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC);
ezfree(Z_UNIVAL(zv));
} else {
fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC);
}
#else
fname = expand_filepath(intern->file_name, NULL TSRMLS_CC);
#endif
if (!fname) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
return ZEND_HASH_APPLY_STOP;
}
fname_len = strlen(fname);
save = fname;
goto phar_spl_fileinfo;
}
}
/* fall-through */
default:
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid value (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
fname = Z_STRVAL_PP(value);
fname_len = Z_STRLEN_PP(value);
phar_spl_fileinfo:
if (base_len) {
temp = expand_filepath(base, NULL TSRMLS_CC);
if (!temp) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Could not resolve file path");
if (save) {
efree(save);
}
return ZEND_HASH_APPLY_STOP;
}
base = temp;
base_len = strlen(base);
if (strstr(fname, base)) {
str_key_len = fname_len - base_len;
if (str_key_len <= 0) {
if (save) {
efree(save);
efree(temp);
}
return ZEND_HASH_APPLY_KEEP;
}
str_key = fname + base_len;
if (*str_key == '/' || *str_key == '\\') {
str_key++;
str_key_len--;
}
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that is not in the base directory \"%s\"", ce->name, fname, base);
if (save) {
efree(save);
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
} else {
if (iter->funcs->get_current_key) {
key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (key_type == HASH_KEY_IS_LONG) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
if (key_type > 9) { /* IS_UNICODE == 10 */
#if PHP_VERSION_ID < 60000
/* this can never happen, but fixes a compile warning */
spprintf(&str_key, 0, "%s", key);
#else
spprintf(&str_key, 0, "%v", key);
ezfree(key);
#endif
} else {
PHAR_STR(key, str_key);
}
save = str_key;
if (str_key[str_key_len - 1] == '\0') str_key_len--;
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned an invalid key (must return a string)", ce->name);
return ZEND_HASH_APPLY_STOP;
}
}
#if PHP_API_VERSION < 20100412
if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that safe mode prevents opening", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
#endif
if (php_check_open_basedir(fname TSRMLS_CC)) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a path \"%s\" that open_basedir prevents opening", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
/* try to open source file, then create internal phar file and copy contents */
fp = php_stream_open_wrapper(fname, "rb", STREAM_MUST_SEEK|0, &opened);
if (!fp) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Iterator %v returned a file that could not be opened \"%s\"", ce->name, fname);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
return ZEND_HASH_APPLY_STOP;
}
after_open_fp:
if (str_key_len >= sizeof(".phar")-1 && !memcmp(str_key, ".phar", sizeof(".phar")-1)) {
/* silently skip any files that would be added to the magic .phar directory */
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
if (opened) {
efree(opened);
}
if (close_fp) {
php_stream_close(fp);
}
return ZEND_HASH_APPLY_KEEP;
}
if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, "w+b", 0, &error, 1 TSRMLS_CC))) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Entry %s cannot be created: %s", str_key, error);
efree(error);
if (save) {
efree(save);
}
if (opened) {
efree(opened);
}
if (temp) {
efree(temp);
}
if (close_fp) {
php_stream_close(fp);
}
return ZEND_HASH_APPLY_STOP;
} else {
if (error) {
efree(error);
}
/* convert to PHAR_UFP */
if (data->internal_file->fp_type == PHAR_MOD) {
php_stream_close(data->internal_file->fp);
}
data->internal_file->fp = NULL;
data->internal_file->fp_type = PHAR_UFP;
data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp);
data->fp = NULL;
phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len);
data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize =
php_stream_tell(p_obj->fp) - data->internal_file->offset;
}
if (close_fp) {
php_stream_close(fp);
}
add_assoc_string(p_obj->ret, str_key, opened, 0);
if (save) {
efree(save);
}
if (temp) {
efree(temp);
}
data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len;
phar_entry_delref(data TSRMLS_CC);
return ZEND_HASH_APPLY_KEEP;
}
/* }}} */
/* {{{ proto array Phar::buildFromDirectory(string base_dir[, string regex])
* Construct a phar archive from an existing directory, recursively.
* Optional second parameter is a regular expression for filtering directory contents.
*
* Return value is an array mapping phar index to actual files added.
*/
PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
int dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, *iter, *iteriter, *regexiter = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
MAKE_STD_ZVAL(iter);
if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg);
ZVAL_STRINGL(&arg, dir, dir_len, 0);
INIT_PZVAL(&arg2);
#if PHP_VERSION_ID < 50300
ZVAL_LONG(&arg2, 0);
#else
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
#endif
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
MAKE_STD_ZVAL(iteriter);
if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
&spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter);
if (EG(exception)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
RETURN_FALSE;
}
zval_ptr_dtor(&iter);
if (regex_len > 0) {
apply_reg = 1;
MAKE_STD_ZVAL(regexiter);
if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(regexiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg2);
ZVAL_STRINGL(&arg2, regex, regex_len, 0);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter);
pass.p = phar_obj;
pass.b = dir;
pass.l = dir_len;
pass.count = 0;
pass.ret = return_value;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
/* }}} */
/* {{{ proto array Phar::buildFromIterator(Iterator iter[, string base_directory])
* Construct a phar archive from an iterator. The iterator must return a series of strings
* that are full paths to files that should be added to the phar. The iterator key should
* be the path that the file will have within the phar archive.
*
* If base directory is specified, then the key will be ignored, and instead the portion of
* the current value minus the base directory will be used
*
* Returned is an array mapping phar index to actual file added
*/
PHP_METHOD(Phar, buildFromIterator)
{
zval *obj;
char *error;
uint base_len = 0;
char *base = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write out phar archive, phar is read-only");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|s", &obj, zend_ce_traversable, &base, &base_len) == FAILURE) {
RETURN_FALSE;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
array_init(return_value);
pass.c = Z_OBJCE_P(obj);
pass.p = phar_obj;
pass.b = base;
pass.l = base_len;
pass.ret = return_value;
pass.count = 0;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\": unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply(obj, (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
php_stream_close(pass.fp);
}
}
/* }}} */
/* {{{ proto int Phar::count()
* Returns the number of entries in the Phar archive
*/
PHP_METHOD(Phar, count)
{
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest));
}
/* }}} */
/* {{{ proto bool Phar::isFileFormat(int format)
* Returns true if the phar archive is based on the tar/zip/phar file format depending
* on whether Phar::TAR, Phar::ZIP or Phar::PHAR was passed in
*/
PHP_METHOD(Phar, isFileFormat)
{
long type;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &type) == FAILURE) {
RETURN_FALSE;
}
switch (type) {
case PHAR_FORMAT_TAR:
RETURN_BOOL(phar_obj->arc.archive->is_tar);
case PHAR_FORMAT_ZIP:
RETURN_BOOL(phar_obj->arc.archive->is_zip);
case PHAR_FORMAT_PHAR:
RETURN_BOOL(!phar_obj->arc.archive->is_tar && !phar_obj->arc.archive->is_zip);
default:
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "Unknown file format specified");
}
}
/* }}} */
static int phar_copy_file_contents(phar_entry_info *entry, php_stream *fp TSRMLS_DC) /* {{{ */
{
char *error;
off_t offset;
phar_entry_info *link;
if (FAILURE == phar_open_entry_fp(entry, &error, 1 TSRMLS_CC)) {
if (error) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents: %s", entry->phar->fname, entry->filename, error);
efree(error);
} else {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to open entry \"%s\" contents", entry->phar->fname, entry->filename);
}
return FAILURE;
}
/* copy old contents in entirety */
phar_seek_efp(entry, 0, SEEK_SET, 0, 1 TSRMLS_CC);
offset = php_stream_tell(fp);
link = phar_get_link_source(entry TSRMLS_CC);
if (!link) {
link = entry;
}
if (SUCCESS != phar_stream_copy_to_stream(phar_get_efp(link, 0 TSRMLS_CC), fp, link->uncompressed_filesize, NULL)) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\", unable to copy entry \"%s\" contents", entry->phar->fname, entry->filename);
return FAILURE;
}
if (entry->fp_type == PHAR_MOD) {
/* save for potential restore on error */
entry->cfp = entry->fp;
entry->fp = NULL;
}
/* set new location of file contents */
entry->fp_type = PHAR_FP;
entry->offset = offset;
return SUCCESS;
}
/* }}} */
static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool compress TSRMLS_DC) /* {{{ */
{
const char *oldname = NULL;
char *oldpath = NULL;
char *basename = NULL, *basepath = NULL;
char *newname = NULL, *newpath = NULL;
zval *ret, arg1;
zend_class_entry *ce;
char *error;
const char *pcr_error;
int ext_len = ext ? strlen(ext) : 0;
int oldname_len;
phar_archive_data **pphar = NULL;
php_stream_statbuf ssb;
if (!ext) {
if (phar->is_zip) {
if (phar->is_data) {
ext = "zip";
} else {
ext = "phar.zip";
}
} else if (phar->is_tar) {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
if (phar->is_data) {
ext = "tar.gz";
} else {
ext = "phar.tar.gz";
}
break;
case PHAR_FILE_COMPRESSED_BZ2:
if (phar->is_data) {
ext = "tar.bz2";
} else {
ext = "phar.tar.bz2";
}
break;
default:
if (phar->is_data) {
ext = "tar";
} else {
ext = "phar.tar";
}
}
} else {
switch (phar->flags) {
case PHAR_FILE_COMPRESSED_GZ:
ext = "phar.gz";
break;
case PHAR_FILE_COMPRESSED_BZ2:
ext = "phar.bz2";
break;
default:
ext = "phar";
}
}
} else if (phar_path_check(&ext, &ext_len, &pcr_error) > pcr_is_ok) {
if (phar->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar converted from \"%s\" has invalid extension %s", phar->fname, ext);
}
return NULL;
}
if (ext[0] == '.') {
++ext;
}
oldpath = estrndup(phar->fname, phar->fname_len);
oldname = zend_memrchr(phar->fname, '/', phar->fname_len);
++oldname;
oldname_len = strlen(oldname);
basename = estrndup(oldname, oldname_len);
spprintf(&newname, 0, "%s.%s", strtok(basename, "."), ext);
efree(basename);
basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len));
phar->fname_len = spprintf(&newpath, 0, "%s%s", basepath, newname);
phar->fname = newpath;
phar->ext = newpath + phar->fname_len - strlen(ext) - 1;
efree(basepath);
efree(newname);
if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, newpath, phar->fname_len, (void **) &pphar)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, new phar name is in phar.cache_list", phar->fname);
return NULL;
}
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void **) &pphar)) {
if ((*pphar)->fname_len == phar->fname_len && !memcmp((*pphar)->fname, phar->fname, phar->fname_len)) {
if (!zend_hash_num_elements(&phar->manifest)) {
(*pphar)->is_tar = phar->is_tar;
(*pphar)->is_zip = phar->is_zip;
(*pphar)->is_data = phar->is_data;
(*pphar)->flags = phar->flags;
(*pphar)->fp = phar->fp;
phar->fp = NULL;
phar_destroy_phar_data(phar TSRMLS_CC);
phar = *pphar;
phar->refcount++;
newpath = oldpath;
goto its_ok;
}
}
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars, a phar with that name already exists", phar->fname);
return NULL;
}
its_ok:
if (SUCCESS == php_stream_stat_path(newpath, &ssb)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" exists and must be unlinked prior to conversion", newpath);
efree(oldpath);
return NULL;
}
if (!phar->is_data) {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 1, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
if (phar->alias) {
if (phar->is_temporary_alias) {
phar->alias = NULL;
phar->alias_len = 0;
} else {
phar->alias = estrndup(newpath, strlen(newpath));
phar->alias_len = strlen(newpath);
phar->is_temporary_alias = 1;
zend_hash_update(&(PHAR_GLOBALS->phar_alias_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL);
}
}
} else {
if (SUCCESS != phar_detect_phar_fname_ext(newpath, phar->fname_len, (const char **) &(phar->ext), &(phar->ext_len), 0, 1, 1 TSRMLS_CC)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "data phar \"%s\" has invalid extension %s", phar->fname, ext);
return NULL;
}
phar->alias = NULL;
phar->alias_len = 0;
}
if ((!pphar || phar == *pphar) && SUCCESS != zend_hash_update(&(PHAR_GLOBALS->phar_fname_map), newpath, phar->fname_len, (void*)&phar, sizeof(phar_archive_data*), NULL)) {
efree(oldpath);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to add newly converted phar \"%s\" to the list of phars", phar->fname);
return NULL;
}
phar_flush(phar, 0, 0, 1, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "%s", error);
efree(error);
efree(oldpath);
return NULL;
}
efree(oldpath);
if (phar->is_data) {
ce = phar_ce_data;
} else {
ce = phar_ce_archive;
}
MAKE_STD_ZVAL(ret);
if (SUCCESS != object_init_ex(ret, ce)) {
zval_dtor(ret);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate phar object when converting archive \"%s\"", phar->fname);
return NULL;
}
INIT_PZVAL(&arg1);
ZVAL_STRINGL(&arg1, phar->fname, phar->fname_len, 0);
zend_call_method_with_1_params(&ret, ce, &ce->constructor, "__construct", NULL, &arg1);
return ret;
}
/* }}} */
static zval *phar_convert_to_other(phar_archive_data *source, int convert, char *ext, php_uint32 flags TSRMLS_DC) /* {{{ */
{
phar_archive_data *phar;
phar_entry_info *entry, newentry;
zval *ret;
/* invalidate phar cache */
PHAR_G(last_phar) = NULL;
PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL;
phar = (phar_archive_data *) ecalloc(1, sizeof(phar_archive_data));
/* set whole-archive compression and type from parameter */
phar->flags = flags;
phar->is_data = source->is_data;
switch (convert) {
case PHAR_FORMAT_TAR:
phar->is_tar = 1;
break;
case PHAR_FORMAT_ZIP:
phar->is_zip = 1;
break;
default:
phar->is_data = 0;
break;
}
zend_hash_init(&(phar->manifest), sizeof(phar_entry_info),
zend_get_hash_value, destroy_phar_manifest_entry, 0);
zend_hash_init(&phar->mounted_dirs, sizeof(char *),
zend_get_hash_value, NULL, 0);
zend_hash_init(&phar->virtual_dirs, sizeof(char *),
zend_get_hash_value, NULL, 0);
phar->fp = php_stream_fopen_tmpfile();
if (phar->fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "unable to create temporary file");
return NULL;
}
phar->fname = source->fname;
phar->fname_len = source->fname_len;
phar->is_temporary_alias = source->is_temporary_alias;
phar->alias = source->alias;
if (source->metadata) {
zval *t;
t = source->metadata;
ALLOC_ZVAL(phar->metadata);
*phar->metadata = *t;
zval_copy_ctor(phar->metadata);
#if PHP_VERSION_ID < 50300
phar->metadata->refcount = 1;
#else
Z_SET_REFCOUNT_P(phar->metadata, 1);
#endif
phar->metadata_len = 0;
}
/* first copy each file's uncompressed contents to a temporary file and set per-file flags */
for (zend_hash_internal_pointer_reset(&source->manifest); SUCCESS == zend_hash_has_more_elements(&source->manifest); zend_hash_move_forward(&source->manifest)) {
if (FAILURE == zend_hash_get_current_data(&source->manifest, (void **) &entry)) {
zend_hash_destroy(&(phar->manifest));
php_stream_close(phar->fp);
efree(phar);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot convert phar archive \"%s\"", source->fname);
return NULL;
}
newentry = *entry;
if (newentry.link) {
newentry.link = estrdup(newentry.link);
goto no_copy;
}
if (newentry.tmp) {
newentry.tmp = estrdup(newentry.tmp);
goto no_copy;
}
newentry.metadata_str.c = 0;
if (FAILURE == phar_copy_file_contents(&newentry, phar->fp TSRMLS_CC)) {
zend_hash_destroy(&(phar->manifest));
php_stream_close(phar->fp);
efree(phar);
/* exception already thrown */
return NULL;
}
no_copy:
newentry.filename = estrndup(newentry.filename, newentry.filename_len);
if (newentry.metadata) {
zval *t;
t = newentry.metadata;
ALLOC_ZVAL(newentry.metadata);
*newentry.metadata = *t;
zval_copy_ctor(newentry.metadata);
#if PHP_VERSION_ID < 50300
newentry.metadata->refcount = 1;
#else
Z_SET_REFCOUNT_P(newentry.metadata, 1);
#endif
newentry.metadata_str.c = NULL;
newentry.metadata_str.len = 0;
}
newentry.is_zip = phar->is_zip;
newentry.is_tar = phar->is_tar;
if (newentry.is_tar) {
newentry.tar_type = (entry->is_dir ? TAR_DIR : TAR_FILE);
}
newentry.is_modified = 1;
newentry.phar = phar;
newentry.old_flags = newentry.flags & ~PHAR_ENT_COMPRESSION_MASK; /* remove compression from old_flags */
phar_set_inode(&newentry TSRMLS_CC);
zend_hash_add(&(phar->manifest), newentry.filename, newentry.filename_len, (void*)&newentry, sizeof(phar_entry_info), NULL);
phar_add_virtual_dirs(phar, newentry.filename, newentry.filename_len TSRMLS_CC);
}
if ((ret = phar_rename_archive(phar, ext, 0 TSRMLS_CC))) {
return ret;
} else {
zend_hash_destroy(&(phar->manifest));
zend_hash_destroy(&(phar->mounted_dirs));
zend_hash_destroy(&(phar->virtual_dirs));
php_stream_close(phar->fp);
efree(phar->fname);
efree(phar);
return NULL;
/* }}} */
| 1 | CVE-2015-5589 | 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. | 2,983 |
linux-2.6 | f6b97b29513950bfbf621a83d85b6f86b39ec8db | static int nr_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct full_sockaddr_ax25 *sax = (struct full_sockaddr_ax25 *)uaddr;
struct sock *sk = sock->sk;
struct nr_sock *nr = nr_sk(sk);
lock_sock(sk);
if (peer != 0) {
if (sk->sk_state != TCP_ESTABLISHED) {
release_sock(sk);
return -ENOTCONN;
}
sax->fsa_ax25.sax25_family = AF_NETROM;
sax->fsa_ax25.sax25_ndigis = 1;
sax->fsa_ax25.sax25_call = nr->user_addr;
sax->fsa_digipeater[0] = nr->dest_addr;
*uaddr_len = sizeof(struct full_sockaddr_ax25);
} else {
sax->fsa_ax25.sax25_family = AF_NETROM;
sax->fsa_ax25.sax25_ndigis = 0;
sax->fsa_ax25.sax25_call = nr->source_addr;
*uaddr_len = sizeof(struct sockaddr_ax25);
}
release_sock(sk);
return 0;
} | 1 | CVE-2009-3001 | 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. | 8,812 |
savannah | 94e01571507835ff59dd8ce2a0b56a4b566965a4 | getenv_TZ (void)
{
return getenv ("TZ");
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,263 |
linux | 7572777eef78ebdee1ecb7c258c0ef94d35bad16 | static sector_t fuse_bmap(struct address_space *mapping, sector_t block)
{
struct inode *inode = mapping->host;
struct fuse_conn *fc = get_fuse_conn(inode);
struct fuse_req *req;
struct fuse_bmap_in inarg;
struct fuse_bmap_out outarg;
int err;
if (!inode->i_sb->s_bdev || fc->no_bmap)
return 0;
req = fuse_get_req(fc);
if (IS_ERR(req))
return 0;
memset(&inarg, 0, sizeof(inarg));
inarg.block = block;
inarg.blocksize = inode->i_sb->s_blocksize;
req->in.h.opcode = FUSE_BMAP;
req->in.h.nodeid = get_node_id(inode);
req->in.numargs = 1;
req->in.args[0].size = sizeof(inarg);
req->in.args[0].value = &inarg;
req->out.numargs = 1;
req->out.args[0].size = sizeof(outarg);
req->out.args[0].value = &outarg;
fuse_request_send(fc, req);
err = req->out.h.error;
fuse_put_request(fc, req);
if (err == -ENOSYS)
fc->no_bmap = 1;
return err ? 0 : outarg.block;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,363 |
savannah | b3500af717010137046ec4076d1e1c0641e33727 | FT_Bitmap_Convert( FT_Library library,
const FT_Bitmap *source,
FT_Bitmap *target,
FT_Int alignment )
{
FT_Error error = FT_Err_Ok;
FT_Memory memory;
FT_Int source_pitch, target_pitch;
if ( !library )
return FT_THROW( Invalid_Library_Handle );
memory = library->memory;
switch ( source->pixel_mode )
{
case FT_PIXEL_MODE_MONO:
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_GRAY2:
case FT_PIXEL_MODE_GRAY4:
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
case FT_PIXEL_MODE_LCD_V:
case FT_PIXEL_MODE_BGRA:
{
FT_Int pad, old_target_pitch;
FT_Long old_size;
old_target_pitch = target->pitch;
old_target_pitch = -old_target_pitch;
old_size = target->rows * old_target_pitch;
target->pixel_mode = FT_PIXEL_MODE_GRAY;
target->rows = source->rows;
target->width = source->width;
pad = 0;
if ( alignment > 0 )
{
pad = source->width % alignment;
if ( pad != 0 )
pad = alignment - pad;
}
target_pitch = source->width + pad;
if ( target_pitch > 0 &&
(FT_ULong)target->rows > FT_ULONG_MAX / target_pitch )
return FT_THROW( Invalid_Argument );
if ( target->rows * target_pitch > old_size &&
FT_QREALLOC( target->buffer,
old_size, target->rows * target_pitch ) )
return error;
target->pitch = target->pitch < 0 ? -target_pitch : target_pitch;
}
break;
default:
error = FT_THROW( Invalid_Argument );
}
source_pitch = source->pitch;
if ( source_pitch < 0 )
source_pitch = -source_pitch;
switch ( source->pixel_mode )
{
case FT_PIXEL_MODE_MONO:
{
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 2;
for ( i = source->rows; i > 0; i-- )
{
FT_Byte* ss = s;
FT_Byte* tt = t;
FT_Int j;
/* get the full bytes */
for ( j = source->width >> 3; j > 0; j-- )
{
FT_Int val = ss[0]; /* avoid a byte->int cast on each line */
tt[0] = (FT_Byte)( ( val & 0x80 ) >> 7 );
tt[1] = (FT_Byte)( ( val & 0x40 ) >> 6 );
tt[2] = (FT_Byte)( ( val & 0x20 ) >> 5 );
tt[3] = (FT_Byte)( ( val & 0x10 ) >> 4 );
tt[4] = (FT_Byte)( ( val & 0x08 ) >> 3 );
tt[5] = (FT_Byte)( ( val & 0x04 ) >> 2 );
tt[6] = (FT_Byte)( ( val & 0x02 ) >> 1 );
tt[7] = (FT_Byte)( val & 0x01 );
tt += 8;
ss += 1;
}
/* get remaining pixels (if any) */
j = source->width & 7;
if ( j > 0 )
{
FT_Int val = *ss;
for ( ; j > 0; j-- )
{
tt[0] = (FT_Byte)( ( val & 0x80 ) >> 7);
val <<= 1;
tt += 1;
}
}
s += source_pitch;
t += target_pitch;
}
}
break;
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
{
FT_Int width = source->width;
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 256;
for ( i = source->rows; i > 0; i-- )
{
FT_ARRAY_COPY( t, s, width );
s += source_pitch;
t += target_pitch;
}
}
break;
case FT_PIXEL_MODE_GRAY2:
{
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 4;
for ( i = source->rows; i > 0; i-- )
{
FT_Byte* ss = s;
FT_Byte* tt = t;
FT_Int j;
/* get the full bytes */
for ( j = source->width >> 2; j > 0; j-- )
{
FT_Int val = ss[0];
tt[0] = (FT_Byte)( ( val & 0xC0 ) >> 6 );
tt[1] = (FT_Byte)( ( val & 0x30 ) >> 4 );
tt[2] = (FT_Byte)( ( val & 0x0C ) >> 2 );
tt[3] = (FT_Byte)( ( val & 0x03 ) );
ss += 1;
tt += 4;
}
j = source->width & 3;
if ( j > 0 )
{
FT_Int val = ss[0];
for ( ; j > 0; j-- )
{
tt[0] = (FT_Byte)( ( val & 0xC0 ) >> 6 );
val <<= 2;
tt += 1;
}
}
s += source_pitch;
t += target_pitch;
}
}
break;
case FT_PIXEL_MODE_GRAY4:
{
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 16;
for ( i = source->rows; i > 0; i-- )
{
FT_Byte* ss = s;
FT_Byte* tt = t;
FT_Int j;
/* get the full bytes */
for ( j = source->width >> 1; j > 0; j-- )
{
FT_Int val = ss[0];
tt[0] = (FT_Byte)( ( val & 0xF0 ) >> 4 );
tt[1] = (FT_Byte)( ( val & 0x0F ) );
ss += 1;
tt += 2;
}
if ( source->width & 1 )
tt[0] = (FT_Byte)( ( ss[0] & 0xF0 ) >> 4 );
s += source_pitch;
t += target_pitch;
}
}
break;
case FT_PIXEL_MODE_BGRA:
{
FT_Byte* s = source->buffer;
FT_Byte* t = target->buffer;
FT_Int i;
target->num_grays = 256;
for ( i = source->rows; i > 0; i-- )
{
FT_Byte* ss = s;
FT_Byte* tt = t;
FT_Int j;
for ( j = source->width; j > 0; j-- )
{
tt[0] = ft_gray_for_premultiplied_srgb_bgra( ss );
ss += 4;
tt += 1;
}
s += source_pitch;
t += target_pitch;
}
}
break;
default:
;
}
return error;
}
| 1 | CVE-2014-9665 | 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,367 |
php-src | c96d08b27226193dd51f2b50e84272235c6aaa69 | static int get_http_body(php_stream *stream, int close, char *headers, char **response, int *out_size TSRMLS_DC)
{
char *header, *http_buf = NULL;
int header_close = close, header_chunked = 0, header_length = 0, http_buf_size = 0;
if (!close) {
header = get_http_header_value(headers, "Connection: ");
if (header) {
if(!strncasecmp(header, "close", sizeof("close")-1)) header_close = 1;
efree(header);
}
}
header = get_http_header_value(headers, "Transfer-Encoding: ");
if (header) {
if(!strncasecmp(header, "chunked", sizeof("chunked")-1)) header_chunked = 1;
efree(header);
}
header = get_http_header_value(headers, "Content-Length: ");
if (header) {
header_length = atoi(header);
efree(header);
if (!header_length && !header_chunked) {
/* Empty response */
http_buf = emalloc(1);
http_buf[0] = '\0';
(*response) = http_buf;
(*out_size) = 0;
return TRUE;
}
}
if (header_chunked) {
char ch, done, headerbuf[8192];
done = FALSE;
while (!done) {
int buf_size = 0;
php_stream_gets(stream, headerbuf, sizeof(headerbuf));
if (sscanf(headerbuf, "%x", &buf_size) > 0 ) {
if (buf_size > 0) {
int len_size = 0;
if (http_buf_size + buf_size + 1 < 0) {
efree(http_buf);
return FALSE;
}
http_buf = erealloc(http_buf, http_buf_size + buf_size + 1);
while (len_size < buf_size) {
int len_read = php_stream_read(stream, http_buf + http_buf_size, buf_size - len_size);
if (len_read <= 0) {
/* Error or EOF */
done = TRUE;
break;
}
len_size += len_read;
http_buf_size += len_read;
}
/* Eat up '\r' '\n' */
ch = php_stream_getc(stream);
if (ch == '\r') {
ch = php_stream_getc(stream);
}
if (ch != '\n') {
/* Somthing wrong in chunked encoding */
if (http_buf) {
efree(http_buf);
}
return FALSE;
}
}
} else {
/* Somthing wrong in chunked encoding */
if (http_buf) {
efree(http_buf);
}
return FALSE;
}
if (buf_size == 0) {
done = TRUE;
}
}
/* Ignore trailer headers */
while (1) {
if (!php_stream_gets(stream, headerbuf, sizeof(headerbuf))) {
break;
}
if ((headerbuf[0] == '\r' && headerbuf[1] == '\n') ||
(headerbuf[0] == '\n')) {
/* empty line marks end of headers */
break;
}
}
if (http_buf == NULL) {
http_buf = emalloc(1);
}
} else if (header_length) {
if (header_length < 0 || header_length >= INT_MAX) {
return FALSE;
}
http_buf = safe_emalloc(1, header_length, 1);
while (http_buf_size < header_length) {
int len_read = php_stream_read(stream, http_buf + http_buf_size, header_length - http_buf_size);
if (len_read <= 0) {
break;
}
http_buf_size += len_read;
}
} else if (header_close) {
do {
int len_read;
http_buf = erealloc(http_buf, http_buf_size + 4096 + 1);
len_read = php_stream_read(stream, http_buf + http_buf_size, 4096);
if (len_read > 0) {
http_buf_size += len_read;
}
} while(!php_stream_eof(stream));
} else {
return FALSE;
}
http_buf[http_buf_size] = '\0';
(*response) = http_buf;
(*out_size) = http_buf_size;
return TRUE;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,778 |
linux | ed6fe9d614fc1bca95eb8c0ccd0e92db00ef9d5d | static int sock_sendmsg_nosec(struct socket *sock, struct msghdr *msg, size_t size)
{
struct kiocb iocb;
struct sock_iocb siocb;
int ret;
init_sync_kiocb(&iocb, NULL);
iocb.private = &siocb;
ret = __sock_sendmsg_nosec(&iocb, sock, msg, size);
if (-EIOCBQUEUED == ret)
ret = wait_on_sync_kiocb(&iocb);
return ret;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,757 |
linux | 1fb254aa983bf190cfd685d40c64a480a9bafaee | xfs_vn_create(
struct inode *dir,
struct dentry *dentry,
umode_t mode,
bool flags)
{
return xfs_vn_mknod(dir, dentry, mode, 0);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,531 |
FreeRDP | f5e73cc7c9cd973b516a618da877c87b80950b65 | BOOL autodetect_send_bandwidth_measure_payload(rdpContext* context, UINT16 payloadLength,
UINT16 sequenceNumber)
{
wStream* s;
UCHAR* buffer = NULL;
BOOL bResult = FALSE;
s = rdp_message_channel_pdu_init(context->rdp);
if (!s)
return FALSE;
WLog_VRB(AUTODETECT_TAG, "sending Bandwidth Measure Payload PDU -> payloadLength=%" PRIu16 "",
payloadLength);
/* 4-bytes aligned */
payloadLength &= ~3;
if (!Stream_EnsureRemainingCapacity(s, 8 + payloadLength))
{
Stream_Release(s);
return FALSE;
}
Stream_Write_UINT8(s, 0x08); /* headerLength (1 byte) */
Stream_Write_UINT8(s, TYPE_ID_AUTODETECT_REQUEST); /* headerTypeId (1 byte) */
Stream_Write_UINT16(s, sequenceNumber); /* sequenceNumber (2 bytes) */
Stream_Write_UINT16(s, RDP_BW_PAYLOAD_REQUEST_TYPE); /* requestType (2 bytes) */
Stream_Write_UINT16(s, payloadLength); /* payloadLength (2 bytes) */
/* Random data (better measurement in case the line is compressed) */
buffer = (UCHAR*)malloc(payloadLength);
if (NULL == buffer)
{
Stream_Release(s);
return FALSE;
}
winpr_RAND(buffer, payloadLength);
Stream_Write(s, buffer, payloadLength);
bResult = rdp_send_message_channel_pdu(context->rdp, s, SEC_AUTODETECT_REQ);
free(buffer);
return bResult;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,821 |
Android | 04839626ed859623901ebd3a5fd483982186b59d | long Segment::DoLoadCluster(
long long& pos,
long& len)
{
if (m_pos < 0)
return DoLoadClusterUnknownSize(pos, len);
long long total, avail;
long status = m_pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
long long cluster_off = -1; //offset relative to start of segment
long long cluster_size = -1; //size of cluster payload
for (;;)
{
if ((total >= 0) && (m_pos >= total))
return 1; //no more clusters
if ((segment_stop >= 0) && (m_pos >= segment_stop))
return 1; //no more clusters
pos = m_pos;
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) //error (or underflow)
return static_cast<long>(id);
pos += len; //consume ID
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
pos += len; //consume length of size of element
if (size == 0) //weird
{
m_pos = pos;
continue;
}
const long long unknown_size = (1LL << (7 * len)) - 1;
#if 0 //we must handle this to support live webm
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; //TODO: allow this
#endif
if ((segment_stop >= 0) &&
(size != unknown_size) &&
((pos + size) > segment_stop))
{
return E_FILE_FORMAT_INVALID;
}
#if 0 //commented-out, to support incremental cluster parsing
len = static_cast<long>(size);
if ((pos + size) > avail)
return E_BUFFER_NOT_FULL;
#endif
if (id == 0x0C53BB6B) //Cues ID
{
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; //TODO: liberalize
if (m_pCues == NULL)
{
const long long element_size = (pos - idpos) + size;
m_pCues = new Cues(this,
pos,
size,
idpos,
element_size);
assert(m_pCues); //TODO
}
m_pos = pos + size; //consume payload
continue;
}
if (id != 0x0F43B675) //Cluster ID
{
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; //TODO: liberalize
m_pos = pos + size; //consume payload
continue;
}
cluster_off = idpos - m_start; //relative pos
if (size != unknown_size)
cluster_size = size;
break;
}
assert(cluster_off >= 0); //have cluster
long long pos_;
long len_;
status = Cluster::HasBlockEntries(this, cluster_off, pos_, len_);
if (status < 0) //error, or underflow
{
pos = pos_;
len = len_;
return status;
}
const long idx = m_clusterCount;
if (m_clusterPreloadCount > 0)
{
assert(idx < m_clusterSize);
Cluster* const pCluster = m_clusters[idx];
assert(pCluster);
assert(pCluster->m_index < 0);
const long long off = pCluster->GetPosition();
assert(off >= 0);
if (off == cluster_off) //preloaded already
{
if (status == 0) //no entries found
return E_FILE_FORMAT_INVALID;
if (cluster_size >= 0)
pos += cluster_size;
else
{
const long long element_size = pCluster->GetElementSize();
if (element_size <= 0)
return E_FILE_FORMAT_INVALID; //TODO: handle this case
pos = pCluster->m_element_start + element_size;
}
pCluster->m_index = idx; //move from preloaded to loaded
++m_clusterCount;
--m_clusterPreloadCount;
m_pos = pos; //consume payload
assert((segment_stop < 0) || (m_pos <= segment_stop));
return 0; //success
}
}
if (status == 0) //no entries found
{
if (cluster_size < 0)
return E_FILE_FORMAT_INVALID; //TODO: handle this
pos += cluster_size;
if ((total >= 0) && (pos >= total))
{
m_pos = total;
return 1; //no more clusters
}
if ((segment_stop >= 0) && (pos >= segment_stop))
{
m_pos = segment_stop;
return 1; //no more clusters
}
m_pos = pos;
return 2; //try again
}
Cluster* const pCluster = Cluster::Create(this,
idx,
cluster_off);
assert(pCluster);
AppendCluster(pCluster);
assert(m_clusters);
assert(idx < m_clusterSize);
assert(m_clusters[idx] == pCluster);
if (cluster_size >= 0)
{
pos += cluster_size;
m_pos = pos;
assert((segment_stop < 0) || (m_pos <= segment_stop));
return 0;
}
m_pUnknownSize = pCluster;
m_pos = -pos;
return 0; //partial success, since we have a new cluster
//// status == 0 means "no block entries found"
//// pos designates start of payload
//// m_pos has NOT been adjusted yet (in case we need to come back here)
#if 0
if (cluster_size < 0) //unknown size
{
const long long payload_pos = pos; //absolute pos of cluster payload
for (;;) //determine cluster size
{
if ((total >= 0) && (pos >= total))
break;
if ((segment_stop >= 0) && (pos >= segment_stop))
break; //no more clusters
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) //error (or underflow)
return static_cast<long>(id);
if (id == 0x0F43B675) //Cluster ID
break;
if (id == 0x0C53BB6B) //Cues ID
break;
switch (id)
{
case 0x20: //BlockGroup
case 0x23: //Simple Block
case 0x67: //TimeCode
case 0x2B: //PrevSize
break;
default:
assert(false);
break;
}
pos += len; //consume ID (of sub-element)
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
pos += len; //consume size field of element
if (size == 0) //weird
continue;
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; //not allowed for sub-elements
if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird
return E_FILE_FORMAT_INVALID;
pos += size; //consume payload of sub-element
assert((segment_stop < 0) || (pos <= segment_stop));
} //determine cluster size
cluster_size = pos - payload_pos;
assert(cluster_size >= 0);
pos = payload_pos; //reset and re-parse original cluster
}
if (m_clusterPreloadCount > 0)
{
assert(idx < m_clusterSize);
Cluster* const pCluster = m_clusters[idx];
assert(pCluster);
assert(pCluster->m_index < 0);
const long long off = pCluster->GetPosition();
assert(off >= 0);
if (off == cluster_off) //preloaded already
return E_FILE_FORMAT_INVALID; //subtle
}
m_pos = pos + cluster_size; //consume payload
assert((segment_stop < 0) || (m_pos <= segment_stop));
return 2; //try to find another cluster
#endif
}
| 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). | 3,946 |
linux | 350a5c4dd2452ea999cc5e1d4a8dbf12de2f97ef | static int link_detach(union bpf_attr *attr)
{
struct bpf_link *link;
int ret;
if (CHECK_ATTR(BPF_LINK_DETACH))
return -EINVAL;
link = bpf_link_get_from_fd(attr->link_detach.link_fd);
if (IS_ERR(link))
return PTR_ERR(link);
if (link->ops->detach)
ret = link->ops->detach(link);
else
ret = -EOPNOTSUPP;
bpf_link_put(link);
return ret;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,233 |
Android | b9096dc | virtual status_t setCaptureState(bool active)
{
Parcel data, reply;
data.writeInterfaceToken(ISoundTriggerHwService::getInterfaceDescriptor());
data.writeInt32(active);
status_t status = remote()->transact(SET_CAPTURE_STATE, data, &reply);
if (status == NO_ERROR) {
status = reply.readInt32();
}
return status;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,409 |
hhvm | ab6fdeb84fb090b48606b6f7933028cfe7bf3a5e | virtual void moduleInit() {
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_3DES.get(), StaticString("tripledes").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_ARCFOUR.get(), StaticString("arcfour").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_ARCFOUR_IV.get(), StaticString("arcfour-iv").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_BLOWFISH.get(), StaticString("blowfish").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_BLOWFISH_COMPAT.get(), StaticString("blowfish-compat").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_CAST_128.get(), StaticString("cast-128").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_CAST_256.get(), StaticString("cast-256").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_CRYPT.get(), StaticString("crypt").get()
);
Native::registerConstant<KindOfInt64>(
s_MCRYPT_DECRYPT.get(), 1
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_DES.get(), StaticString("des").get()
);
Native::registerConstant<KindOfInt64>(
s_MCRYPT_DEV_RANDOM.get(), RANDOM
);
Native::registerConstant<KindOfInt64>(
s_MCRYPT_DEV_URANDOM.get(), URANDOM
);
Native::registerConstant<KindOfInt64>(
s_MCRYPT_ENCRYPT.get(), 0
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_ENIGNA.get(), StaticString("crypt").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_GOST.get(), StaticString("gost").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_IDEA.get(), StaticString("idea").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_LOKI97.get(), StaticString("loki97").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_MARS.get(), StaticString("mars").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_MODE_CBC.get(), StaticString("cbc").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_MODE_CFB.get(), StaticString("cfb").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_MODE_ECB.get(), StaticString("ecb").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_MODE_NOFB.get(), StaticString("nofb").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_MODE_OFB.get(), StaticString("ofb").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_MODE_STREAM.get(), StaticString("stream").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_PANAMA.get(), StaticString("panama").get()
);
Native::registerConstant<KindOfInt64>(
s_MCRYPT_RAND.get(), RAND
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_RC2.get(), StaticString("rc2").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_RC6.get(), StaticString("rc6").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_RIJNDAEL_128.get(), StaticString("rijndael-128").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_RIJNDAEL_192.get(), StaticString("rijndael-192").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_RIJNDAEL_256.get(), StaticString("rijndael-256").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_SAFER128.get(), StaticString("safer-sk128").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_SAFER64.get(), StaticString("safer-sk64").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_SAFERPLUS.get(), StaticString("saferplus").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_SERPENT.get(), StaticString("serpent").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_SKIPJACK.get(), StaticString("skipjack").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_THREEWAY.get(), StaticString("threeway").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_TRIPLEDES.get(), StaticString("tripledes").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_TWOFISH.get(), StaticString("twofish").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_WAKE.get(), StaticString("wake").get()
);
Native::registerConstant<KindOfStaticString>(
s_MCRYPT_XTEA.get(), StaticString("xtea").get()
);
HHVM_FE(mcrypt_module_open);
HHVM_FE(mcrypt_module_close);
HHVM_FE(mcrypt_list_algorithms);
HHVM_FE(mcrypt_list_modes);
HHVM_FE(mcrypt_module_get_algo_block_size);
HHVM_FE(mcrypt_module_get_algo_key_size);
HHVM_FE(mcrypt_module_get_supported_key_sizes);
HHVM_FE(mcrypt_module_is_block_algorithm_mode);
HHVM_FE(mcrypt_module_is_block_algorithm);
HHVM_FE(mcrypt_module_is_block_mode);
HHVM_FE(mcrypt_module_self_test);
HHVM_FE(mcrypt_create_iv);
HHVM_FE(mcrypt_encrypt);
HHVM_FE(mcrypt_decrypt);
HHVM_FE(mcrypt_cbc);
HHVM_FE(mcrypt_cfb);
HHVM_FE(mcrypt_ecb);
HHVM_FE(mcrypt_ofb);
HHVM_FE(mcrypt_get_block_size);
HHVM_FE(mcrypt_get_cipher_name);
HHVM_FE(mcrypt_get_iv_size);
HHVM_FE(mcrypt_get_key_size);
HHVM_FE(mcrypt_enc_get_algorithms_name);
HHVM_FE(mcrypt_enc_get_block_size);
HHVM_FE(mcrypt_enc_get_iv_size);
HHVM_FE(mcrypt_enc_get_key_size);
HHVM_FE(mcrypt_enc_get_modes_name);
HHVM_FE(mcrypt_enc_get_supported_key_sizes);
HHVM_FE(mcrypt_enc_is_block_algorithm_mode);
HHVM_FE(mcrypt_enc_is_block_algorithm);
HHVM_FE(mcrypt_enc_is_block_mode);
HHVM_FE(mcrypt_enc_self_test);
HHVM_FE(mcrypt_generic_init);
HHVM_FE(mcrypt_generic);
HHVM_FE(mdecrypt_generic);
HHVM_FE(mcrypt_generic_deinit);
HHVM_FE(mcrypt_generic_end);
loadSystemlib();
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,472 |
gpac | bceb03fd2be95097a7b409ea59914f332fb6bc86 | GF_Err stsh_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 count, i;
GF_StshEntry *ent;
GF_ShadowSyncBox *ptr = (GF_ShadowSyncBox *)s;
count = gf_bs_read_u32(bs);
for (i = 0; i < count; i++) {
ent = (GF_StshEntry *) gf_malloc(sizeof(GF_StshEntry));
if (!ent) return GF_OUT_OF_MEM;
ent->shadowedSampleNumber = gf_bs_read_u32(bs);
ent->syncSampleNumber = gf_bs_read_u32(bs);
e = gf_list_add(ptr->entries, ent);
if (e) return e;
}
return GF_OK;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,131 |
stb | 5ba0baaa269b3fd681828e0e3b3ac0f1472eaf40 | static int stbi__process_frame_header(stbi__jpeg *z, int scan)
{
stbi__context *s = z->s;
int Lf,p,i,q, h_max=1,v_max=1,c;
Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG
p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires
if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
c = stbi__get8(s);
if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG");
s->img_n = c;
for (i=0; i < c; ++i) {
z->img_comp[i].data = NULL;
z->img_comp[i].linebuf = NULL;
}
if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG");
z->rgb = 0;
for (i=0; i < s->img_n; ++i) {
static const unsigned char rgb[3] = { 'R', 'G', 'B' };
z->img_comp[i].id = stbi__get8(s);
if (s->img_n == 3 && z->img_comp[i].id == rgb[i])
++z->rgb;
q = stbi__get8(s);
z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG");
z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG");
z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG");
}
if (scan != STBI__SCAN_load) return 1;
if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode");
for (i=0; i < s->img_n; ++i) {
if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
}
// compute interleaved mcu info
z->img_h_max = h_max;
z->img_v_max = v_max;
z->img_mcu_w = h_max * 8;
z->img_mcu_h = v_max * 8;
// these sizes can't be more than 17 bits
z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;
z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;
for (i=0; i < s->img_n; ++i) {
// number of effective pixels (e.g. for non-interleaved MCU)
z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;
z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;
// to simplify generation, we'll allocate enough memory to decode
// the bogus oversized data from using interleaved MCUs and their
// big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
// discard the extra data until colorspace conversion
//
// img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier)
// so these muls can't overflow with 32-bit ints (which we require)
z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
z->img_comp[i].coeff = 0;
z->img_comp[i].raw_coeff = 0;
z->img_comp[i].linebuf = NULL;
z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15);
if (z->img_comp[i].raw_data == NULL)
return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory"));
// align blocks for idct using mmx/sse
z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
if (z->progressive) {
// w2, h2 are multiples of 8 (see above)
z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8;
z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8;
z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15);
if (z->img_comp[i].raw_coeff == NULL)
return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory"));
z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15);
}
}
return 1;
} | 1 | CVE-2021-28021 | 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). | 1,700 |
linux | c085c49920b2f900ba716b4ca1c1a55ece9872cc | static int br_mdb_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net_device *dev;
struct net *net = sock_net(skb->sk);
struct nlmsghdr *nlh = NULL;
int idx = 0, s_idx;
s_idx = cb->args[0];
rcu_read_lock();
/* In theory this could be wrapped to 0... */
cb->seq = net->dev_base_seq + br_mdb_rehash_seq;
for_each_netdev_rcu(net, dev) {
if (dev->priv_flags & IFF_EBRIDGE) {
struct br_port_msg *bpm;
if (idx < s_idx)
goto skip;
nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, RTM_GETMDB,
sizeof(*bpm), NLM_F_MULTI);
if (nlh == NULL)
break;
bpm = nlmsg_data(nlh);
bpm->ifindex = dev->ifindex;
if (br_mdb_fill_info(skb, cb, dev) < 0)
goto out;
if (br_rports_fill_info(skb, cb, dev) < 0)
goto out;
cb->args[1] = 0;
nlmsg_end(skb, nlh);
skip:
idx++;
}
}
out:
if (nlh)
nlmsg_end(skb, nlh);
rcu_read_unlock();
cb->args[0] = idx;
return skb->len;
}
| 1 | CVE-2013-2636 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 7,570 |
gpac | 35ab4475a7df9b2a4bcab235e379c0c3ec543658 | GF_Err gf_sm_load_init(GF_SceneLoader *load)
{
GF_Err e = GF_NOT_SUPPORTED;
char *ext, szExt[50];
/*we need at least a scene graph*/
if (!load || (!load->ctx && !load->scene_graph)
#ifndef GPAC_DISABLE_ISOM
|| (!load->fileName && !load->isom && !(load->flags & GF_SM_LOAD_FOR_PLAYBACK) )
#endif
) return GF_BAD_PARAM;
if (!load->type) {
#ifndef GPAC_DISABLE_ISOM
if (load->isom) {
load->type = GF_SM_LOAD_MP4;
} else
#endif
{
ext = (char *)strrchr(load->fileName, '.');
if (!ext) return GF_NOT_SUPPORTED;
if (!stricmp(ext, ".gz")) {
char *anext;
ext[0] = 0;
anext = (char *)strrchr(load->fileName, '.');
ext[0] = '.';
ext = anext;
}
strcpy(szExt, &ext[1]);
strlwr(szExt);
if (strstr(szExt, "bt")) load->type = GF_SM_LOAD_BT;
else if (strstr(szExt, "wrl")) load->type = GF_SM_LOAD_VRML;
else if (strstr(szExt, "x3dv")) load->type = GF_SM_LOAD_X3DV;
#ifndef GPAC_DISABLE_LOADER_XMT
else if (strstr(szExt, "xmt") || strstr(szExt, "xmta")) load->type = GF_SM_LOAD_XMTA;
else if (strstr(szExt, "x3d")) load->type = GF_SM_LOAD_X3D;
#endif
else if (strstr(szExt, "swf")) load->type = GF_SM_LOAD_SWF;
else if (strstr(szExt, "mov")) load->type = GF_SM_LOAD_QT;
else if (strstr(szExt, "svg")) load->type = GF_SM_LOAD_SVG;
else if (strstr(szExt, "xsr")) load->type = GF_SM_LOAD_XSR;
else if (strstr(szExt, "xbl")) load->type = GF_SM_LOAD_XBL;
else if (strstr(szExt, "xml")) {
char *rtype = gf_xml_get_root_type(load->fileName, &e);
if (rtype) {
if (!strcmp(rtype, "SAFSession")) load->type = GF_SM_LOAD_XSR;
else if (!strcmp(rtype, "XMT-A")) load->type = GF_SM_LOAD_XMTA;
else if (!strcmp(rtype, "X3D")) load->type = GF_SM_LOAD_X3D;
else if (!strcmp(rtype, "bindings")) load->type = GF_SM_LOAD_XBL;
gf_free(rtype);
}
}
}
}
if (!load->type) return e;
if (!load->scene_graph) load->scene_graph = load->ctx->scene_graph;
switch (load->type) {
#ifndef GPAC_DISABLE_LOADER_BT
case GF_SM_LOAD_BT:
case GF_SM_LOAD_VRML:
case GF_SM_LOAD_X3DV:
return gf_sm_load_init_bt(load);
#endif
#ifndef GPAC_DISABLE_LOADER_XMT
case GF_SM_LOAD_XMTA:
case GF_SM_LOAD_X3D:
return gf_sm_load_init_xmt(load);
#endif
#ifndef GPAC_DISABLE_SVG
case GF_SM_LOAD_SVG:
case GF_SM_LOAD_XSR:
case GF_SM_LOAD_DIMS:
return gf_sm_load_init_svg(load);
case GF_SM_LOAD_XBL:
e = gf_sm_load_init_xbl(load);
load->process = gf_sm_load_run_xbl;
load->done = gf_sm_load_done_xbl;
return e;
#endif
#ifndef GPAC_DISABLE_SWF_IMPORT
case GF_SM_LOAD_SWF:
return gf_sm_load_init_swf(load);
#endif
#ifndef GPAC_DISABLE_LOADER_ISOM
case GF_SM_LOAD_MP4:
return gf_sm_load_init_isom(load);
#endif
#ifndef GPAC_DISABLE_QTVR
case GF_SM_LOAD_QT:
return gf_sm_load_init_qt(load);
#endif
default:
return GF_NOT_SUPPORTED;
}
return GF_NOT_SUPPORTED;
}
| 1 | CVE-2018-20762 | 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). | 425 |
libxkbcommon | c1e5ac16e77a21f87bdf3bc4dea61b037a17dddb | ExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append)
{
unsigned nSyms = darray_size(expr->keysym_list.syms);
unsigned numEntries = darray_size(append->keysym_list.syms);
darray_append(expr->keysym_list.symsMapIndex, nSyms);
darray_append(expr->keysym_list.symsNumEntries, numEntries);
darray_concat(expr->keysym_list.syms, append->keysym_list.syms);
FreeStmt((ParseCommon *) &append);
return expr;
}
| 1 | CVE-2018-15857 | CWE-416 | Use After Free | The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
Phase: Architecture and Design
Strategy: Language Selection
Choose a language that provides automatic memory management.
Phase: Implementation
Strategy: Attack Surface Reduction
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.
Effectiveness: Defense in Depth
Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution. | 8,388 |
linux | fb58fdcd295b914ece1d829b24df00a17a9624bc | static void intel_iommu_domain_free(struct iommu_domain *domain)
{
domain_exit(to_dmar_domain(domain));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,455 |
tensorflow | a68f68061e263a88321c104a6c911fe5598050a8 | explicit SparseTensorAccessingOp(OpKernelConstruction* context)
: OpKernel(context), sparse_tensors_map_(nullptr) {} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,229 |
openssl | 1421e0c584ae9120ca1b88098f13d6d2e90b83a3 | int ssl3_accept(SSL *s)
{
BUF_MEM *buf;
unsigned long alg_k,Time=(unsigned long)time(NULL);
void (*cb)(const SSL *ssl,int type,int val)=NULL;
int ret= -1;
int new_state,state,skip=0;
RAND_add(&Time,sizeof(Time),0);
ERR_clear_error();
clear_sys_error();
if (s->info_callback != NULL)
cb=s->info_callback;
else if (s->ctx->info_callback != NULL)
cb=s->ctx->info_callback;
/* init things to blank */
s->in_handshake++;
if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
if (s->cert == NULL)
{
SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
return(-1);
}
#ifndef OPENSSL_NO_HEARTBEATS
/* If we're awaiting a HeartbeatResponse, pretend we
* already got and don't await it anymore, because
* Heartbeats don't make sense during handshakes anyway.
*/
if (s->tlsext_hb_pending)
{
s->tlsext_hb_pending = 0;
s->tlsext_hb_seq++;
}
#endif
for (;;)
{
state=s->state;
switch (s->state)
{
case SSL_ST_RENEGOTIATE:
s->renegotiate=1;
/* s->state=SSL_ST_ACCEPT; */
case SSL_ST_BEFORE:
case SSL_ST_ACCEPT:
case SSL_ST_BEFORE|SSL_ST_ACCEPT:
case SSL_ST_OK|SSL_ST_ACCEPT:
s->server=1;
if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
if ((s->version>>8) != 3)
{
SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
return -1;
}
if (!ssl_security(s, SSL_SECOP_VERSION, 0,
s->version, NULL))
{
SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW);
return -1;
}
s->type=SSL_ST_ACCEPT;
if (s->init_buf == NULL)
{
if ((buf=BUF_MEM_new()) == NULL)
{
ret= -1;
goto end;
}
if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
{
BUF_MEM_free(buf);
ret= -1;
goto end;
}
s->init_buf=buf;
}
if (!ssl3_setup_buffers(s))
{
ret= -1;
goto end;
}
s->init_num=0;
s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
/* Should have been reset by ssl3_get_finished, too. */
s->s3->change_cipher_spec = 0;
if (s->state != SSL_ST_RENEGOTIATE)
{
/* Ok, we now need to push on a buffering BIO so that
* the output is sent in a way that TCP likes :-)
*/
if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
ssl3_init_finished_mac(s);
s->state=SSL3_ST_SR_CLNT_HELLO_A;
s->ctx->stats.sess_accept++;
}
else if (!s->s3->send_connection_binding &&
!(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
{
/* Server attempting to renegotiate with
* client that doesn't support secure
* renegotiation.
*/
SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
ret = -1;
goto end;
}
else
{
/* s->state == SSL_ST_RENEGOTIATE,
* we will just send a HelloRequest */
s->ctx->stats.sess_accept_renegotiate++;
s->state=SSL3_ST_SW_HELLO_REQ_A;
}
break;
case SSL3_ST_SW_HELLO_REQ_A:
case SSL3_ST_SW_HELLO_REQ_B:
s->shutdown=0;
ret=ssl3_send_hello_request(s);
if (ret <= 0) goto end;
s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
s->state=SSL3_ST_SW_FLUSH;
s->init_num=0;
ssl3_init_finished_mac(s);
break;
case SSL3_ST_SW_HELLO_REQ_C:
s->state=SSL_ST_OK;
break;
case SSL3_ST_SR_CLNT_HELLO_A:
case SSL3_ST_SR_CLNT_HELLO_B:
case SSL3_ST_SR_CLNT_HELLO_C:
ret=ssl3_get_client_hello(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_SRP
s->state = SSL3_ST_SR_CLNT_HELLO_D;
case SSL3_ST_SR_CLNT_HELLO_D:
{
int al;
if ((ret = ssl_check_srp_ext_ClientHello(s,&al)) < 0)
{
/* callback indicates firther work to be done */
s->rwstate=SSL_X509_LOOKUP;
goto end;
}
if (ret != SSL_ERROR_NONE)
{
ssl3_send_alert(s,SSL3_AL_FATAL,al);
/* This is not really an error but the only means to
for a client to detect whether srp is supported. */
if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
ret= -1;
goto end;
}
}
#endif
s->renegotiate = 2;
s->state=SSL3_ST_SW_SRVR_HELLO_A;
s->init_num=0;
break;
case SSL3_ST_SW_SRVR_HELLO_A:
case SSL3_ST_SW_SRVR_HELLO_B:
ret=ssl3_send_server_hello(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s->hit)
{
if (s->tlsext_ticket_expected)
s->state=SSL3_ST_SW_SESSION_TICKET_A;
else
s->state=SSL3_ST_SW_CHANGE_A;
}
#else
if (s->hit)
s->state=SSL3_ST_SW_CHANGE_A;
#endif
else
s->state = SSL3_ST_SW_CERT_A;
s->init_num = 0;
break;
case SSL3_ST_SW_CERT_A:
case SSL3_ST_SW_CERT_B:
/* Check if it is anon DH or anon ECDH, */
/* normal PSK or KRB5 or SRP */
if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP))
&& !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
{
ret=ssl3_send_server_certificate(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s->tlsext_status_expected)
s->state=SSL3_ST_SW_CERT_STATUS_A;
else
s->state=SSL3_ST_SW_KEY_EXCH_A;
}
else
{
skip = 1;
s->state=SSL3_ST_SW_KEY_EXCH_A;
}
#else
}
else
skip=1;
s->state=SSL3_ST_SW_KEY_EXCH_A;
#endif
s->init_num=0;
break;
case SSL3_ST_SW_KEY_EXCH_A:
case SSL3_ST_SW_KEY_EXCH_B:
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
/*
* clear this, it may get reset by
* send_server_key_exchange
*/
s->s3->tmp.use_rsa_tmp=0;
/* only send if a DH key exchange, fortezza or
* RSA but we have a sign only certificate
*
* PSK: may send PSK identity hints
*
* For ECC ciphersuites, we send a serverKeyExchange
* message only if the cipher suite is either
* ECDH-anon or ECDHE. In other cases, the
* server certificate contains the server's
* public key for key exchange.
*/
if (0
/* PSK: send ServerKeyExchange if PSK identity
* hint if provided */
#ifndef OPENSSL_NO_PSK
|| ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
#endif
#ifndef OPENSSL_NO_SRP
/* SRP: send ServerKeyExchange */
|| (alg_k & SSL_kSRP)
#endif
|| (alg_k & SSL_kDHE)
|| (alg_k & SSL_kECDHE)
|| ((alg_k & SSL_kRSA)
&& (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
|| (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
&& EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
)
)
)
)
{
ret=ssl3_send_server_key_exchange(s);
if (ret <= 0) goto end;
}
else
skip=1;
s->state=SSL3_ST_SW_CERT_REQ_A;
s->init_num=0;
break;
case SSL3_ST_SW_CERT_REQ_A:
case SSL3_ST_SW_CERT_REQ_B:
if (/* don't request cert unless asked for it: */
!(s->verify_mode & SSL_VERIFY_PEER) ||
/* if SSL_VERIFY_CLIENT_ONCE is set,
* don't request cert during re-negotiation: */
((s->session->peer != NULL) &&
(s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
/* never request cert in anonymous ciphersuites
* (see section "Certificate request" in SSL 3 drafts
* and in RFC 2246): */
((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
/* ... except when the application insists on verification
* (against the specs, but s3_clnt.c accepts this for SSL 3) */
!(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
/* never request cert in Kerberos ciphersuites */
(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
/* don't request certificate for SRP auth */
(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
/* With normal PSK Certificates and
* Certificate Requests are omitted */
|| (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
{
/* no cert request */
skip=1;
s->s3->tmp.cert_request=0;
s->state=SSL3_ST_SW_SRVR_DONE_A;
if (s->s3->handshake_buffer)
if (!ssl3_digest_cached_records(s))
return -1;
}
else
{
s->s3->tmp.cert_request=1;
ret=ssl3_send_certificate_request(s);
if (ret <= 0) goto end;
#ifndef NETSCAPE_HANG_BUG
s->state=SSL3_ST_SW_SRVR_DONE_A;
#else
s->state=SSL3_ST_SW_FLUSH;
s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
#endif
s->init_num=0;
}
break;
case SSL3_ST_SW_SRVR_DONE_A:
case SSL3_ST_SW_SRVR_DONE_B:
ret=ssl3_send_server_done(s);
if (ret <= 0) goto end;
s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
s->state=SSL3_ST_SW_FLUSH;
s->init_num=0;
break;
case SSL3_ST_SW_FLUSH:
/* This code originally checked to see if
* any data was pending using BIO_CTRL_INFO
* and then flushed. This caused problems
* as documented in PR#1939. The proposed
* fix doesn't completely resolve this issue
* as buggy implementations of BIO_CTRL_PENDING
* still exist. So instead we just flush
* unconditionally.
*/
s->rwstate=SSL_WRITING;
if (BIO_flush(s->wbio) <= 0)
{
ret= -1;
goto end;
}
s->rwstate=SSL_NOTHING;
s->state=s->s3->tmp.next_state;
break;
case SSL3_ST_SR_CERT_A:
case SSL3_ST_SR_CERT_B:
if (s->s3->tmp.cert_request)
{
ret=ssl3_get_client_certificate(s);
if (ret <= 0) goto end;
}
s->init_num=0;
s->state=SSL3_ST_SR_KEY_EXCH_A;
break;
case SSL3_ST_SR_KEY_EXCH_A:
case SSL3_ST_SR_KEY_EXCH_B:
ret=ssl3_get_client_key_exchange(s);
if (ret <= 0)
goto end;
if (ret == 2)
{
/* For the ECDH ciphersuites when
* the client sends its ECDH pub key in
* a certificate, the CertificateVerify
* message is not sent.
* Also for GOST ciphersuites when
* the client uses its key from the certificate
* for key exchange.
*/
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->state=SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->state=SSL3_ST_SR_NEXT_PROTO_A;
else
s->state=SSL3_ST_SR_FINISHED_A;
#endif
s->init_num = 0;
}
else if (SSL_USE_SIGALGS(s))
{
s->state=SSL3_ST_SR_CERT_VRFY_A;
s->init_num=0;
if (!s->session->peer)
break;
/* For sigalgs freeze the handshake buffer
* at this point and digest cached records.
*/
if (!s->s3->handshake_buffer)
{
SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR);
return -1;
}
s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
if (!ssl3_digest_cached_records(s))
return -1;
}
else
{
int offset=0;
int dgst_num;
s->state=SSL3_ST_SR_CERT_VRFY_A;
s->init_num=0;
/* We need to get hashes here so if there is
* a client cert, it can be verified
* FIXME - digest processing for CertificateVerify
* should be generalized. But it is next step
*/
if (s->s3->handshake_buffer)
if (!ssl3_digest_cached_records(s))
return -1;
for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)
if (s->s3->handshake_dgst[dgst_num])
{
int dgst_size;
s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset]));
dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
if (dgst_size < 0)
{
ret = -1;
goto end;
}
offset+=dgst_size;
}
}
break;
case SSL3_ST_SR_CERT_VRFY_A:
case SSL3_ST_SR_CERT_VRFY_B:
/*
* This *should* be the first time we enable CCS, but be
* extra careful about surrounding code changes. We need
* to set this here because we don't know if we're
* expecting a CertificateVerify or not.
*/
if (!s->s3->change_cipher_spec)
s->s3->flags |= SSL3_FLAGS_CCS_OK;
/* we should decide if we expected this one */
ret=ssl3_get_cert_verify(s);
if (ret <= 0) goto end;
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->state=SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->state=SSL3_ST_SR_NEXT_PROTO_A;
else
s->state=SSL3_ST_SR_FINISHED_A;
#endif
s->init_num=0;
break;
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
case SSL3_ST_SR_NEXT_PROTO_A:
case SSL3_ST_SR_NEXT_PROTO_B:
/*
* Enable CCS for resumed handshakes with NPN.
* In a full handshake with NPN, we end up here through
* SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
* already set. Receiving a CCS clears the flag, so make
* sure not to re-enable it to ban duplicates.
* s->s3->change_cipher_spec is set when a CCS is
* processed in s3_pkt.c, and remains set until
* the client's Finished message is read.
*/
if (!s->s3->change_cipher_spec)
s->s3->flags |= SSL3_FLAGS_CCS_OK;
ret=ssl3_get_next_proto(s);
if (ret <= 0) goto end;
s->init_num = 0;
s->state=SSL3_ST_SR_FINISHED_A;
break;
#endif
case SSL3_ST_SR_FINISHED_A:
case SSL3_ST_SR_FINISHED_B:
/*
* Enable CCS for resumed handshakes without NPN.
* In a full handshake, we end up here through
* SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
* already set. Receiving a CCS clears the flag, so make
* sure not to re-enable it to ban duplicates.
* s->s3->change_cipher_spec is set when a CCS is
* processed in s3_pkt.c, and remains set until
* the client's Finished message is read.
*/
if (!s->s3->change_cipher_spec)
s->s3->flags |= SSL3_FLAGS_CCS_OK;
ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
SSL3_ST_SR_FINISHED_B);
if (ret <= 0) goto end;
if (s->hit)
s->state=SSL_ST_OK;
#ifndef OPENSSL_NO_TLSEXT
else if (s->tlsext_ticket_expected)
s->state=SSL3_ST_SW_SESSION_TICKET_A;
#endif
else
s->state=SSL3_ST_SW_CHANGE_A;
s->init_num=0;
break;
#ifndef OPENSSL_NO_TLSEXT
case SSL3_ST_SW_SESSION_TICKET_A:
case SSL3_ST_SW_SESSION_TICKET_B:
ret=ssl3_send_newsession_ticket(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_CHANGE_A;
s->init_num=0;
break;
case SSL3_ST_SW_CERT_STATUS_A:
case SSL3_ST_SW_CERT_STATUS_B:
ret=ssl3_send_cert_status(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_KEY_EXCH_A;
s->init_num=0;
break;
#endif
case SSL3_ST_SW_CHANGE_A:
case SSL3_ST_SW_CHANGE_B:
s->session->cipher=s->s3->tmp.new_cipher;
if (!s->method->ssl3_enc->setup_key_block(s))
{ ret= -1; goto end; }
ret=ssl3_send_change_cipher_spec(s,
SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_FINISHED_A;
s->init_num=0;
if (!s->method->ssl3_enc->change_cipher_state(s,
SSL3_CHANGE_CIPHER_SERVER_WRITE))
{
ret= -1;
goto end;
}
break;
case SSL3_ST_SW_FINISHED_A:
case SSL3_ST_SW_FINISHED_B:
ret=ssl3_send_finished(s,
SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
s->method->ssl3_enc->server_finished_label,
s->method->ssl3_enc->server_finished_label_len);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_FLUSH;
if (s->hit)
{
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
{
s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A;
}
else
s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
#endif
}
else
s->s3->tmp.next_state=SSL_ST_OK;
s->init_num=0;
break;
case SSL_ST_OK:
/* clean a few things up */
ssl3_cleanup_key_block(s);
BUF_MEM_free(s->init_buf);
s->init_buf=NULL;
/* remove buffering on output */
ssl_free_wbio_buffer(s);
s->init_num=0;
if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
{
s->renegotiate=0;
s->new_session=0;
ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
s->ctx->stats.sess_accept_good++;
/* s->server=1; */
s->handshake_func=ssl3_accept;
if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
}
ret = 1;
goto end;
/* break; */
default:
SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
ret= -1;
goto end;
/* break; */
}
if (!s->s3->tmp.reuse_message && !skip)
{
if (s->debug)
{
if ((ret=BIO_flush(s->wbio)) <= 0)
goto end;
}
if ((cb != NULL) && (s->state != state))
{
new_state=s->state;
s->state=state;
cb(s,SSL_CB_ACCEPT_LOOP,1);
s->state=new_state;
}
}
skip=0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,478 |
php | 1e9b175204e3286d64dfd6c9f09151c31b5e099a | PHP_METHOD(Phar, offsetUnset)
{
char *fname, *error;
size_t fname_len;
phar_entry_info *entry;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) {
return;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) {
if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) {
if (entry->is_deleted) {
/* entry is deleted, but has not been flushed to disk yet */
return;
}
if (phar_obj->archive->is_persistent) {
if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
/* re-populate entry after copy on write */
entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len);
}
entry->is_modified = 0;
entry->is_deleted = 1;
/* we need to "flush" the stream to save the newly deleted file on disk */
phar_flush(phar_obj->archive, 0, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
RETURN_TRUE;
}
} else {
RETURN_FALSE;
}
}
| 1 | CVE-2016-4072 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 2,584 |
ImageMagick | 73a2bad43d157acfe360595feee739b4cc4406cb | static Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define CMYKProcessColor "CMYKProcessColor"
#define CropBox "CropBox"
#define DefaultCMYK "DefaultCMYK"
#define DeviceCMYK "DeviceCMYK"
#define MediaBox "MediaBox"
#define RenderPostscriptText "Rendering Postscript... "
#define PDFRotate "Rotate"
#define SpotColor "Separation"
#define TrimBox "TrimBox"
#define PDFVersion "PDF-"
char
command[MaxTextExtent],
*density,
filename[MaxTextExtent],
geometry[MaxTextExtent],
*options,
input_filename[MaxTextExtent],
message[MaxTextExtent],
postscript_filename[MaxTextExtent];
const char
*option;
const DelegateInfo
*delegate_info;
double
angle;
GeometryInfo
geometry_info;
Image
*image,
*next,
*pdf_image;
ImageInfo
*read_info;
int
c,
file;
MagickBooleanType
cmyk,
cropbox,
fitPage,
status,
stop_on_error,
trimbox;
MagickStatusType
flags;
PointInfo
delta;
RectangleInfo
bounding_box,
page;
register char
*p;
register ssize_t
i;
SegmentInfo
bounds,
hires_bounds;
size_t
scene,
spotcolor;
ssize_t
count;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
/*
Open image file.
*/
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);
if (status == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
image_info->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Set the page density.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
{
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
if (image_info->density != (char *) NULL)
{
flags=ParseGeometry(image_info->density,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
(void) ResetMagickMemory(&page,0,sizeof(page));
(void) ParseAbsoluteGeometry(PSPageGeometry,&page);
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
page.width=(size_t) ceil((double) (page.width*image->x_resolution/delta.x)-
0.5);
page.height=(size_t) ceil((double) (page.height*image->y_resolution/delta.y)-
0.5);
/*
Determine page geometry from the PDF media box.
*/
cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;
cropbox=MagickFalse;
option=GetImageOption(image_info,"pdf:use-cropbox");
if (option != (const char *) NULL)
cropbox=IsMagickTrue(option);
stop_on_error=MagickFalse;
option=GetImageOption(image_info,"pdf:stop-on-error");
if (option != (const char *) NULL)
stop_on_error=IsMagickTrue(option);
trimbox=MagickFalse;
option=GetImageOption(image_info,"pdf:use-trimbox");
if (option != (const char *) NULL)
trimbox=IsMagickTrue(option);
count=0;
spotcolor=0;
(void) ResetMagickMemory(&bounding_box,0,sizeof(bounding_box));
(void) ResetMagickMemory(&bounds,0,sizeof(bounds));
(void) ResetMagickMemory(&hires_bounds,0,sizeof(hires_bounds));
(void) ResetMagickMemory(command,0,sizeof(command));
angle=0.0;
p=command;
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
/*
Note PDF elements.
*/
if (c == '\n')
c=' ';
*p++=(char) c;
if ((c != (int) '/') && (c != (int) '%') &&
((size_t) (p-command) < (MaxTextExtent-1)))
continue;
*(--p)='\0';
p=command;
if (LocaleNCompare(PDFRotate,command,strlen(PDFRotate)) == 0)
(void) sscanf(command,"Rotate %lf",&angle);
/*
Is this a CMYK document?
*/
if (LocaleNCompare(DefaultCMYK,command,strlen(DefaultCMYK)) == 0)
cmyk=MagickTrue;
if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0)
cmyk=MagickTrue;
if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0)
cmyk=MagickTrue;
if (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0)
{
char
name[MaxTextExtent],
property[MaxTextExtent],
*value;
register ssize_t
i;
/*
Note spot names.
*/
(void) FormatLocaleString(property,MaxTextExtent,"pdf:SpotColor-%.20g",
(double) spotcolor++);
i=0;
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
if ((isspace(c) != 0) || (c == '/') || ((i+1) == MaxTextExtent))
break;
name[i++]=(char) c;
}
name[i]='\0';
value=AcquireString(name);
(void) SubstituteString(&value,"#20"," ");
(void) SetImageProperty(image,property,value);
value=DestroyString(value);
continue;
}
if (LocaleNCompare(PDFVersion,command,strlen(PDFVersion)) == 0)
(void) SetImageProperty(image,"pdf:Version",command);
if (image_info->page != (char *) NULL)
continue;
count=0;
if (cropbox != MagickFalse)
{
if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0)
{
/*
Note region defined by crop box.
*/
count=(ssize_t) sscanf(command,"CropBox [%lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
if (count != 4)
count=(ssize_t) sscanf(command,"CropBox[%lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
}
}
else
if (trimbox != MagickFalse)
{
if (LocaleNCompare(TrimBox,command,strlen(TrimBox)) == 0)
{
/*
Note region defined by trim box.
*/
count=(ssize_t) sscanf(command,"TrimBox [%lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
if (count != 4)
count=(ssize_t) sscanf(command,"TrimBox[%lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
}
}
else
if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0)
{
/*
Note region defined by media box.
*/
count=(ssize_t) sscanf(command,"MediaBox [%lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
if (count != 4)
count=(ssize_t) sscanf(command,"MediaBox[%lf %lf %lf %lf",
&bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
}
if (count != 4)
continue;
if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) ||
(fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1)))
continue;
hires_bounds=bounds;
}
if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) &&
(fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon))
{
/*
Set PDF render geometry.
*/
(void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+.15g%+.15g",
hires_bounds.x2-bounds.x1,hires_bounds.y2-hires_bounds.y1,
hires_bounds.x1,hires_bounds.y1);
(void) SetImageProperty(image,"pdf:HiResBoundingBox",geometry);
page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)*
image->x_resolution/delta.x)-0.5);
page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)*
image->y_resolution/delta.y)-0.5);
}
fitPage=MagickFalse;
option=GetImageOption(image_info,"pdf:fit-page");
if (option != (char *) NULL)
{
char
*geometry;
MagickStatusType
flags;
geometry=GetPageGeometry(option);
flags=ParseMetaGeometry(geometry,&page.x,&page.y,&page.width,
&page.height);
if (flags == NoValue)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidGeometry","`%s'",option);
image=DestroyImage(image);
return((Image *) NULL);
}
page.width=(size_t) ceil((double) (page.width*image->x_resolution/delta.x)
-0.5);
page.height=(size_t) ceil((double) (page.height*image->y_resolution/
delta.y) -0.5);
geometry=DestroyString(geometry);
fitPage=MagickTrue;
}
(void) CloseBlob(image);
if ((fabs(angle) == 90.0) || (fabs(angle) == 270.0))
{
size_t
swap;
swap=page.width;
page.width=page.height;
page.height=swap;
}
if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse)
cmyk=MagickFalse;
/*
Create Ghostscript control file.
*/
file=AcquireUniqueFileResource(postscript_filename);
if (file == -1)
{
ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
image_info->filename);
image=DestroyImage(image);
return((Image *) NULL);
}
count=write(file," ",1);
file=close(file)-1;
/*
Render Postscript with the Ghostscript delegate.
*/
if (image_info->monochrome != MagickFalse)
delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception);
else
if (cmyk != MagickFalse)
delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception);
else
delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception);
if (delegate_info == (const DelegateInfo *) NULL)
{
(void) RelinquishUniqueFileResource(postscript_filename);
image=DestroyImage(image);
return((Image *) NULL);
}
density=AcquireString("");
options=AcquireString("");
(void) FormatLocaleString(density,MaxTextExtent,"%gx%g",image->x_resolution,
image->y_resolution);
if ((image_info->page != (char *) NULL) || (fitPage != MagickFalse))
(void) FormatLocaleString(options,MaxTextExtent,"-g%.20gx%.20g ",(double)
page.width,(double) page.height);
if (fitPage != MagickFalse)
(void) ConcatenateMagickString(options,"-dPSFitPage ",MaxTextExtent);
if (cmyk != MagickFalse)
(void) ConcatenateMagickString(options,"-dUseCIEColor ",MaxTextExtent);
if (cropbox != MagickFalse)
(void) ConcatenateMagickString(options,"-dUseCropBox ",MaxTextExtent);
if (trimbox != MagickFalse)
(void) ConcatenateMagickString(options,"-dUseTrimBox ",MaxTextExtent);
if (stop_on_error != MagickFalse)
(void) ConcatenateMagickString(options,"-dPDFSTOPONERROR ",MaxTextExtent);
option=GetImageOption(image_info,"authenticate");
if (option != (char *) NULL)
{
char
passphrase[MaxTextExtent];
(void) FormatLocaleString(passphrase,MaxTextExtent,
"'-sPDFPassword=%s' ",option);
(void) ConcatenateMagickString(options,passphrase,MaxTextExtent);
}
read_info=CloneImageInfo(image_info);
*read_info->magick='\0';
if (read_info->number_scenes != 0)
{
char
pages[MaxTextExtent];
(void) FormatLocaleString(pages,MaxTextExtent,"-dFirstPage=%.20g "
"-dLastPage=%.20g",(double) read_info->scene+1,(double)
(read_info->scene+read_info->number_scenes));
(void) ConcatenateMagickString(options,pages,MaxTextExtent);
read_info->number_scenes=0;
if (read_info->scenes != (char *) NULL)
*read_info->scenes='\0';
}
(void) CopyMagickString(filename,read_info->filename,MaxTextExtent);
(void) AcquireUniqueFilename(filename);
(void) RelinquishUniqueFileResource(filename);
(void) ConcatenateMagickString(filename,"%d",MaxTextExtent);
(void) FormatLocaleString(command,MaxTextExtent,
GetDelegateCommands(delegate_info),
read_info->antialias != MagickFalse ? 4 : 1,
read_info->antialias != MagickFalse ? 4 : 1,density,options,filename,
postscript_filename,input_filename);
options=DestroyString(options);
density=DestroyString(density);
*message='\0';
status=InvokePDFDelegate(read_info->verbose,command,message,exception);
(void) RelinquishUniqueFileResource(postscript_filename);
(void) RelinquishUniqueFileResource(input_filename);
pdf_image=(Image *) NULL;
if (status == MagickFalse)
for (i=1; ; i++)
{
(void) InterpretImageFilename(image_info,image,filename,(int) i,
read_info->filename);
if (IsPDFRendered(read_info->filename) == MagickFalse)
break;
(void) RelinquishUniqueFileResource(read_info->filename);
}
else
for (i=1; ; i++)
{
(void) InterpretImageFilename(image_info,image,filename,(int) i,
read_info->filename);
if (IsPDFRendered(read_info->filename) == MagickFalse)
break;
read_info->blob=NULL;
read_info->length=0;
next=ReadImage(read_info,exception);
(void) RelinquishUniqueFileResource(read_info->filename);
if (next == (Image *) NULL)
break;
AppendImageToList(&pdf_image,next);
}
read_info=DestroyImageInfo(read_info);
if (pdf_image == (Image *) NULL)
{
if (*message != '\0')
(void) ThrowMagickException(exception,GetMagickModule(),DelegateError,
"PDFDelegateFailed","`%s'",message);
image=DestroyImage(image);
return((Image *) NULL);
}
if (LocaleCompare(pdf_image->magick,"BMP") == 0)
{
Image
*cmyk_image;
cmyk_image=ConsolidateCMYKImages(pdf_image,exception);
if (cmyk_image != (Image *) NULL)
{
pdf_image=DestroyImageList(pdf_image);
pdf_image=cmyk_image;
}
}
if (image_info->number_scenes != 0)
{
Image
*clone_image;
register ssize_t
i;
/*
Add place holder images to meet the subimage specification requirement.
*/
for (i=0; i < (ssize_t) image_info->scene; i++)
{
clone_image=CloneImage(pdf_image,1,1,MagickTrue,exception);
if (clone_image != (Image *) NULL)
PrependImageToList(&pdf_image,clone_image);
}
}
do
{
(void) CopyMagickString(pdf_image->filename,filename,MaxTextExtent);
(void) CopyMagickString(pdf_image->magick,image->magick,MaxTextExtent);
pdf_image->page=page;
(void) CloneImageProfiles(pdf_image,image);
(void) CloneImageProperties(pdf_image,image);
next=SyncNextImageInList(pdf_image);
if (next != (Image *) NULL)
pdf_image=next;
} while (next != (Image *) NULL);
image=DestroyImage(image);
scene=0;
for (next=GetFirstImageInList(pdf_image); next != (Image *) NULL; )
{
next->scene=scene++;
next=GetNextImageInList(next);
}
return(GetFirstImageInList(pdf_image));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,275 |
libarchive | a550daeecf6bc689ade371349892ea17b5b97c77 | parse_device(dev_t *pdev, struct archive *a, char *val)
{
#define MAX_PACK_ARGS 3
unsigned long numbers[MAX_PACK_ARGS];
char *p, *dev;
int argc;
pack_t *pack;
dev_t result;
const char *error = NULL;
memset(pdev, 0, sizeof(*pdev));
if ((dev = strchr(val, ',')) != NULL) {
/*
* Device's major/minor are given in a specified format.
* Decode and pack it accordingly.
*/
*dev++ = '\0';
if ((pack = pack_find(val)) == NULL) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown format `%s'", val);
return ARCHIVE_WARN;
}
argc = 0;
while ((p = la_strsep(&dev, ",")) != NULL) {
if (*p == '\0') {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Missing number");
return ARCHIVE_WARN;
}
numbers[argc++] = (unsigned long)mtree_atol(&p);
if (argc > MAX_PACK_ARGS) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Too many arguments");
return ARCHIVE_WARN;
}
}
if (argc < 2) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Not enough arguments");
return ARCHIVE_WARN;
}
result = (*pack)(argc, numbers, &error);
if (error != NULL) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"%s", error);
return ARCHIVE_WARN;
}
} else {
/* file system raw value. */
result = (dev_t)mtree_atol(&val);
}
*pdev = result;
return ARCHIVE_OK;
#undef MAX_PACK_ARGS
}
| 1 | CVE-2016-4301 | 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,245 |
ImageMagick | 0f6fc2d5bf8f500820c3dbcf0d23ee14f2d9f734 | MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count,
const size_t quantum)
{
MemoryInfo
*memory_info;
size_t
length;
length=count*quantum;
if ((count == 0) || (quantum != (length/count)))
{
errno=ENOMEM;
return((MemoryInfo *) NULL);
}
memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1,
sizeof(*memory_info)));
if (memory_info == (MemoryInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(memory_info,0,sizeof(*memory_info));
memory_info->length=length;
memory_info->signature=MagickSignature;
if (AcquireMagickResource(MemoryResource,length) != MagickFalse)
{
memory_info->blob=AcquireAlignedMemory(1,length);
if (memory_info->blob != NULL)
memory_info->type=AlignedVirtualMemory;
else
RelinquishMagickResource(MemoryResource,length);
}
if ((memory_info->blob == NULL) &&
(AcquireMagickResource(MapResource,length) != MagickFalse))
{
/*
Heap memory failed, try anonymous memory mapping.
*/
memory_info->blob=MapBlob(-1,IOMode,0,length);
if (memory_info->blob != NULL)
memory_info->type=MapVirtualMemory;
else
RelinquishMagickResource(MapResource,length);
}
if (memory_info->blob == NULL)
{
int
file;
/*
Anonymous memory mapping failed, try file-backed memory mapping.
*/
file=AcquireUniqueFileResource(memory_info->filename);
if (file != -1)
{
if ((lseek(file,length-1,SEEK_SET) >= 0) && (write(file,"",1) == 1))
{
memory_info->blob=MapBlob(file,IOMode,0,length);
if (memory_info->blob != NULL)
{
memory_info->type=MapVirtualMemory;
(void) AcquireMagickResource(MapResource,length);
}
}
(void) close(file);
}
}
if (memory_info->blob == NULL)
{
memory_info->blob=AcquireMagickMemory(length);
if (memory_info->blob != NULL)
memory_info->type=UnalignedVirtualMemory;
}
if (memory_info->blob == NULL)
memory_info=RelinquishVirtualMemory(memory_info);
return(memory_info);
}
| 1 | CVE-2015-8896 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 5,064 |
linux | ae6650163c66a7eff1acd6eb8b0f752dcfa8eba5 | static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
{
int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
return sprintf(buf, "%s\n", autoclear ? "1" : "0");
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,873 |
ghostscript | 937ccd17ac65935633b2ebc06cb7089b91e17e6b | static void gx_ttfReader__Read(ttfReader *self, void *p, int n)
{
gx_ttfReader *r = (gx_ttfReader *)self;
const byte *q;
if (!r->error) {
if (r->extra_glyph_index != -1) {
q = r->glyph_data.bits.data + r->pos;
r->error = (r->glyph_data.bits.size - r->pos < n ?
gs_note_error(gs_error_invalidfont) : 0);
if (r->error == 0)
memcpy(p, q, n);
unsigned int cnt;
for (cnt = 0; cnt < (uint)n; cnt += r->error) {
r->error = r->pfont->data.string_proc(r->pfont, (ulong)r->pos + cnt, (ulong)n - cnt, &q);
if (r->error < 0)
break;
else if ( r->error == 0) {
memcpy((char *)p + cnt, q, n - cnt);
break;
} else {
memcpy((char *)p + cnt, q, r->error);
}
}
}
}
if (r->error) {
memset(p, 0, n);
return;
}
r->pos += n;
}
| 1 | CVE-2017-9727 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 6,817 |
sqlite | 57f7ece78410a8aae86aa4625fb7556897db384c | static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
if( ALWAYS(z!=0) ){
double value;
sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
if( negateFlag ) value = -value;
sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,728 |
Bento4 | 41cad602709436628f07b4c4f64e9ff7a611f687 | AP4_DataAtom::AP4_DataAtom(const AP4_MetaData::Value& value) :
AP4_Atom(AP4_ATOM_TYPE_DATA, AP4_ATOM_HEADER_SIZE),
m_DataType(DATA_TYPE_BINARY)
{
AP4_MemoryByteStream* memory = new AP4_MemoryByteStream();
AP4_Size payload_size = 8;
m_Source = memory;
switch (value.GetType()) {
case AP4_MetaData::Value::TYPE_STRING_UTF_8: {
m_DataType = DATA_TYPE_STRING_UTF_8;
AP4_String string_value = value.ToString();
if (string_value.GetLength()) {
memory->Write(string_value.GetChars(), string_value.GetLength());
}
payload_size += string_value.GetLength();
break;
}
case AP4_MetaData::Value::TYPE_INT_08_BE: {
m_DataType = DATA_TYPE_SIGNED_INT_BE;
AP4_UI08 int_value = (AP4_UI08)value.ToInteger();
memory->Write(&int_value, 1);
payload_size += 1;
break;
}
case AP4_MetaData::Value::TYPE_INT_16_BE: {
m_DataType = DATA_TYPE_SIGNED_INT_BE;
AP4_UI16 int_value = (AP4_UI16)value.ToInteger();
memory->Write(&int_value, 2);
payload_size += 2;
break;
}
case AP4_MetaData::Value::TYPE_INT_32_BE: {
m_DataType = DATA_TYPE_SIGNED_INT_BE;
AP4_UI32 int_value = (AP4_UI32)value.ToInteger();
memory->Write(&int_value, 4);
payload_size += 4;
break;
}
case AP4_MetaData::Value::TYPE_JPEG:
m_DataType = DATA_TYPE_JPEG;
// FALLTHROUGH
case AP4_MetaData::Value::TYPE_GIF:
if (m_DataType == DATA_TYPE_BINARY) m_DataType = DATA_TYPE_GIF;
// FALLTHROUGH
case AP4_MetaData::Value::TYPE_BINARY: {
AP4_DataBuffer buffer;
value.ToBytes(buffer);
if (buffer.GetDataSize()) {
memory->Write(buffer.GetData(), buffer.GetDataSize());
}
payload_size += buffer.GetDataSize();
break;
}
default:
break;
}
const AP4_String& language = value.GetLanguage();
if (language == "en") {
m_DataLang = LANGUAGE_ENGLISH;
} else {
// default
m_DataLang = LANGUAGE_ENGLISH;
}
m_Size32 += payload_size;
} | 1 | CVE-2017-14641 | 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. | 9,878 |
wget | 59b920874daa565a1323ffa1e756e80493190686 | schemes_are_similar_p (enum url_scheme a, enum url_scheme b)
{
if (a == b)
return true;
#ifdef HAVE_SSL
if ((a == SCHEME_HTTP && b == SCHEME_HTTPS)
|| (a == SCHEME_HTTPS && b == SCHEME_HTTP))
return true;
#endif
return false;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,602 |
linux | 574823bfab82d9d8fa47f422778043fbb4b4f50e | static int mincore_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
spinlock_t *ptl;
struct vm_area_struct *vma = walk->vma;
pte_t *ptep;
unsigned char *vec = walk->private;
int nr = (end - addr) >> PAGE_SHIFT;
ptl = pmd_trans_huge_lock(pmd, vma);
if (ptl) {
memset(vec, 1, nr);
spin_unlock(ptl);
goto out;
}
if (pmd_trans_unstable(pmd)) {
__mincore_unmapped_range(addr, end, vma, vec);
goto out;
}
ptep = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
for (; addr != end; ptep++, addr += PAGE_SIZE) {
pte_t pte = *ptep;
if (pte_none(pte))
__mincore_unmapped_range(addr, addr + PAGE_SIZE,
vma, vec);
else if (pte_present(pte))
*vec = 1;
else { /* pte is a swap entry */
swp_entry_t entry = pte_to_swp_entry(pte);
if (non_swap_entry(entry)) {
/*
* migration or hwpoison entries are always
* uptodate
*/
*vec = 1;
} else {
#ifdef CONFIG_SWAP
*vec = mincore_page(swap_address_space(entry),
swp_offset(entry));
#else
WARN_ON(1);
*vec = 1;
#endif
}
}
vec++;
}
pte_unmap_unlock(ptep - 1, ptl);
out:
walk->private += nr;
cond_resched();
return 0;
}
| 1 | CVE-2019-5489 | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. |
Phase: Architecture and Design
Strategy: Separation of Privilege
Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area.
Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges. | 7,025 |
Chrome | 2aec794f26098c7a361c27d7c8f57119631cca8a | ExtensionDevToolsClientHost::ExtensionDevToolsClientHost(
Profile* profile,
DevToolsAgentHost* agent_host,
const std::string& extension_id,
const std::string& extension_name,
const Debuggee& debuggee)
: profile_(profile),
agent_host_(agent_host),
extension_id_(extension_id),
last_request_id_(0),
infobar_(nullptr),
detach_reason_(api::debugger::DETACH_REASON_TARGET_CLOSED),
extension_registry_observer_(this) {
CopyDebuggee(&debuggee_, debuggee);
g_attached_client_hosts.Get().insert(this);
extension_registry_observer_.Add(ExtensionRegistry::Get(profile_));
registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
content::NotificationService::AllSources());
agent_host_->AttachClient(this);
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
::switches::kSilentDebuggerExtensionAPI)) {
return;
}
const Extension* extension =
ExtensionRegistry::Get(profile)->enabled_extensions().GetByID(
extension_id);
if (extension && Manifest::IsPolicyLocation(extension->location()))
return;
infobar_ = ExtensionDevToolsInfoBar::Create(
extension_id, extension_name, this,
base::Bind(&ExtensionDevToolsClientHost::InfoBarDismissed,
base::Unretained(this)));
}
| 1 | CVE-2018-6140 | 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,314 |
matio | 651a8e28099edb5fbb9e4e1d4d3238848f446c9a | Mat_VarWrite4(mat_t *mat,matvar_t *matvar)
{
typedef struct {
mat_int32_t type;
mat_int32_t mrows;
mat_int32_t ncols;
mat_int32_t imagf;
mat_int32_t namelen;
} Fmatrix;
mat_int32_t nelems = 1, i;
Fmatrix x;
if ( NULL == mat || NULL == matvar || NULL == matvar->name || matvar->rank != 2 )
return -1;
switch ( matvar->data_type ) {
case MAT_T_DOUBLE:
x.type = 0;
break;
case MAT_T_SINGLE:
x.type = 10;
break;
case MAT_T_INT32:
x.type = 20;
break;
case MAT_T_INT16:
x.type = 30;
break;
case MAT_T_UINT16:
x.type = 40;
break;
case MAT_T_UINT8:
x.type = 50;
break;
default:
return 2;
}
#if defined(__GLIBC__)
#if (__BYTE_ORDER == __LITTLE_ENDIAN)
#elif (__BYTE_ORDER == __BIG_ENDIAN)
x.type += 1000;
#else
return -1;
#endif
#elif defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN)
x.type += 1000;
#elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)
#elif defined(__sparc) || defined(__sparc__) || defined(_POWER) || defined(__powerpc__) || \
defined(__ppc__) || defined(__hpux) || defined(_MIPSEB) || defined(_POWER) || defined(__s390__)
x.type += 1000;
#elif defined(__i386__) || defined(__alpha__) || defined(__ia64) || defined(__ia64__) || \
defined(_M_IX86) || defined(_M_IA64) || defined(_M_ALPHA) || defined(__amd64) || \
defined(__amd64__) || defined(_M_AMD64) || defined(__x86_64) || defined(__x86_64__) || \
defined(_M_X64) || defined(__bfin__)
#else
return -1;
#endif
x.namelen = (mat_int32_t)strlen(matvar->name) + 1;
/* FIXME: SEEK_END is not Guaranteed by the C standard */
(void)fseek((FILE*)mat->fp,0,SEEK_END); /* Always write at end of file */
switch ( matvar->class_type ) {
case MAT_C_CHAR:
x.type++;
/* Fall through */
case MAT_C_DOUBLE:
case MAT_C_SINGLE:
case MAT_C_INT32:
case MAT_C_INT16:
case MAT_C_UINT16:
case MAT_C_UINT8:
for ( i = 0; i < matvar->rank; i++ ) {
mat_int32_t dim;
dim = (mat_int32_t)matvar->dims[i];
nelems *= dim;
}
x.mrows = (mat_int32_t)matvar->dims[0];
x.ncols = (mat_int32_t)matvar->dims[1];
x.imagf = matvar->isComplex ? 1 : 0;
fwrite(&x, sizeof(Fmatrix), 1, (FILE*)mat->fp);
fwrite(matvar->name, sizeof(char), x.namelen, (FILE*)mat->fp);
if ( matvar->isComplex ) {
mat_complex_split_t *complex_data;
complex_data = (mat_complex_split_t*)matvar->data;
fwrite(complex_data->Re, matvar->data_size, nelems, (FILE*)mat->fp);
fwrite(complex_data->Im, matvar->data_size, nelems, (FILE*)mat->fp);
}
else {
fwrite(matvar->data, matvar->data_size, nelems, (FILE*)mat->fp);
}
break;
case MAT_C_SPARSE:
{
mat_sparse_t* sparse;
double tmp;
int j;
size_t stride = Mat_SizeOf(matvar->data_type);
#if !defined(EXTENDED_SPARSE)
if ( MAT_T_DOUBLE != matvar->data_type )
break;
#endif
sparse = (mat_sparse_t*)matvar->data;
x.type += 2;
x.mrows = sparse->njc > 0 ? sparse->jc[sparse->njc - 1] + 1 : 1;
x.ncols = matvar->isComplex ? 4 : 3;
x.imagf = 0;
fwrite(&x, sizeof(Fmatrix), 1, (FILE*)mat->fp);
fwrite(matvar->name, sizeof(char), x.namelen, (FILE*)mat->fp);
for ( i = 0; i < sparse->njc - 1; i++ ) {
for ( j = sparse->jc[i];
j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) {
tmp = sparse->ir[j] + 1;
fwrite(&tmp, sizeof(double), 1, (FILE*)mat->fp);
}
}
tmp = (double)matvar->dims[0];
fwrite(&tmp, sizeof(double), 1, (FILE*)mat->fp);
for ( i = 0; i < sparse->njc - 1; i++ ) {
for ( j = sparse->jc[i];
j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) {
tmp = i + 1;
fwrite(&tmp, sizeof(double), 1, (FILE*)mat->fp);
}
}
tmp = (double)matvar->dims[1];
fwrite(&tmp, sizeof(double), 1, (FILE*)mat->fp);
tmp = 0.;
if ( matvar->isComplex ) {
mat_complex_split_t *complex_data;
char* re, *im;
complex_data = (mat_complex_split_t*)sparse->data;
re = (char*)complex_data->Re;
im = (char*)complex_data->Im;
for ( i = 0; i < sparse->njc - 1; i++ ) {
for ( j = sparse->jc[i];
j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) {
fwrite(re + j*stride, stride, 1, (FILE*)mat->fp);
}
}
fwrite(&tmp, stride, 1, (FILE*)mat->fp);
for ( i = 0; i < sparse->njc - 1; i++ ) {
for ( j = sparse->jc[i];
j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) {
fwrite(im + j*stride, stride, 1, (FILE*)mat->fp);
}
}
} else {
char *data = (char*)sparse->data;
for ( i = 0; i < sparse->njc - 1; i++ ) {
for ( j = sparse->jc[i];
j < sparse->jc[i + 1] && j < sparse->ndata; j++ ) {
fwrite(data + j*stride, stride, 1, (FILE*)mat->fp);
}
}
}
fwrite(&tmp, stride, 1, (FILE*)mat->fp);
break;
}
default:
break;
}
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,217 |
qemu | 6d4b9e55fc625514a38d27cff4b9933f617fa7dc | static CURLState *curl_init_state(BDRVCURLState *s)
{
CURLState *state = NULL;
int i, j;
do {
for (i=0; i<CURL_NUM_STATES; i++) {
for (j=0; j<CURL_NUM_ACB; j++)
if (s->states[i].acb[j])
continue;
if (s->states[i].in_use)
continue;
state = &s->states[i];
state->in_use = 1;
break;
}
if (!state) {
g_usleep(100);
curl_multi_do(s);
}
} while(!state);
if (state->curl)
goto has_curl;
state->curl = curl_easy_init();
if (!state->curl)
return NULL;
curl_easy_setopt(state->curl, CURLOPT_URL, s->url);
curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, 5);
curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION, (void *)curl_read_cb);
curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);
curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);
curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);
curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);
curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);
/* Restrict supported protocols to avoid security issues in the more
* obscure protocols. For example, do not allow POP3/SMTP/IMAP see
* CVE-2013-0249.
*
* Restricting protocols is only supported from 7.19.4 upwards.
*/
#if LIBCURL_VERSION_NUM >= 0x071304
curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);
curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);
#endif
#ifdef DEBUG_VERBOSE
curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);
#endif
has_curl:
state->s = s;
return state;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,718 |
gpac | 04dbf08bff4d61948bab80c3f9096ecc60c7f302 | static s32 avc_parse_slice(GF_BitStream *bs, AVCState *avc, Bool svc_idr_flag, AVCSliceInfo *si)
{
s32 pps_id, num_ref_idx_l0_active_minus1 = 0, num_ref_idx_l1_active_minus1 = 0;
/*s->current_picture.reference= h->nal_ref_idc != 0;*/
gf_bs_read_ue_log(bs, "first_mb_in_slice");
si->slice_type = gf_bs_read_ue_log(bs, "slice_type");
if (si->slice_type > 9) return -1;
pps_id = gf_bs_read_ue_log(bs, "pps_id");
if ((pps_id<0) || (pps_id > 255)) return -1;
si->pps = &avc->pps[pps_id];
if (!si->pps->slice_group_count) return -2;
si->sps = &avc->sps[si->pps->sps_id];
if (!si->sps->log2_max_frame_num) return -2;
avc->sps_active_idx = si->pps->sps_id;
avc->pps_active_idx = pps_id;
si->frame_num = gf_bs_read_int_log(bs, si->sps->log2_max_frame_num, "frame_num");
si->field_pic_flag = 0;
si->bottom_field_flag = 0;
if (!si->sps->frame_mbs_only_flag) {
si->field_pic_flag = gf_bs_read_int_log(bs, 1, "field_pic_flag");
if (si->field_pic_flag)
si->bottom_field_flag = gf_bs_read_int_log(bs, 1, "bottom_field_flag");
}
if ((si->nal_unit_type == GF_AVC_NALU_IDR_SLICE) || svc_idr_flag)
si->idr_pic_id = gf_bs_read_ue_log(bs, "idr_pic_id");
if (si->sps->poc_type == 0) {
si->poc_lsb = gf_bs_read_int_log(bs, si->sps->log2_max_poc_lsb, "poc_lsb");
if (si->pps->pic_order_present && !si->field_pic_flag) {
si->delta_poc_bottom = gf_bs_read_se_log(bs, "poc_lsb");
}
}
else if ((si->sps->poc_type == 1) && !si->sps->delta_pic_order_always_zero_flag) {
si->delta_poc[0] = gf_bs_read_se_log(bs, "delta_poc0");
if ((si->pps->pic_order_present == 1) && !si->field_pic_flag)
si->delta_poc[1] = gf_bs_read_se_log(bs, "delta_poc1");
}
if (si->pps->redundant_pic_cnt_present) {
si->redundant_pic_cnt = gf_bs_read_ue_log(bs, "redundant_pic_cnt");
}
if (si->slice_type % 5 == GF_AVC_TYPE_B) {
gf_bs_read_int_log(bs, 1, "direct_spatial_mv_pred_flag");
}
num_ref_idx_l0_active_minus1 = si->pps->num_ref_idx_l0_default_active_minus1;
num_ref_idx_l1_active_minus1 = si->pps->num_ref_idx_l1_default_active_minus1;
if (si->slice_type % 5 == GF_AVC_TYPE_P || si->slice_type % 5 == GF_AVC_TYPE_SP || si->slice_type % 5 == GF_AVC_TYPE_B) {
Bool num_ref_idx_active_override_flag = gf_bs_read_int_log(bs, 1, "num_ref_idx_active_override_flag");
if (num_ref_idx_active_override_flag) {
num_ref_idx_l0_active_minus1 = gf_bs_read_ue_log(bs, "num_ref_idx_l0_active_minus1");
if (si->slice_type % 5 == GF_AVC_TYPE_B) {
num_ref_idx_l1_active_minus1 = gf_bs_read_ue_log(bs, "num_ref_idx_l1_active_minus1");
}
}
}
if (si->nal_unit_type == 20 || si->nal_unit_type == 21) {
//ref_pic_list_mvc_modification(); /* specified in Annex H */
GF_LOG(GF_LOG_ERROR, GF_LOG_CODING, ("[avc-h264] unimplemented ref_pic_list_mvc_modification() in slide header\n"));
assert(0);
return -1;
}
else {
ref_pic_list_modification(bs, si->slice_type);
}
if ((si->pps->weighted_pred_flag && (si->slice_type % 5 == GF_AVC_TYPE_P || si->slice_type % 5 == GF_AVC_TYPE_SP))
|| (si->pps->weighted_bipred_idc == 1 && si->slice_type % 5 == GF_AVC_TYPE_B)) {
pred_weight_table(bs, si->slice_type, si->sps->ChromaArrayType, num_ref_idx_l0_active_minus1, num_ref_idx_l1_active_minus1);
}
if (si->nal_ref_idc != 0) {
dec_ref_pic_marking(bs, (si->nal_unit_type == GF_AVC_NALU_IDR_SLICE));
}
if (si->pps->entropy_coding_mode_flag && si->slice_type % 5 != GF_AVC_TYPE_I && si->slice_type % 5 != GF_AVC_TYPE_SI) {
gf_bs_read_ue_log(bs, "cabac_init_idc");
}
/*slice_qp_delta = */gf_bs_read_se(bs);
if (si->slice_type % 5 == GF_AVC_TYPE_SP || si->slice_type % 5 == GF_AVC_TYPE_SI) {
if (si->slice_type % 5 == GF_AVC_TYPE_SP) {
gf_bs_read_int_log(bs, 1, "sp_for_switch_flag");
}
gf_bs_read_se_log(bs, "slice_qs_delta");
}
if (si->pps->deblocking_filter_control_present_flag) {
if (gf_bs_read_ue_log(bs, "disable_deblocking_filter_idc") != 1) {
gf_bs_read_se_log(bs, "slice_alpha_c0_offset_div2");
gf_bs_read_se_log(bs, "slice_beta_offset_div2");
}
}
if (si->pps->slice_group_count > 1 && si->pps->mb_slice_group_map_type >= 3 && si->pps->mb_slice_group_map_type <= 5) {
gf_bs_read_int_log(bs, (u32)ceil(log1p((si->pps->pic_size_in_map_units_minus1 + 1) / (si->pps->slice_group_change_rate_minus1 + 1) ) / log(2)), "slice_group_change_cycle");
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,433 |
sudo | b301b46b79c6e2a76d530fa36d05992e74952ee8 | display_usage(int (*output)(const char *))
{
struct sudo_lbuf lbuf;
char *uvec[6];
int i, ulen;
/*
* Use usage vectors appropriate to the progname.
*/
if (strcmp(getprogname(), "sudoedit") == 0) {
uvec[0] = &SUDO_USAGE5[3];
uvec[1] = NULL;
} else {
uvec[0] = SUDO_USAGE1;
uvec[1] = SUDO_USAGE2;
uvec[2] = SUDO_USAGE3;
uvec[3] = SUDO_USAGE4;
uvec[4] = SUDO_USAGE5;
uvec[5] = NULL;
}
/*
* Print usage and wrap lines as needed, depending on the
* tty width.
*/
ulen = (int)strlen(getprogname()) + 8;
sudo_lbuf_init(&lbuf, output, ulen, NULL,
user_details.ts_cols);
for (i = 0; uvec[i] != NULL; i++) {
sudo_lbuf_append(&lbuf, "usage: %s%s", getprogname(), uvec[i]);
sudo_lbuf_print(&lbuf);
}
sudo_lbuf_destroy(&lbuf);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,316 |
qemu | 670e56d3ed2918b3861d9216f2c0540d9e9ae0d5 | static int mptsas_process_scsi_io_request(MPTSASState *s,
MPIMsgSCSIIORequest *scsi_io,
hwaddr addr)
{
MPTSASRequest *req;
MPIMsgSCSIIOReply reply;
SCSIDevice *sdev;
int status;
mptsas_fix_scsi_io_endianness(scsi_io);
trace_mptsas_process_scsi_io_request(s, scsi_io->Bus, scsi_io->TargetID,
scsi_io->LUN[1], scsi_io->DataLength);
status = mptsas_scsi_device_find(s, scsi_io->Bus, scsi_io->TargetID,
scsi_io->LUN, &sdev);
if (status) {
goto bad;
}
req = g_new(MPTSASRequest, 1);
QTAILQ_INSERT_TAIL(&s->pending, req, next);
req->scsi_io = *scsi_io;
req->dev = s;
status = mptsas_build_sgl(s, req, addr);
if (status) {
goto free_bad;
}
if (req->qsg.size < scsi_io->DataLength) {
trace_mptsas_sgl_overflow(s, scsi_io->MsgContext, scsi_io->DataLength,
req->qsg.size);
status = MPI_IOCSTATUS_INVALID_SGL;
goto free_bad;
}
req->sreq = scsi_req_new(sdev, scsi_io->MsgContext,
scsi_io->LUN[1], scsi_io->CDB, req);
if (req->sreq->cmd.xfer > scsi_io->DataLength) {
goto overrun;
}
switch (scsi_io->Control & MPI_SCSIIO_CONTROL_DATADIRECTION_MASK) {
case MPI_SCSIIO_CONTROL_NODATATRANSFER:
if (req->sreq->cmd.mode != SCSI_XFER_NONE) {
goto overrun;
}
break;
case MPI_SCSIIO_CONTROL_WRITE:
if (req->sreq->cmd.mode != SCSI_XFER_TO_DEV) {
goto overrun;
}
break;
case MPI_SCSIIO_CONTROL_READ:
if (req->sreq->cmd.mode != SCSI_XFER_FROM_DEV) {
goto overrun;
}
break;
}
if (scsi_req_enqueue(req->sreq)) {
scsi_req_continue(req->sreq);
}
return 0;
overrun:
trace_mptsas_scsi_overflow(s, scsi_io->MsgContext, req->sreq->cmd.xfer,
scsi_io->DataLength);
status = MPI_IOCSTATUS_SCSI_DATA_OVERRUN;
free_bad:
mptsas_free_request(req);
bad:
memset(&reply, 0, sizeof(reply));
reply.TargetID = scsi_io->TargetID;
reply.Bus = scsi_io->Bus;
reply.MsgLength = sizeof(reply) / 4;
reply.Function = scsi_io->Function;
reply.CDBLength = scsi_io->CDBLength;
reply.SenseBufferLength = scsi_io->SenseBufferLength;
reply.MsgContext = scsi_io->MsgContext;
reply.SCSIState = MPI_SCSI_STATE_NO_SCSI_STATUS;
reply.IOCStatus = status;
mptsas_fix_scsi_io_reply_endianness(&reply);
mptsas_reply(s, (MPIDefaultReply *)&reply);
return 0;
}
| 1 | CVE-2016-7423 | 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,659 |
Android | 50270d98e26fa18b20ca88216c3526667b724ba7 | OMX_ERRORTYPE SoftMPEG4Encoder::initEncParams() {
CHECK(mHandle != NULL);
memset(mHandle, 0, sizeof(tagvideoEncControls));
CHECK(mEncParams != NULL);
memset(mEncParams, 0, sizeof(tagvideoEncOptions));
if (!PVGetDefaultEncOption(mEncParams, 0)) {
ALOGE("Failed to get default encoding parameters");
return OMX_ErrorUndefined;
}
mEncParams->encMode = mEncodeMode;
mEncParams->encWidth[0] = mWidth;
mEncParams->encHeight[0] = mHeight;
mEncParams->encFrameRate[0] = mFramerate >> 16; // mFramerate is in Q16 format
mEncParams->rcType = VBR_1;
mEncParams->vbvDelay = 5.0f;
mEncParams->profile_level = CORE_PROFILE_LEVEL2;
mEncParams->packetSize = 32;
mEncParams->rvlcEnable = PV_OFF;
mEncParams->numLayers = 1;
mEncParams->timeIncRes = 1000;
mEncParams->tickPerSrc = ((int64_t)mEncParams->timeIncRes << 16) / mFramerate;
mEncParams->bitRate[0] = mBitrate;
mEncParams->iQuant[0] = 15;
mEncParams->pQuant[0] = 12;
mEncParams->quantType[0] = 0;
mEncParams->noFrameSkipped = PV_OFF;
if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) {
free(mInputFrameData);
mInputFrameData =
(uint8_t *) malloc((mWidth * mHeight * 3 ) >> 1);
CHECK(mInputFrameData != NULL);
}
if (mWidth % 16 != 0 || mHeight % 16 != 0) {
ALOGE("Video frame size %dx%d must be a multiple of 16",
mWidth, mHeight);
return OMX_ErrorBadParameter;
}
if (mIDRFrameRefreshIntervalInSec < 0) {
mEncParams->intraPeriod = -1;
} else if (mIDRFrameRefreshIntervalInSec == 0) {
mEncParams->intraPeriod = 1; // All I frames
} else {
mEncParams->intraPeriod =
(mIDRFrameRefreshIntervalInSec * mFramerate) >> 16;
}
mEncParams->numIntraMB = 0;
mEncParams->sceneDetect = PV_ON;
mEncParams->searchRange = 16;
mEncParams->mv8x8Enable = PV_OFF;
mEncParams->gobHeaderInterval = 0;
mEncParams->useACPred = PV_ON;
mEncParams->intraDCVlcTh = 0;
return OMX_ErrorNone;
}
| 1 | CVE-2016-0803 | 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). | 511 |
qemu | c689b4f1bac352dcfd6ecb9a1d45337de0f1de67 | static bool ga_create_file(const char *path)
{
int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
if (fd == -1) {
g_warning("unable to open/create file %s: %s", path, strerror(errno));
return false;
}
close(fd);
return true;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,607 |
linux-2.6 | 214b7049a7929f03bbd2786aaef04b8b79db34e2 | void __inode_dir_notify(struct inode *inode, unsigned long event)
{
struct dnotify_struct * dn;
struct dnotify_struct **prev;
struct fown_struct * fown;
int changed = 0;
spin_lock(&inode->i_lock);
prev = &inode->i_dnotify;
while ((dn = *prev) != NULL) {
if ((dn->dn_mask & event) == 0) {
prev = &dn->dn_next;
continue;
}
fown = &dn->dn_filp->f_owner;
send_sigio(fown, dn->dn_fd, POLL_MSG);
if (dn->dn_mask & DN_MULTISHOT)
prev = &dn->dn_next;
else {
*prev = dn->dn_next;
changed = 1;
kmem_cache_free(dn_cache, dn);
}
}
if (changed)
redo_inode_mask(inode);
spin_unlock(&inode->i_lock);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,501 |
linux-2.6 | 9ef1d4c7c7aca1cd436612b6ca785b726ffb8ed8 | static struct Qdisc *qdisc_leaf(struct Qdisc *p, u32 classid)
{
unsigned long cl;
struct Qdisc *leaf;
struct Qdisc_class_ops *cops = p->ops->cl_ops;
if (cops == NULL)
return NULL;
cl = cops->get(p, classid);
if (cl == 0)
return NULL;
leaf = cops->leaf(p, cl);
cops->put(p, cl);
return leaf;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,130 |
envoy | 9371333230b1a6e1be2eccf4868771e11af6253a | PathMatcherImpl(const RequirementRule& rule)
: BaseMatcherImpl(rule), path_(rule.match().path()),
path_matcher_(Matchers::PathMatcher::createExact(path_, !case_sensitive_)) {} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,164 |
libtiff | 5ad9d8016fbb60109302d558f7edb2cb2a3bb8e3 | DECLAREwriteFunc(writeBufferToContigTiles)
{
uint32 imagew = TIFFScanlineSize(out);
uint32 tilew = TIFFTileRowSize(out);
int iskew = imagew - tilew;
tsize_t tilesize = TIFFTileSize(out);
tdata_t obuf;
uint8* bufp = (uint8*) buf;
uint32 tl, tw;
uint32 row;
(void) spp;
obuf = _TIFFmalloc(TIFFTileSize(out));
if (obuf == NULL)
return 0;
_TIFFmemset(obuf, 0, tilesize);
(void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
(void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
for (row = 0; row < imagelength; row += tilelength) {
uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl;
uint32 colb = 0;
uint32 col;
for (col = 0; col < imagewidth; col += tw) {
/*
* Tile is clipped horizontally. Calculate
* visible portion and skewing factors.
*/
if (colb + tilew > imagew) {
uint32 width = imagew - colb;
int oskew = tilew - width;
cpStripToTile(obuf, bufp + colb, nrow, width,
oskew, oskew + iskew);
} else
cpStripToTile(obuf, bufp + colb, nrow, tilew,
0, iskew);
if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write tile at %lu %lu",
(unsigned long) col,
(unsigned long) row);
_TIFFfree(obuf);
return 0;
}
colb += tilew;
}
bufp += nrow * imagew;
}
_TIFFfree(obuf);
return 1;
}
| 1 | CVE-2016-9540 | 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). | 7,450 |
libvncserver | 85a778c0e45e87e35ee7199f1f25020648e8b812 | static void FillRectangle(rfbClient* client, int x, int y, int w, int h, uint32_t colour) {
int i,j;
#define FILL_RECT(BPP) \
for(j=y*client->width;j<(y+h)*client->width;j+=client->width) \
for(i=x;i<x+w;i++) \
((uint##BPP##_t*)client->frameBuffer)[j+i]=colour;
switch(client->format.bitsPerPixel) {
case 8: FILL_RECT(8); break;
case 16: FILL_RECT(16); break;
case 32: FILL_RECT(32); break;
default:
rfbClientLog("Unsupported bitsPerPixel: %d\n",client->format.bitsPerPixel);
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,907 |
php-src | abd159cce48f3e34f08e4751c568e09677d5ec9c | PHPAPI PHP_FUNCTION(fread)
{
zval *arg1;
long len;
php_stream *stream;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &arg1, &len) == FAILURE) {
RETURN_FALSE;
}
PHP_STREAM_TO_ZVAL(stream, &arg1);
if (len <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
if (len > INT_MAX) {
/* string length is int in 5.x so we can not read more than int */
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be no more than %d", INT_MAX);
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(len + 1);
Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,066 |
FreeRDP | 09b9d4f1994a674c4ec85b4947aa656eda1aed8a | BOOL gdi_register_graphics(rdpGraphics* graphics)
{
rdpBitmap bitmap;
rdpGlyph glyph;
bitmap.size = sizeof(gdiBitmap);
bitmap.New = gdi_Bitmap_New;
bitmap.Free = gdi_Bitmap_Free;
bitmap.Paint = gdi_Bitmap_Paint;
bitmap.Decompress = gdi_Bitmap_Decompress;
bitmap.SetSurface = gdi_Bitmap_SetSurface;
graphics_register_bitmap(graphics, &bitmap);
glyph.size = sizeof(gdiGlyph);
glyph.New = gdi_Glyph_New;
glyph.Free = gdi_Glyph_Free;
glyph.Draw = gdi_Glyph_Draw;
glyph.BeginDraw = gdi_Glyph_BeginDraw;
glyph.EndDraw = gdi_Glyph_EndDraw;
glyph.SetBounds = gdi_Glyph_SetBounds;
graphics_register_glyph(graphics, &glyph);
return TRUE;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,203 |
Chrome | d0947db40187f4708c58e64cbd6013faf9eddeed | xmlParseNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNameComplex++;
#endif
/*
* Handler for more complex cases
*/
GROW;
c = CUR_CHAR(l);
if ((ctxt->options & XML_PARSE_OLD10) == 0) {
/*
* Use the new checks of production [4] [4a] amd [5] of the
* Update 5 of XML-1.0
*/
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
(c == '_') || (c == ':') ||
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))))) {
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
while ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
(((c >= 'a') && (c <= 'z')) ||
((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9')) || /* !start */
(c == '_') || (c == ':') ||
(c == '-') || (c == '.') || (c == 0xB7) || /* !start */
((c >= 0xC0) && (c <= 0xD6)) ||
((c >= 0xD8) && (c <= 0xF6)) ||
((c >= 0xF8) && (c <= 0x2FF)) ||
((c >= 0x300) && (c <= 0x36F)) || /* !start */
((c >= 0x370) && (c <= 0x37D)) ||
((c >= 0x37F) && (c <= 0x1FFF)) ||
((c >= 0x200C) && (c <= 0x200D)) ||
((c >= 0x203F) && (c <= 0x2040)) || /* !start */
((c >= 0x2070) && (c <= 0x218F)) ||
((c >= 0x2C00) && (c <= 0x2FEF)) ||
((c >= 0x3001) && (c <= 0xD7FF)) ||
((c >= 0xF900) && (c <= 0xFDCF)) ||
((c >= 0xFDF0) && (c <= 0xFFFD)) ||
((c >= 0x10000) && (c <= 0xEFFFF))
)) {
if (count++ > 100) {
count = 0;
GROW;
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
} else {
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!IS_LETTER(c) && (c != '_') &&
(c != ':'))) {
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
((IS_LETTER(c)) || (IS_DIGIT(c)) ||
(c == '.') || (c == '-') ||
(c == '_') || (c == ':') ||
(IS_COMBINING(c)) ||
(IS_EXTENDER(c)))) {
if (count++ > 100) {
count = 0;
GROW;
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
}
if ((*ctxt->input->cur == '\n') && (ctxt->input->cur[-1] == '\r'))
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len));
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
}
| 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). | 1,941 |
ImageMagick | e14fd0a2801f73bdc123baf4fbab97dec55919eb | static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
has_merged_image,
skip_layers;
MagickOffsetType
offset;
MagickSizeType
length;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
ssize_t
count;
unsigned char
*data;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read image header.
*/
image->endian=MSBEndian;
count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
psd_info.version=ReadBlobMSBShort(image);
if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
((psd_info.version != 1) && (psd_info.version != 2)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlob(image,6,psd_info.reserved);
psd_info.channels=ReadBlobMSBShort(image);
if (psd_info.channels > MaxPSDChannels)
ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
psd_info.rows=ReadBlobMSBLong(image);
psd_info.columns=ReadBlobMSBLong(image);
if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
(psd_info.columns > 30000)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.depth=ReadBlobMSBShort(image);
if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.mode=ReadBlobMSBShort(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
(double) psd_info.columns,(double) psd_info.rows,(double)
psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
psd_info.mode));
/*
Initialize image.
*/
image->depth=psd_info.depth;
image->columns=psd_info.columns;
image->rows=psd_info.rows;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (SetImageBackgroundColor(image,exception) == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (psd_info.mode == LabMode)
SetImageColorspace(image,LabColorspace,exception);
if (psd_info.mode == CMYKMode)
{
SetImageColorspace(image,CMYKColorspace,exception);
image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait :
UndefinedPixelTrait;
}
else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == DuotoneMode))
{
status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536,
exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait :
UndefinedPixelTrait;
}
else
image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait :
UndefinedPixelTrait;
/*
Read PSD raster colormap only present for indexed and duotone images.
*/
length=ReadBlobMSBLong(image);
if (length != 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading colormap");
if (psd_info.mode == DuotoneMode)
{
/*
Duotone image data; the format of this data is undocumented.
*/
data=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,(size_t) length,data);
data=(unsigned char *) RelinquishMagickMemory(data);
}
else
{
size_t
number_colors;
/*
Read PSD raster colormap.
*/
number_colors=length/3;
if (number_colors > 65536)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->alpha_trait=UndefinedPixelTrait;
}
}
has_merged_image=MagickTrue;
length=ReadBlobMSBLong(image);
if (length != 0)
{
unsigned char
*blocks;
/*
Image resources block.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading image resource blocks - %.20g bytes",(double)
((MagickOffsetType) length));
blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*blocks));
if (blocks == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,blocks);
if ((count != (ssize_t) length) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image,
exception);
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
}
/*
Layer and mask block.
*/
length=GetPSDSize(&psd_info,image);
if (length == 8)
{
length=ReadBlobMSBLong(image);
length=ReadBlobMSBLong(image);
}
offset=TellBlob(image);
skip_layers=MagickFalse;
if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
(has_merged_image != MagickFalse))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read composite only");
skip_layers=MagickTrue;
}
if (length == 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has no layers");
}
else
{
if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=
MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Skip the rest of the layer and mask information.
*/
SeekBlob(image,offset+length,SEEK_SET);
}
/*
If we are only "pinging" the image, then we're done - so return.
*/
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read the precombined layer, present for PSD < 4 compatibility.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading the precombined layer");
if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1))
has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image,
&psd_info,exception);
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) &&
(length != 0))
{
SeekBlob(image,offset,SEEK_SET);
status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception);
if (status != MagickTrue)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
}
if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1))
{
Image
*merged;
SetImageAlphaChannel(image,TransparentAlphaChannel,exception);
image->background_color.alpha=TransparentAlpha;
image->background_color.alpha_trait=BlendPixelTrait;
merged=MergeImageLayers(image,FlattenLayer,exception);
ReplaceImageInList(&image,merged);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,491 |
openssl | 77c77f0a1b9f15b869ca3342186dfbedd1119d0e | int ssl3_do_change_cipher_spec(SSL *s)
{
int i;
const char *sender;
int slen;
if (s->state & SSL_ST_ACCEPT)
i = SSL3_CHANGE_CIPHER_SERVER_READ;
else
i = SSL3_CHANGE_CIPHER_CLIENT_READ;
if (s->s3->tmp.key_block == NULL) {
if (s->session == NULL || s->session->master_key_length == 0) {
/* might happen if dtls1_read_bytes() calls this */
SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,
SSL_R_CCS_RECEIVED_EARLY);
return (0);
}
s->session->cipher = s->s3->tmp.new_cipher;
if (!s->method->ssl3_enc->setup_key_block(s))
return (0);
}
if (!s->method->ssl3_enc->change_cipher_state(s, i))
return (0);
/*
* we have to record the message digest at this point so we can get it
* before we read the finished message
*/
if (s->state & SSL_ST_CONNECT) {
sender = s->method->ssl3_enc->server_finished_label;
slen = s->method->ssl3_enc->server_finished_label_len;
} else {
sender = s->method->ssl3_enc->client_finished_label;
slen = s->method->ssl3_enc->client_finished_label_len;
}
i = s->method->ssl3_enc->final_finish_mac(s,
sender, slen,
s->s3->tmp.peer_finish_md);
if (i == 0) {
SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
return 0;
}
s->s3->tmp.peer_finish_md_len = i;
return (1);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,761 |
ImageMagick | 1e59b29e520d2beab73e8c78aacd5f1c0d76196d | static MagickBooleanType InsertRow(int bpp,unsigned char *p,ssize_t y,
Image *image)
{
ExceptionInfo
*exception;
int
bit;
ssize_t
x;
register PixelPacket
*q;
IndexPacket
index;
register IndexPacket
*indexes;
exception=(&image->exception);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickFalse);
indexes=GetAuthenticIndexQueue(image);
switch (bpp)
{
case 1: /* Convert bitmap scanline. */
{
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(indexes+x+bit,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (ssize_t) (image->columns % 8); bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(indexes+x+bit,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
p++;
}
break;
}
case 2: /* Convert PseudoColor scanline. */
{
if ((image->storage_class != PseudoClass) ||
(indexes == (IndexPacket *) NULL))
break;
for (x=0; x < ((ssize_t) image->columns-3); x+=4)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p) & 0x3);
SetPixelIndex(indexes+x+1,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
p++;
}
if ((image->columns % 4) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
if ((image->columns % 4) > 1)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
if ((image->columns % 4) > 2)
{
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
}
p++;
}
break;
}
case 4: /* Convert PseudoColor scanline. */
{
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p) & 0x0f);
SetPixelIndex(indexes+x+1,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
if ((image->columns % 2) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
break;
}
case 8: /* Convert PseudoColor scanline. */
{
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
}
break;
case 24: /* Convert DirectColor scanline. */
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
q++;
}
break;
}
if (!SyncAuthenticPixels(image,exception))
return(MagickFalse);
return(MagickTrue);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,032 |
WavPack | 26cb47f99d481ad9b93eeff80d26e6b63bbd7e15 | int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config)
{
int64_t total_samples = 0, infilesize;
Wave64ChunkHeader chunk_header;
Wave64FileHeader filehdr;
WaveHeader WaveHeader;
uint32_t bcount;
infilesize = DoGetFileSize (infile);
memcpy (&filehdr, fourcc, 4);
if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) ||
bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) ||
memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) {
error_line ("%s is not a valid .W64 file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
#if 1 // this might be a little too picky...
WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat);
if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) &&
filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) {
error_line ("%s is not a valid .W64 file!", infilename);
return WAVPACK_SOFT_ERROR;
}
#endif
while (1) {
if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) ||
bcount != sizeof (Wave64ChunkHeader)) {
error_line ("%s is not a valid .W64 file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat);
chunk_header.ckSize -= sizeof (chunk_header);
if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) {
int supported = TRUE, format;
chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L;
if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) ||
!DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) ||
bcount != chunk_header.ckSize) {
error_line ("%s is not a valid .W64 file!", infilename);
return WAVPACK_SOFT_ERROR;
}
else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) {
error_line ("%s", WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat);
if (debug_logging_mode) {
error_line ("format tag size = %d", chunk_header.ckSize);
error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d",
WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample);
error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d",
WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond);
if (chunk_header.ckSize > 16)
error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize,
WaveHeader.ValidBitsPerSample);
if (chunk_header.ckSize > 20)
error_line ("ChannelMask = %x, SubFormat = %d",
WaveHeader.ChannelMask, WaveHeader.SubFormat);
}
if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2)
config->qmode |= QMODE_ADOBE_MODE;
format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ?
WaveHeader.SubFormat : WaveHeader.FormatTag;
config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ?
WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample;
if (format != 1 && format != 3)
supported = FALSE;
if (format == 3 && config->bits_per_sample != 32)
supported = FALSE;
if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 ||
WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 ||
WaveHeader.BlockAlign % WaveHeader.NumChannels)
supported = FALSE;
if (config->bits_per_sample < 1 || config->bits_per_sample > 32)
supported = FALSE;
if (!supported) {
error_line ("%s is an unsupported .W64 format!", infilename);
return WAVPACK_SOFT_ERROR;
}
if (chunk_header.ckSize < 40) {
if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) {
if (WaveHeader.NumChannels <= 2)
config->channel_mask = 0x5 - WaveHeader.NumChannels;
else if (WaveHeader.NumChannels <= 18)
config->channel_mask = (1 << WaveHeader.NumChannels) - 1;
else
config->channel_mask = 0x3ffff;
}
}
else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) {
error_line ("this W64 file already has channel order information!");
return WAVPACK_SOFT_ERROR;
}
else if (WaveHeader.ChannelMask)
config->channel_mask = WaveHeader.ChannelMask;
if (format == 3)
config->float_norm_exp = 127;
else if ((config->qmode & QMODE_ADOBE_MODE) &&
WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) {
if (WaveHeader.BitsPerSample == 24)
config->float_norm_exp = 127 + 23;
else if (WaveHeader.BitsPerSample == 32)
config->float_norm_exp = 127 + 15;
}
if (debug_logging_mode) {
if (config->float_norm_exp == 127)
error_line ("data format: normalized 32-bit floating point");
else
error_line ("data format: %d-bit integers stored in %d byte(s)",
config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels);
}
}
else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop
if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk
error_line ("%s is not a valid .W64 file!", infilename);
return WAVPACK_SOFT_ERROR;
}
if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) {
config->qmode |= QMODE_IGNORE_LENGTH;
if (infilesize && DoGetFilePosition (infile) != -1)
total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign;
else
total_samples = -1;
}
else {
if (infilesize && infilesize - chunk_header.ckSize > 16777216) {
error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
total_samples = chunk_header.ckSize / WaveHeader.BlockAlign;
if (!total_samples) {
error_line ("this .W64 file has no audio samples, probably is corrupt!");
return WAVPACK_SOFT_ERROR;
}
if (total_samples > MAX_WAVPACK_SAMPLES) {
error_line ("%s has too many samples for WavPack!", infilename);
return WAVPACK_SOFT_ERROR;
}
}
config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels;
config->num_channels = WaveHeader.NumChannels;
config->sample_rate = WaveHeader.SampleRate;
break;
}
else { // just copy unknown chunks to output file
int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L;
char *buff;
if (bytes_to_copy < 0 || bytes_to_copy > 4194304) {
error_line ("%s is not a valid .W64 file!", infilename);
return WAVPACK_SOFT_ERROR;
}
buff = malloc (bytes_to_copy);
if (debug_logging_mode)
error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes",
chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2],
chunk_header.ckID [3], chunk_header.ckSize);
if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) ||
bcount != bytes_to_copy ||
(!(config->qmode & QMODE_NO_STORE_WRAPPER) &&
!WavpackAddWrapper (wpc, buff, bytes_to_copy))) {
error_line ("%s", WavpackGetErrorMessage (wpc));
free (buff);
return WAVPACK_SOFT_ERROR;
}
free (buff);
}
}
if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) {
error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc));
return WAVPACK_SOFT_ERROR;
}
return WAVPACK_NO_ERROR;
}
| 1 | CVE-2018-10537 | 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). | 9,877 |
Android | 014b01706cc64dc9c2ad94a96f62e07c058d0b5d | void close_all_sockets(atransport* t) {
asocket* s;
/* this is a little gross, but since s->close() *will* modify
** the list out from under you, your options are limited.
*/
std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
restart:
for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
if (s->transport == t || (s->peer && s->peer->transport == t)) {
local_socket_close(s);
goto restart;
}
}
}
| 1 | CVE-2016-3890 | 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 | 7,849 |
systemd | cb31827d62066a04b02111df3052949fda4b6888 | enum nss_status _nss_mymachines_getpwnam_r(
const char *name,
struct passwd *pwd,
char *buffer, size_t buflen,
int *errnop) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
const char *p, *e, *machine;
uint32_t mapped;
uid_t uid;
size_t l;
int r;
assert(name);
assert(pwd);
p = startswith(name, "vu-");
if (!p)
goto not_found;
e = strrchr(p, '-');
if (!e || e == p)
goto not_found;
r = parse_uid(e + 1, &uid);
if (r < 0)
goto not_found;
machine = strndupa(p, e - p);
if (!machine_name_is_valid(machine))
goto not_found;
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"MapFromMachineUser",
&error,
&reply,
"su",
machine, (uint32_t) uid);
if (r < 0) {
if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_USER_MAPPING))
goto not_found;
goto fail;
}
r = sd_bus_message_read(reply, "u", &mapped);
if (r < 0)
goto fail;
l = strlen(name);
if (buflen < l+1) {
*errnop = ENOMEM;
return NSS_STATUS_TRYAGAIN;
}
memcpy(buffer, name, l+1);
pwd->pw_name = buffer;
pwd->pw_uid = mapped;
pwd->pw_gid = 65534; /* nobody */
pwd->pw_gecos = buffer;
pwd->pw_passwd = (char*) "*"; /* locked */
pwd->pw_dir = (char*) "/";
pwd->pw_shell = (char*) "/sbin/nologin";
*errnop = 0;
return NSS_STATUS_SUCCESS;
not_found:
*errnop = 0;
return NSS_STATUS_NOTFOUND;
fail:
*errnop = -r;
return NSS_STATUS_UNAVAIL;
}
| 1 | CVE-2015-7510 | 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). | 4,001 |
linux | 212925802454672e6cd2949a727f5e2c1377bf06 | bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
{
if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
return false;
if (is_data_mapping(flags) &&
mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
/* Workaround for Valgrind */
if (rlimit(RLIMIT_DATA) == 0 &&
mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
return true;
if (!ignore_rlimit_data) {
pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits or use boot option ignore_rlimit_data.\n",
current->comm, current->pid,
(mm->data_vm + npages) << PAGE_SHIFT,
rlimit(RLIMIT_DATA));
return false;
}
}
return true;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,261 |
Chrome | 47ae3dfdee9a0796a079cd4eadf2f75b34f257ae | ChooserContextBase::GetGrantedObjects(const GURL& requesting_origin,
const GURL& embedding_origin) {
DCHECK_EQ(requesting_origin, requesting_origin.GetOrigin());
DCHECK_EQ(embedding_origin, embedding_origin.GetOrigin());
if (!CanRequestObjectPermission(requesting_origin, embedding_origin))
return {};
std::vector<std::unique_ptr<Object>> results;
content_settings::SettingInfo info;
std::unique_ptr<base::DictionaryValue> setting =
GetWebsiteSetting(requesting_origin, embedding_origin, &info);
std::unique_ptr<base::Value> objects;
if (!setting->Remove(kObjectListKey, &objects))
return results;
std::unique_ptr<base::ListValue> object_list =
base::ListValue::From(std::move(objects));
if (!object_list)
return results;
for (auto& object : *object_list) {
base::DictionaryValue* object_dict;
if (object.GetAsDictionary(&object_dict) && IsValidObject(*object_dict)) {
results.push_back(std::make_unique<Object>(
requesting_origin, embedding_origin, object_dict, info.source,
host_content_settings_map_->is_incognito()));
}
}
return results;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,450 |
Chrome | 297ae873b471a46929ea39697b121c0b411434ee | bool CustomButton::OnMousePressed(const ui::MouseEvent& event) {
if (state_ != STATE_DISABLED) {
if (ShouldEnterPushedState(event) && HitTestPoint(event.location()))
SetState(STATE_PRESSED);
if (request_focus_on_press_)
RequestFocus();
if (IsTriggerableEvent(event) && notify_action_ == NOTIFY_ON_PRESS) {
NotifyClick(event);
}
}
return true;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,596 |
openssh-portable | d4697fe9a28dab7255c60433e4dd23cf7fce8a8b | mm_answer_pam_init_ctx(int sock, Buffer *m)
{
debug3("%s", __func__);
authctxt->user = buffer_get_string(m, NULL);
sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
sshpam_authok = NULL;
buffer_clear(m);
if (sshpam_ctxt != NULL) {
monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
buffer_put_int(m, 1);
} else {
buffer_put_int(m, 0);
}
mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
return (0);
}
| 1 | CVE-2015-6563 | 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,000 |
savannah | 1fc9c95ec144499e69dc8ec76dbe07799d7d82cd | check_retry_on_http_error (const int statcode)
{
const char *tok = opt.retry_on_http_error;
while (tok && *tok)
{
if (atoi (tok) == statcode)
return true;
if ((tok = strchr (tok, ',')))
++tok;
}
return false;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,638 |
Chrome | 9fd9d629fcf836bb0d6210015d33a299cf6bca34 | UserCloudPolicyManagerChromeOS::UserCloudPolicyManagerChromeOS(
scoped_ptr<CloudPolicyStore> store,
scoped_ptr<CloudExternalDataManager> external_data_manager,
const base::FilePath& component_policy_cache_path,
bool wait_for_policy_fetch,
base::TimeDelta initial_policy_fetch_timeout,
const scoped_refptr<base::SequencedTaskRunner>& task_runner,
const scoped_refptr<base::SequencedTaskRunner>& file_task_runner,
const scoped_refptr<base::SequencedTaskRunner>& io_task_runner)
: CloudPolicyManager(
PolicyNamespaceKey(dm_protocol::kChromeUserPolicyType, std::string()),
store.get(),
task_runner,
file_task_runner,
io_task_runner),
store_(store.Pass()),
external_data_manager_(external_data_manager.Pass()),
component_policy_cache_path_(component_policy_cache_path),
wait_for_policy_fetch_(wait_for_policy_fetch),
policy_fetch_timeout_(false, false) {
time_init_started_ = base::Time::Now();
if (wait_for_policy_fetch_) {
policy_fetch_timeout_.Start(
FROM_HERE,
initial_policy_fetch_timeout,
base::Bind(&UserCloudPolicyManagerChromeOS::OnBlockingFetchTimeout,
base::Unretained(this)));
}
}
| 1 | CVE-2013-6623 | 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,804 |
ghostscript | 661e8d8fb8248c38d67958beda32f3a5876d0c3f | zgetdefaultdevice(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
const gx_device *dev;
dev = gs_getdefaultlibdevice(imemory);
if (dev == 0) /* couldn't find a default device */
return_error(gs_error_unknownerror);
push(1);
make_tav(op, t_device, avm_foreign | a_readonly, pdevice,
(gx_device *) dev);
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,748 |
cJSON | 94df772485c92866ca417d92137747b2e3b0a917 | static const char *parse_string(cJSON *item,const char *str,const char **ep)
{
const char *ptr=str+1,*end_ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2;
if (*str!='\"') {*ep=str;return 0;} /* not a string! */
while (*end_ptr!='\"' && *end_ptr && ++len) if (*end_ptr++ == '\\') end_ptr++; /* Skip escaped quotes. */
out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */
if (!out) return 0;
item->valuestring=out; /* assign here so out will be deleted during cJSON_Delete() later */
item->type=cJSON_String;
ptr=str+1;ptr2=out;
while (ptr < end_ptr)
{
if (*ptr!='\\') *ptr2++=*ptr++;
else
{
ptr++;
switch (*ptr)
{
case 'b': *ptr2++='\b'; break;
case 'f': *ptr2++='\f'; break;
case 'n': *ptr2++='\n'; break;
case 'r': *ptr2++='\r'; break;
case 't': *ptr2++='\t'; break;
case 'u': /* transcode utf16 to utf8. */
uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */
if (ptr >= end_ptr) {*ep=str;return 0;} /* invalid */
if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) {*ep=str;return 0;} /* check for invalid. */
if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */
{
if (ptr+6 > end_ptr) {*ep=str;return 0;} /* invalid */
if (ptr[1]!='\\' || ptr[2]!='u') {*ep=str;return 0;} /* missing second-half of surrogate. */
uc2=parse_hex4(ptr+3);ptr+=6;
if (uc2<0xDC00 || uc2>0xDFFF) {*ep=str;return 0;} /* invalid second-half of surrogate. */
uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF));
}
len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len;
switch (len) {
case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 1: *--ptr2 =(uc | firstByteMark[len]);
}
ptr2+=len;
break;
default: *ptr2++=*ptr; break;
}
ptr++;
}
}
*ptr2=0;
if (*ptr=='\"') ptr++;
return ptr;
}
| 1 | CVE-2016-10749 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 8,310 |
php-src | 5b597a2e5b28e2d5a52fc1be13f425f08f47cb62 | static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC)
{
zend_hash_destroy(&pglobals->ht_rc);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,820 |
vim | 1889f499a4f248cd84e0e0bf6d0d820016774494 | compile_nested_function(exarg_T *eap, cctx_T *cctx, garray_T *lines_to_free)
{
int is_global = *eap->arg == 'g' && eap->arg[1] == ':';
char_u *name_start = eap->arg;
char_u *name_end = to_name_end(eap->arg, TRUE);
int off;
char_u *func_name;
char_u *lambda_name;
ufunc_T *ufunc;
int r = FAIL;
compiletype_T compile_type;
isn_T *funcref_isn = NULL;
if (eap->forceit)
{
emsg(_(e_cannot_use_bang_with_nested_def));
return NULL;
}
if (*name_start == '/')
{
name_end = skip_regexp(name_start + 1, '/', TRUE);
if (*name_end == '/')
++name_end;
set_nextcmd(eap, name_end);
}
if (name_end == name_start || *skipwhite(name_end) != '(')
{
if (!ends_excmd2(name_start, name_end))
{
if (*skipwhite(name_end) == '.')
semsg(_(e_cannot_define_dict_func_in_vim9_script_str),
eap->cmd);
else
semsg(_(e_invalid_command_str), eap->cmd);
return NULL;
}
// "def" or "def Name": list functions
if (generate_DEF(cctx, name_start, name_end - name_start) == FAIL)
return NULL;
return eap->nextcmd == NULL ? (char_u *)"" : eap->nextcmd;
}
// Only g:Func() can use a namespace.
if (name_start[1] == ':' && !is_global)
{
semsg(_(e_namespace_not_supported_str), name_start);
return NULL;
}
if (cctx->ctx_skip != SKIP_YES
&& check_defined(name_start, name_end - name_start, cctx,
NULL, FALSE) == FAIL)
return NULL;
if (!ASCII_ISUPPER(is_global ? name_start[2] : name_start[0]))
{
semsg(_(e_function_name_must_start_with_capital_str), name_start);
return NULL;
}
eap->arg = name_end;
fill_exarg_from_cctx(eap, cctx);
eap->forceit = FALSE;
// We use the special <Lamba>99 name, but it's not really a lambda.
lambda_name = vim_strsave(get_lambda_name());
if (lambda_name == NULL)
return NULL;
// This may free the current line, make a copy of the name.
off = is_global ? 2 : 0;
func_name = vim_strnsave(name_start + off, name_end - name_start - off);
if (func_name == NULL)
{
r = FAIL;
goto theend;
}
ufunc = define_function(eap, lambda_name, lines_to_free);
if (ufunc == NULL)
{
r = eap->skip ? OK : FAIL;
goto theend;
}
if (eap->nextcmd != NULL)
{
semsg(_(e_text_found_after_str_str),
eap->cmdidx == CMD_def ? "enddef" : "endfunction", eap->nextcmd);
r = FAIL;
func_ptr_unref(ufunc);
goto theend;
}
// copy over the block scope IDs before compiling
if (!is_global && cctx->ctx_ufunc->uf_block_depth > 0)
{
int block_depth = cctx->ctx_ufunc->uf_block_depth;
ufunc->uf_block_ids = ALLOC_MULT(int, block_depth);
if (ufunc->uf_block_ids != NULL)
{
mch_memmove(ufunc->uf_block_ids, cctx->ctx_ufunc->uf_block_ids,
sizeof(int) * block_depth);
ufunc->uf_block_depth = block_depth;
}
}
// Define the funcref before compiling, so that it is found by any
// recursive call.
if (is_global)
{
r = generate_NEWFUNC(cctx, lambda_name, func_name);
func_name = NULL;
lambda_name = NULL;
}
else
{
// Define a local variable for the function reference.
lvar_T *lvar = reserve_local(cctx, func_name, name_end - name_start,
TRUE, ufunc->uf_func_type);
if (lvar == NULL)
goto theend;
if (generate_FUNCREF(cctx, ufunc, &funcref_isn) == FAIL)
goto theend;
r = generate_STORE(cctx, ISN_STORE, lvar->lv_idx, NULL);
}
compile_type = get_compile_type(ufunc);
#ifdef FEAT_PROFILE
// If the outer function is profiled, also compile the nested function for
// profiling.
if (cctx->ctx_compile_type == CT_PROFILE)
compile_type = CT_PROFILE;
#endif
if (func_needs_compiling(ufunc, compile_type)
&& compile_def_function(ufunc, TRUE, compile_type, cctx) == FAIL)
{
func_ptr_unref(ufunc);
goto theend;
}
#ifdef FEAT_PROFILE
// When the outer function is compiled for profiling, the nested function
// may be called without profiling. Compile it here in the right context.
if (compile_type == CT_PROFILE && func_needs_compiling(ufunc, CT_NONE))
compile_def_function(ufunc, FALSE, CT_NONE, cctx);
#endif
// If a FUNCREF instruction was generated, set the index after compiling.
if (funcref_isn != NULL && ufunc->uf_def_status == UF_COMPILED)
funcref_isn->isn_arg.funcref.fr_dfunc_idx = ufunc->uf_dfunc_idx;
theend:
vim_free(lambda_name);
vim_free(func_name);
return r == FAIL ? NULL : (char_u *)"";
} | 1 | CVE-2022-2862 | CWE-416 | Use After Free | The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
Phase: Architecture and Design
Strategy: Language Selection
Choose a language that provides automatic memory management.
Phase: Implementation
Strategy: Attack Surface Reduction
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.
Effectiveness: Defense in Depth
Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution. | 8,244 |
ImageMagick | 548701354191a3dda5cffc6d415374b35b01d0b9 | static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
FILE
*file;
Image
*image,
*next_image,
*pwp_image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
register Image
*p;
register ssize_t
i;
size_t
filesize,
length;
ssize_t
count;
unsigned char
magick[MagickPathExtent];
/*
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);
pwp_image=AcquireImage(image_info,exception);
image=pwp_image;
status=OpenBlob(image_info,pwp_image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return((Image *) NULL);
count=ReadBlob(pwp_image,5,magick);
if ((count != 5) || (LocaleNCompare((char *) magick,"SFW95",5) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
read_info=CloneImageInfo(image_info);
(void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL,
(void *) NULL);
SetImageInfoBlob(read_info,(void *) NULL,0);
unique_file=AcquireUniqueFileResource(read_info->filename);
for ( ; ; )
{
for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image))
{
for (i=0; i < 17; i++)
magick[i]=magick[i+1];
magick[17]=(unsigned char) c;
if (LocaleNCompare((char *) (magick+12),"SFW94A",6) == 0)
break;
}
if (c == EOF)
break;
if (LocaleNCompare((char *) (magick+12),"SFW94A",6) != 0)
{
(void) RelinquishUniqueFileResource(read_info->filename);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Dump SFW image to a temporary file.
*/
file=(FILE *) NULL;
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
(void) RelinquishUniqueFileResource(read_info->filename);
ThrowFileException(exception,FileOpenError,"UnableToWriteFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
length=fwrite("SFW94A",1,6,file);
(void) length;
filesize=65535UL*magick[2]+256L*magick[1]+magick[0];
for (i=0; i < (ssize_t) filesize; i++)
{
c=ReadBlobByte(pwp_image);
(void) fputc(c,file);
}
(void) fclose(file);
next_image=ReadImage(read_info,exception);
if (next_image == (Image *) NULL)
break;
(void) FormatLocaleString(next_image->filename,MagickPathExtent,
"slide_%02ld.sfw",(long) next_image->scene);
if (image == (Image *) NULL)
image=next_image;
else
{
/*
Link image into image list.
*/
for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ;
next_image->previous=p;
next_image->scene=p->scene+1;
p->next=next_image;
}
if (image_info->number_scenes != 0)
if (next_image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image),
GetBlobSize(pwp_image));
if (status == MagickFalse)
break;
}
if (unique_file != -1)
(void) close(unique_file);
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
if (EOFBlob(image) != MagickFalse)
{
char
*message;
message=GetExceptionMessage(errno);
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"UnexpectedEndOfFile","`%s': %s",image->filename,message);
message=DestroyString(message);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,718 |
Chrome | 20b65d00ca3d8696430e22efad7485366f8c3a21 | void NormalPageArena::VerifyMarking() {
#if DCHECK_IS_ON()
SetAllocationPoint(nullptr, 0);
for (NormalPage* page = static_cast<NormalPage*>(first_page_); page;
page = static_cast<NormalPage*>(page->Next()))
page->VerifyMarking();
#endif // DCHECK_IS_ON()
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,362 |
zstd | 3e5cdf1b6a85843e991d7d10f6a2567c15580da0 | static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)
{
static const U32 maxSrcLog = 23;
static const U32 maxSampleLog = 22;
size_t const srcBufferSize = (size_t)1<<maxSrcLog;
size_t const dstBufferSize = (size_t)1<<maxSampleLog;
size_t const cBufferSize = ZSTD_compressBound(dstBufferSize);
BYTE* cNoiseBuffer[5];
BYTE* const cBuffer = (BYTE*) malloc (cBufferSize);
BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize);
BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize);
ZSTD_CCtx* const refCtx = ZSTD_createCCtx();
ZSTD_CCtx* const ctx = ZSTD_createCCtx();
ZSTD_DCtx* const dctx = ZSTD_createDCtx();
U32 result = 0;
U32 testNb = 0;
U32 coreSeed = seed;
UTIL_time_t const startClock = UTIL_getTime();
U64 const maxClockSpan = maxDurationS * SEC_TO_MICRO;
int const cLevelLimiter = bigTests ? 3 : 2;
/* allocation */
cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4]
|| !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx,
"Not enough memory, fuzzer tests cancelled");
/* Create initial samples */
RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
/* catch up testNb */
for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed);
/* main test loop */
for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < maxClockSpan); testNb++ ) {
BYTE* srcBuffer; /* jumping pointer */
U32 lseed;
size_t sampleSize, maxTestSize, totalTestSize;
size_t cSize, totalCSize, totalGenSize;
U64 crcOrig;
BYTE* sampleBuffer;
const BYTE* dict;
size_t dictSize;
/* notification */
if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests); }
else { DISPLAYUPDATE(2, "\r%6u ", testNb); }
FUZ_rand(&coreSeed);
{ U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }
/* srcBuffer selection [0-4] */
{ U32 buffNb = FUZ_rand(&lseed) & 0x7F;
if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
else {
buffNb >>= 3;
if (buffNb & 7) {
const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
buffNb = tnb[buffNb >> 3];
} else {
const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
buffNb = tnb[buffNb >> 3];
} }
srcBuffer = cNoiseBuffer[buffNb];
}
/* select src segment */
sampleSize = FUZ_randomLength(&lseed, maxSampleLog);
/* create sample buffer (to catch read error with valgrind & sanitizers) */
sampleBuffer = (BYTE*)malloc(sampleSize);
CHECK(sampleBuffer==NULL, "not enough memory for sample buffer");
{ size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);
memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }
crcOrig = XXH64(sampleBuffer, sampleSize, 0);
/* compression tests */
{ int const cLevelPositive =
( FUZ_rand(&lseed) %
(ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )
+ 1;
int const cLevel = ((FUZ_rand(&lseed) & 15) == 3) ?
- (int)((FUZ_rand(&lseed) & 7) + 1) : /* test negative cLevel */
cLevelPositive;
DISPLAYLEVEL(5, "fuzzer t%u: Simple compression test (level %i) \n", testNb, cLevel);
cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);
CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize));
/* compression failure test : too small dest buffer */
if (cSize > 3) {
const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
const size_t tooSmallSize = cSize - missing;
const U32 endMark = 0x4DC2B1A9;
memcpy(dstBuffer+tooSmallSize, &endMark, 4);
{ size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);
CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (U32)tooSmallSize, (U32)cSize); }
{ U32 endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, 4);
CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow"); }
} }
/* frame header decompression test */
{ ZSTD_frameHeader zfh;
CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) );
CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect");
}
/* Decompressed size test */
{ unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);
CHECK(rSize != sampleSize, "decompressed size incorrect");
}
/* successful decompression test */
DISPLAYLEVEL(5, "fuzzer t%u: simple decompression test \n", testNb);
{ size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;
size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);
CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (U32)sampleSize, (U32)cSize);
{ U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);
CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (U32)findDiff(sampleBuffer, dstBuffer, sampleSize), (U32)sampleSize);
} }
free(sampleBuffer); /* no longer useful after this point */
/* truncated src decompression test */
DISPLAYLEVEL(5, "fuzzer t%u: decompression of truncated source \n", testNb);
{ size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
size_t const tooSmallSize = cSize - missing;
void* cBufferTooSmall = malloc(tooSmallSize); /* valgrind will catch read overflows */
CHECK(cBufferTooSmall == NULL, "not enough memory !");
memcpy(cBufferTooSmall, cBuffer, tooSmallSize);
{ size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);
CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); }
free(cBufferTooSmall);
}
/* too small dst decompression test */
DISPLAYLEVEL(5, "fuzzer t%u: decompress into too small dst buffer \n", testNb);
if (sampleSize > 3) {
size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
size_t const tooSmallSize = sampleSize - missing;
static const BYTE token = 0xA9;
dstBuffer[tooSmallSize] = token;
{ size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);
CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (U32)errorCode, (U32)tooSmallSize); }
CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow");
}
/* noisy src decompression test */
if (cSize > 6) {
/* insert noise into src */
{ U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));
size_t pos = 4; /* preserve magic number (too easy to detect) */
for (;;) {
/* keep some original src */
{ U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;
size_t const mask = (1<<nbBits) - 1;
size_t const skipLength = FUZ_rand(&lseed) & mask;
pos += skipLength;
}
if (pos >= cSize) break;
/* add noise */
{ U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;
U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
size_t const mask = (1<<nbBits) - 1;
size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1;
size_t const noiseLength = MIN(rNoiseLength, cSize-pos);
size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength);
memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength);
pos += noiseLength;
} } }
/* decompress noisy source */
DISPLAYLEVEL(5, "fuzzer t%u: decompress noisy source \n", testNb);
{ U32 const endMark = 0xA9B1C3D6;
memcpy(dstBuffer+sampleSize, &endMark, 4);
{ size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize);
/* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize),
"ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (U32)decompressResult, (U32)sampleSize);
}
{ U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);
CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow");
} } } /* noisy src decompression test */
/*===== Bufferless streaming compression test, scattered segments and dictionary =====*/
DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming compression test \n", testNb);
{ U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
int const cLevel = (FUZ_rand(&lseed) %
(ZSTD_maxCLevel() -
(MAX(testLog, dictLog) / cLevelLimiter))) +
1;
maxTestSize = FUZ_rLogLength(&lseed, testLog);
if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;
dictSize = FUZ_rLogLength(&lseed, dictLog); /* needed also for decompression */
dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));
DISPLAYLEVEL(6, "fuzzer t%u: Compressing up to <=%u bytes at level %i with dictionary size %u \n",
testNb, (U32)maxTestSize, cLevel, (U32)dictSize);
if (FUZ_rand(&lseed) & 0xF) {
CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );
} else {
ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,
!(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,
0 /*NodictID*/ }; /* note : since dictionary is fake, dictIDflag has no impact */
ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);
CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );
}
CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );
}
{ U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;
U32 n;
XXH64_state_t xxhState;
XXH64_reset(&xxhState, 0);
for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) {
size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog);
size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize);
if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break; /* avoid invalid dstBufferTooSmall */
if (totalTestSize+segmentSize > maxTestSize) break;
{ size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);
CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult));
cSize += compressResult;
}
XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);
memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);
totalTestSize += segmentSize;
}
{ size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);
CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult));
cSize += flushResult;
}
crcOrig = XXH64_digest(&xxhState);
}
/* streaming decompression test */
DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming decompression test \n", testNb);
/* ensure memory requirement is good enough (should always be true) */
{ ZSTD_frameHeader zfh;
CHECK( ZSTD_getFrameHeader(&zfh, cBuffer, ZSTD_frameHeaderSize_max),
"ZSTD_getFrameHeader(): error retrieving frame information");
{ size_t const roundBuffSize = ZSTD_decodingBufferSize_min(zfh.windowSize, zfh.frameContentSize);
CHECK_Z(roundBuffSize);
CHECK((roundBuffSize > totalTestSize) && (zfh.frameContentSize!=ZSTD_CONTENTSIZE_UNKNOWN),
"ZSTD_decodingBufferSize_min() requires more memory (%u) than necessary (%u)",
(U32)roundBuffSize, (U32)totalTestSize );
} }
if (dictSize<8) dictSize=0, dict=NULL; /* disable dictionary */
CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );
totalCSize = 0;
totalGenSize = 0;
while (totalCSize < cSize) {
size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);
size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);
CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize));
totalGenSize += genSize;
totalCSize += inSize;
}
CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded");
CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size")
CHECK (totalCSize != cSize, "compressed data should be fully read")
{ U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
CHECK(crcOrig != crcDest, "streaming decompressed data corrupted (pos %u / %u)",
(U32)findDiff(mirrorBuffer, dstBuffer, totalTestSize), (U32)totalTestSize);
}
} /* for ( ; (testNb <= nbTests) */
DISPLAY("\r%u fuzzer tests completed \n", testNb-1);
_cleanup:
ZSTD_freeCCtx(refCtx);
ZSTD_freeCCtx(ctx);
ZSTD_freeDCtx(dctx);
free(cNoiseBuffer[0]);
free(cNoiseBuffer[1]);
free(cNoiseBuffer[2]);
free(cNoiseBuffer[3]);
free(cNoiseBuffer[4]);
free(cBuffer);
free(dstBuffer);
free(mirrorBuffer);
return result;
_output_error:
result = 1;
goto _cleanup;
}
| 1 | CVE-2019-11922 | 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 | 2,597 |
Chrome | 0c14577c9905bd8161159ec7eaac810c594508d0 | gfx::NativeView OmniboxViewWin::GetRelativeWindowForNativeView(
gfx::NativeView edit_native_view) {
HWND ime_window = ImmGetDefaultIMEWnd(edit_native_view);
return ime_window ? ime_window : HWND_NOTOPMOST;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,795 |
linux | ee53664bda169f519ce3c6a22d378f0b946c8178 | static inline int pmd_numa(pmd_t pmd)
{
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,072 |
openssl | 0c27d793745c7837b13646302b6890a556b7017a | static int ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in,
BIGNUM **kinvp, BIGNUM **rp,
const unsigned char *dgst, int dlen)
{
BN_CTX *ctx = NULL;
BIGNUM *k = NULL, *r = NULL, *X = NULL;
const BIGNUM *order;
EC_POINT *tmp_point = NULL;
const EC_GROUP *group;
int ret = 0;
int order_bits;
if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL) {
ECerr(EC_F_ECDSA_SIGN_SETUP, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (!EC_KEY_can_sign(eckey)) {
ECerr(EC_F_ECDSA_SIGN_SETUP, EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING);
return 0;
}
if (ctx_in == NULL) {
if ((ctx = BN_CTX_new()) == NULL) {
ECerr(EC_F_ECDSA_SIGN_SETUP, ERR_R_MALLOC_FAILURE);
return 0;
}
} else
ctx = ctx_in;
k = BN_new(); /* this value is later returned in *kinvp */
r = BN_new(); /* this value is later returned in *rp */
X = BN_new();
if (k == NULL || r == NULL || X == NULL) {
ECerr(EC_F_ECDSA_SIGN_SETUP, ERR_R_MALLOC_FAILURE);
goto err;
}
if ((tmp_point = EC_POINT_new(group)) == NULL) {
ECerr(EC_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB);
goto err;
}
order = EC_GROUP_get0_order(group);
if (order == NULL) {
ECerr(EC_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB);
goto err;
}
/* Preallocate space */
order_bits = BN_num_bits(order);
if (!BN_set_bit(k, order_bits)
|| !BN_set_bit(r, order_bits)
|| !BN_set_bit(X, order_bits))
goto err;
do {
/* get random k */
do
if (dgst != NULL) {
if (!BN_generate_dsa_nonce
(k, order, EC_KEY_get0_private_key(eckey), dgst, dlen,
ctx)) {
ECerr(EC_F_ECDSA_SIGN_SETUP,
EC_R_RANDOM_NUMBER_GENERATION_FAILED);
goto err;
}
} else {
if (!BN_rand_range(k, order)) {
ECerr(EC_F_ECDSA_SIGN_SETUP,
EC_R_RANDOM_NUMBER_GENERATION_FAILED);
goto err;
}
}
while (BN_is_zero(k));
/*
* We do not want timing information to leak the length of k, so we
* compute G*k using an equivalent scalar of fixed bit-length.
*
* We unconditionally perform both of these additions to prevent a
* small timing information leakage. We then choose the sum that is
* one bit longer than the order. This guarantees the code
* path used in the constant time implementations elsewhere.
*
* TODO: revisit the BN_copy aiming for a memory access agnostic
* conditional copy.
*/
if (!BN_add(r, k, order)
|| !BN_add(X, r, order)
|| !BN_copy(k, BN_num_bits(r) > order_bits ? r : X))
goto err;
/* compute r the x-coordinate of generator * k */
if (!EC_POINT_mul(group, tmp_point, k, NULL, NULL, ctx)) {
ECerr(EC_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB);
goto err;
}
if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) ==
NID_X9_62_prime_field) {
if (!EC_POINT_get_affine_coordinates_GFp
(group, tmp_point, X, NULL, ctx)) {
ECerr(EC_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB);
goto err;
}
}
#ifndef OPENSSL_NO_EC2M
else { /* NID_X9_62_characteristic_two_field */
if (!EC_POINT_get_affine_coordinates_GF2m(group,
tmp_point, X, NULL,
ctx)) {
ECerr(EC_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB);
goto err;
}
}
#endif
if (!BN_nnmod(r, X, order, ctx)) {
ECerr(EC_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB);
goto err;
}
}
while (BN_is_zero(r));
/* compute the inverse of k */
if (EC_GROUP_get_mont_data(group) != NULL) {
/*
* We want inverse in constant time, therefore we utilize the fact
* order must be prime and use Fermats Little Theorem instead.
*/
if (!BN_set_word(X, 2)) {
ECerr(EC_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB);
goto err;
}
if (!BN_mod_sub(X, order, X, order, ctx)) {
ECerr(EC_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB);
goto err;
}
BN_set_flags(X, BN_FLG_CONSTTIME);
if (!BN_mod_exp_mont_consttime
(k, k, X, order, ctx, EC_GROUP_get_mont_data(group))) {
ECerr(EC_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB);
goto err;
}
} else {
if (!BN_mod_inverse(k, k, order, ctx)) {
ECerr(EC_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB);
goto err;
}
}
/* clear old values if necessary */
BN_clear_free(*rp);
BN_clear_free(*kinvp);
/* save the pre-computed values */
*rp = r;
*kinvp = k;
ret = 1;
err:
if (!ret) {
BN_clear_free(k);
BN_clear_free(r);
}
if (ctx != ctx_in)
BN_CTX_free(ctx);
EC_POINT_free(tmp_point);
BN_clear_free(X);
return (ret);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,606 |
linux | 99d825822eade8d827a1817357cbf3f889a552d6 | int get_rock_ridge_filename(struct iso_directory_record *de,
char *retname, struct inode *inode)
{
struct rock_state rs;
struct rock_ridge *rr;
int sig;
int retnamlen = 0;
int truncate = 0;
int ret = 0;
if (!ISOFS_SB(inode->i_sb)->s_rock)
return 0;
*retname = 0;
init_rock_state(&rs, inode);
setup_rock_ridge(de, inode, &rs);
repeat:
while (rs.len > 2) { /* There may be one byte for padding somewhere */
rr = (struct rock_ridge *)rs.chr;
/*
* Ignore rock ridge info if rr->len is out of range, but
* don't return -EIO because that would make the file
* invisible.
*/
if (rr->len < 3)
goto out; /* Something got screwed up here */
sig = isonum_721(rs.chr);
if (rock_check_overflow(&rs, sig))
goto eio;
rs.chr += rr->len;
rs.len -= rr->len;
/*
* As above, just ignore the rock ridge info if rr->len
* is bogus.
*/
if (rs.len < 0)
goto out; /* Something got screwed up here */
switch (sig) {
case SIG('R', 'R'):
if ((rr->u.RR.flags[0] & RR_NM) == 0)
goto out;
break;
case SIG('S', 'P'):
if (check_sp(rr, inode))
goto out;
break;
case SIG('C', 'E'):
rs.cont_extent = isonum_733(rr->u.CE.extent);
rs.cont_offset = isonum_733(rr->u.CE.offset);
rs.cont_size = isonum_733(rr->u.CE.size);
break;
case SIG('N', 'M'):
if (truncate)
break;
if (rr->len < 5)
break;
/*
* If the flags are 2 or 4, this indicates '.' or '..'.
* We don't want to do anything with this, because it
* screws up the code that calls us. We don't really
* care anyways, since we can just use the non-RR
* name.
*/
if (rr->u.NM.flags & 6)
break;
if (rr->u.NM.flags & ~1) {
printk("Unsupported NM flag settings (%d)\n",
rr->u.NM.flags);
break;
}
if ((strlen(retname) + rr->len - 5) >= 254) {
truncate = 1;
break;
}
strncat(retname, rr->u.NM.name, rr->len - 5);
retnamlen += rr->len - 5;
break;
case SIG('R', 'E'):
kfree(rs.buffer);
return -1;
default:
break;
}
}
ret = rock_continue(&rs);
if (ret == 0)
goto repeat;
if (ret == 1)
return retnamlen; /* If 0, this file did not have a NM field */
out:
kfree(rs.buffer);
return ret;
eio:
ret = -EIO;
goto out;
}
| 1 | CVE-2016-4913 | 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. | 8,114 |
jerryscript | efe63a5bbc5106164a08ee2eb415a7a701f5311f | parser_parse_import_statement (parser_context_t *context_p) /**< parser context */
{
JERRY_ASSERT (context_p->token.type == LEXER_KEYW_IMPORT);
JERRY_ASSERT (context_p->module_names_p == NULL);
if (lexer_check_next_characters (context_p, LIT_CHAR_LEFT_PAREN, LIT_CHAR_DOT))
{
if (context_p->status_flags & PARSER_IS_FUNCTION)
{
parser_parse_expression_statement (context_p, PARSE_EXPR);
return;
}
parser_parse_block_expression (context_p, PARSE_EXPR);
return;
}
parser_module_check_request_place (context_p);
lexer_next_token (context_p);
/* Check for a ModuleSpecifier*/
if (context_p->token.type != LEXER_LITERAL
|| context_p->token.lit_location.type != LEXER_STRING_LITERAL)
{
if (!(context_p->token.type == LEXER_LEFT_BRACE
|| context_p->token.type == LEXER_MULTIPLY
|| (context_p->token.type == LEXER_LITERAL && context_p->token.lit_location.type == LEXER_IDENT_LITERAL)))
{
parser_raise_error (context_p, PARSER_ERR_LEFT_BRACE_MULTIPLY_LITERAL_EXPECTED);
}
if (context_p->token.type == LEXER_LITERAL)
{
/* Handle ImportedDefaultBinding */
lexer_construct_literal_object (context_p, &context_p->token.lit_location, LEXER_IDENT_LITERAL);
ecma_string_t *local_name_p = parser_new_ecma_string_from_literal (context_p->lit_object.literal_p);
if (parser_module_check_duplicate_import (context_p, local_name_p))
{
ecma_deref_ecma_string (local_name_p);
parser_raise_error (context_p, PARSER_ERR_DUPLICATED_IMPORT_BINDING);
}
ecma_string_t *import_name_p = ecma_get_magic_string (LIT_MAGIC_STRING_DEFAULT);
parser_module_add_names_to_node (context_p, import_name_p, local_name_p);
ecma_deref_ecma_string (local_name_p);
ecma_deref_ecma_string (import_name_p);
lexer_next_token (context_p);
if (context_p->token.type == LEXER_COMMA)
{
lexer_next_token (context_p);
if (context_p->token.type != LEXER_MULTIPLY
&& context_p->token.type != LEXER_LEFT_BRACE)
{
parser_raise_error (context_p, PARSER_ERR_LEFT_BRACE_MULTIPLY_EXPECTED);
}
}
else if (!lexer_token_is_identifier (context_p, "from", 4))
{
parser_raise_error (context_p, PARSER_ERR_FROM_COMMA_EXPECTED);
}
}
if (context_p->token.type == LEXER_MULTIPLY)
{
/* NameSpaceImport */
lexer_next_token (context_p);
if (!lexer_token_is_identifier (context_p, "as", 2))
{
parser_raise_error (context_p, PARSER_ERR_AS_EXPECTED);
}
lexer_next_token (context_p);
if (context_p->token.type != LEXER_LITERAL)
{
parser_raise_error (context_p, PARSER_ERR_IDENTIFIER_EXPECTED);
}
lexer_construct_literal_object (context_p, &context_p->token.lit_location, LEXER_IDENT_LITERAL);
ecma_string_t *local_name_p = parser_new_ecma_string_from_literal (context_p->lit_object.literal_p);
if (parser_module_check_duplicate_import (context_p, local_name_p))
{
ecma_deref_ecma_string (local_name_p);
parser_raise_error (context_p, PARSER_ERR_DUPLICATED_IMPORT_BINDING);
}
ecma_string_t *import_name_p = ecma_get_magic_string (LIT_MAGIC_STRING_ASTERIX_CHAR);
parser_module_add_names_to_node (context_p, import_name_p, local_name_p);
ecma_deref_ecma_string (local_name_p);
ecma_deref_ecma_string (import_name_p);
lexer_next_token (context_p);
}
else if (context_p->token.type == LEXER_LEFT_BRACE)
{
/* Handle NamedImports */
parser_module_parse_import_clause (context_p);
}
if (!lexer_token_is_identifier (context_p, "from", 4))
{
parser_raise_error (context_p, PARSER_ERR_FROM_EXPECTED);
}
lexer_next_token (context_p);
}
parser_module_handle_module_specifier (context_p, NULL);
} /* parser_parse_import_statement */ | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,108 |
tensorflow | 9e62869465573cb2d9b5053f1fa02a81fce21d69 | void Compute(OpKernelContext* ctx) override {
const Tensor& input = ctx->input(kInputTensorIndex);
const Tensor& input_min = ctx->input(kInputMinIndex);
const Tensor& input_max = ctx->input(kInputMaxIndex);
const size_t depth = input_max.NumElements();
OP_REQUIRES(
ctx, input_min.dim_size(0) == depth,
errors::InvalidArgument("input_min has incorrect size, expected ",
depth, " was ", input_min.dim_size(0)));
OP_REQUIRES(
ctx, input_max.dim_size(0) == depth,
errors::InvalidArgument("input_max has incorrect size, expected ",
depth, " was ", input_max.dim_size(0)));
OP_REQUIRES(
ctx, input_min.NumElements() == depth,
errors::InvalidArgument("input_min must have the same number of "
"elements as input_max, got ",
input_min.NumElements(), " and ", depth));
OP_REQUIRES(ctx, input.NumElements() > 0,
errors::InvalidArgument("input must not be empty"));
OP_REQUIRES(ctx, input.dims() == 4,
errors::InvalidArgument("input must be in NHWC format"));
OP_REQUIRES(
ctx, input.dim_size(3) == depth,
errors::InvalidArgument(
"input must have same number of channels as length of input_min: ",
input.dim_size(3), " vs ", depth));
const float* input_min_data = input_min.flat<float>().data();
const float* input_max_data = input_max.flat<float>().data();
std::vector<float> ranges(depth);
bool is_non_negative = true;
Eigen::array<int, 2> shuffling({1, 0});
auto input_matrix = input.flat_inner_dims<qint32>();
// TODO: verify performance of not transposing and finding the min max
// directly from input_matrix vs the one presented below of transposing and
// using the transposed matrix as the transposing operation in itself might
// be more costly.
// Note that this operation is a calibration step for quantization and will
// cease to exist in the final inference graph(will exist as a const node).
auto transposed_input = input_matrix.shuffle(shuffling);
// Find the ranges of each channel in parallel.
float out_min_max = std::numeric_limits<float>::min();
#ifdef ENABLE_ONEDNN_OPENMP
#ifdef _MSC_VER
#pragma omp parallel for
#else
#pragma omp parallel for reduction(max : out_min_max)
#endif
#endif // ENABLE_ONEDNN_OPENMP
// TODO: Add eigen parallel_for
for (int64_t i = 0; i < depth; ++i) {
Eigen::Tensor<qint32, 0, Eigen::RowMajor> min =
transposed_input.chip<0>(i).minimum();
Eigen::Tensor<qint32, 0, Eigen::RowMajor> max =
transposed_input.chip<0>(i).maximum();
const int32_t min_per_channel = min();
const int32_t max_per_channel = max();
const int32_t abs_max =
std::max(std::abs(min_per_channel), std::abs(max_per_channel));
float scale =
std::max(std::abs(input_min_data[i]), std::abs(input_max_data[i]));
ranges[i] =
scale * static_cast<float>(abs_max) / static_cast<float>(1L << 31);
if (min_per_channel < 0) is_non_negative = false;
// Thread-local out_min_max.
out_min_max = std::max(out_min_max, ranges[i]);
}
// All local out_min_max gets max-reduced into one global out_min_max at
// the end of the loop by specifying reduction(max:out_min_max) along with
// omp parallel for.
// Fixing max to clip_value_max_ (example 6.0 to support relu6)
if (out_min_max > clip_value_max_) out_min_max = clip_value_max_;
Tensor* output_min = nullptr;
Tensor* output_max = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(kOutputMinIndex, {}, &output_min));
OP_REQUIRES_OK(ctx, ctx->allocate_output(kOutputMaxIndex, {}, &output_max));
output_min->flat<float>()(0) = is_non_negative ? 0.0f : -out_min_max;
output_max->flat<float>()(0) = out_min_max;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,173 |
linux | 8d0c2d10dd72c5292eda7a06231056a4c972e4cc | static ext3_fsblk_t get_sb_block(void **data, struct super_block *sb)
{
ext3_fsblk_t sb_block;
char *options = (char *) *data;
if (!options || strncmp(options, "sb=", 3) != 0)
return 1; /* Default location */
options += 3;
/*todo: use simple_strtoll with >32bit ext3 */
sb_block = simple_strtoul(options, &options, 0);
if (*options && *options != ',') {
ext3_msg(sb, "error: invalid sb specification: %s",
(char *) *data);
return 1;
}
if (*options == ',')
options++;
*data = (void *) options;
return sb_block;
}
| 1 | CVE-2013-1848 | 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,505 |
poppler | fc071d800cb4329a3ccf898d7bf16b4db7323ad8 | void DCTStream::init()
{
jpeg_std_error(&jerr);
jerr.error_exit = &exitErrorHandler;
src.pub.init_source = str_init_source;
src.pub.fill_input_buffer = str_fill_input_buffer;
src.pub.skip_input_data = str_skip_input_data;
src.pub.resync_to_restart = jpeg_resync_to_restart;
src.pub.term_source = str_term_source;
src.pub.next_input_byte = NULL;
src.str = str;
src.index = 0;
src.abort = false;
current = NULL;
limit = NULL;
limit = NULL;
cinfo.err = &jerr;
jpeg_create_decompress(&cinfo);
cinfo.src = (jpeg_source_mgr *)&src;
row_buffer = NULL;
}
| 1 | CVE-2010-5110 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 8,599 |
Chrome | 04aaacb936a08d70862d6d9d7e8354721ae46be8 | void StoreExistingGroupExistingCache() {
MakeCacheAndGroup(kManifestUrl, 1, 1, true);
EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin]);
base::Time now = base::Time::Now();
cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::MASTER, 1, 100));
cache_->set_update_time(now);
PushNextTask(base::BindOnce(
&AppCacheStorageImplTest::Verify_StoreExistingGroupExistingCache,
base::Unretained(this), now));
EXPECT_EQ(cache_.get(), group_->newest_complete_cache());
storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate());
EXPECT_FALSE(delegate()->stored_group_success_);
}
| 1 | CVE-2019-5837 | 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. | 2,932 |
linux | af368027a49a751d6ff4ee9e3f9961f35bb4fede | static int _snd_timer_stop(struct snd_timer_instance * timeri,
int keep_flag, int event)
{
struct snd_timer *timer;
unsigned long flags;
if (snd_BUG_ON(!timeri))
return -ENXIO;
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) {
if (!keep_flag) {
spin_lock_irqsave(&slave_active_lock, flags);
timeri->flags &= ~SNDRV_TIMER_IFLG_RUNNING;
spin_unlock_irqrestore(&slave_active_lock, flags);
}
goto __end;
}
timer = timeri->timer;
if (!timer)
return -EINVAL;
spin_lock_irqsave(&timer->lock, flags);
list_del_init(&timeri->ack_list);
list_del_init(&timeri->active_list);
if ((timeri->flags & SNDRV_TIMER_IFLG_RUNNING) &&
!(--timer->running)) {
timer->hw.stop(timer);
if (timer->flags & SNDRV_TIMER_FLG_RESCHED) {
timer->flags &= ~SNDRV_TIMER_FLG_RESCHED;
snd_timer_reschedule(timer, 0);
if (timer->flags & SNDRV_TIMER_FLG_CHANGE) {
timer->flags &= ~SNDRV_TIMER_FLG_CHANGE;
timer->hw.start(timer);
}
}
}
if (!keep_flag)
timeri->flags &=
~(SNDRV_TIMER_IFLG_RUNNING | SNDRV_TIMER_IFLG_START);
spin_unlock_irqrestore(&timer->lock, flags);
__end:
if (event != SNDRV_TIMER_EVENT_RESOLUTION)
snd_timer_notify1(timeri, event);
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,785 |
virglrenderer | 48f67f60967f963b698ec8df57ec6912a43d6282 | static void vrend_hw_emit_framebuffer_state(struct vrend_context *ctx)
{
static const GLenum buffers[8] = {
GL_COLOR_ATTACHMENT0_EXT,
GL_COLOR_ATTACHMENT1_EXT,
GL_COLOR_ATTACHMENT2_EXT,
GL_COLOR_ATTACHMENT3_EXT,
GL_COLOR_ATTACHMENT4_EXT,
GL_COLOR_ATTACHMENT5_EXT,
GL_COLOR_ATTACHMENT6_EXT,
GL_COLOR_ATTACHMENT7_EXT,
};
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->sub->fb_id);
if (ctx->sub->nr_cbufs == 0) {
glReadBuffer(GL_NONE);
glDisable(GL_FRAMEBUFFER_SRGB_EXT);
} else {
struct vrend_surface *surf = NULL;
int i;
for (i = 0; i < ctx->sub->nr_cbufs; i++) {
if (ctx->sub->surf[i]) {
surf = ctx->sub->surf[i];
}
}
if (util_format_is_srgb(surf->format)) {
glEnable(GL_FRAMEBUFFER_SRGB_EXT);
} else {
glDisable(GL_FRAMEBUFFER_SRGB_EXT);
}
}
glDrawBuffers(ctx->sub->nr_cbufs, buffers);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,859 |
linux | 9f645bcc566a1e9f921bdae7528a01ced5bc3713 | static int uvesafb_setcmap(struct fb_cmap *cmap, struct fb_info *info)
{
struct uvesafb_pal_entry *entries;
int shift = 16 - dac_width;
int i, err = 0;
if (info->var.bits_per_pixel == 8) {
if (cmap->start + cmap->len > info->cmap.start +
info->cmap.len || cmap->start < info->cmap.start)
return -EINVAL;
entries = kmalloc(sizeof(*entries) * cmap->len, GFP_KERNEL);
if (!entries)
return -ENOMEM;
for (i = 0; i < cmap->len; i++) {
entries[i].red = cmap->red[i] >> shift;
entries[i].green = cmap->green[i] >> shift;
entries[i].blue = cmap->blue[i] >> shift;
entries[i].pad = 0;
}
err = uvesafb_setpalette(entries, cmap->len, cmap->start, info);
kfree(entries);
} else {
/*
* For modes with bpp > 8, we only set the pseudo palette in
* the fb_info struct. We rely on uvesafb_setcolreg to do all
* sanity checking.
*/
for (i = 0; i < cmap->len; i++) {
err |= uvesafb_setcolreg(cmap->start + i, cmap->red[i],
cmap->green[i], cmap->blue[i],
0, info);
}
}
return err;
}
| 1 | CVE-2018-13406 | CWE-190 | Integer Overflow or Wraparound | The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number. | Phase: Requirements
Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol.
Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
If possible, choose a language or compiler that performs automatic bounds checking.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Use libraries or frameworks that make it easier to handle numbers without unexpected consequences.
Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106]
Phase: Implementation
Strategy: Input Validation
Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.
Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values.
Phase: Implementation
Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7]
Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Phase: Implementation
Strategy: Compilation or Build Hardening
Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system. | 1,206 |
bdwgc | be9df82919960214ee4b9d3313523bff44fd99e1 | GC_API void GC_CALL GC_incr_bytes_freed(size_t n)
{
GC_bytes_freed += n;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,357 |
libsass | 25c9b4952f5838b615da996035453967d0420f57 | bool List::operator== (const Expression& rhs) const
{
if (List_Ptr_Const r = Cast<List>(&rhs)) {
if (length() != r->length()) return false;
if (separator() != r->separator()) return false;
for (size_t i = 0, L = length(); i < L; ++i) {
Expression_Obj rv = r->at(i);
Expression_Obj lv = this->at(i);
if (!lv || !rv) return false;
if (!(*lv == *rv)) return false;
}
return true;
}
return false;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,434 |
linux | fe685aabf7c8c9f138e5ea900954d295bf229175 | static struct dentry *isofs_fh_to_parent(struct super_block *sb,
struct fid *fid, int fh_len, int fh_type)
{
struct isofs_fid *ifid = (struct isofs_fid *)fid;
if (fh_type != 2)
return NULL;
return isofs_export_iget(sb,
fh_len > 2 ? ifid->parent_block : 0,
ifid->parent_offset,
fh_len > 4 ? ifid->parent_generation : 0);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,905 |
tcpdump | d7505276842e85bfd067fa21cdb32b8a2dc3c5e4 | icmp6_nodeinfo_print(netdissect_options *ndo, u_int icmp6len, const u_char *bp, const u_char *ep)
{
const struct icmp6_nodeinfo *ni6;
const struct icmp6_hdr *dp;
const u_char *cp;
size_t siz, i;
int needcomma;
if (ep < bp)
return;
dp = (const struct icmp6_hdr *)bp;
ni6 = (const struct icmp6_nodeinfo *)bp;
siz = ep - bp;
switch (ni6->ni_type) {
case ICMP6_NI_QUERY:
if (siz == sizeof(*dp) + 4) {
/* KAME who-are-you */
ND_PRINT((ndo," who-are-you request"));
break;
}
ND_PRINT((ndo," node information query"));
ND_TCHECK2(*dp, sizeof(*ni6));
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," (")); /*)*/
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
ND_PRINT((ndo,"noop"));
break;
case NI_QTYPE_SUPTYPES:
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
ND_PRINT((ndo,"DNS name"));
break;
case NI_QTYPE_NODEADDR:
ND_PRINT((ndo,"node addresses"));
i = ni6->ni_flags;
if (!i)
break;
/* NI_NODEADDR_FLAG_TRUNCATE undefined for query */
ND_PRINT((ndo," [%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : ""));
break;
default:
ND_PRINT((ndo,"unknown"));
break;
}
if (ni6->ni_qtype == NI_QTYPE_NOOP ||
ni6->ni_qtype == NI_QTYPE_SUPTYPES) {
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid len"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
/* XXX backward compat, icmp-name-lookup-03 */
if (siz == sizeof(*ni6)) {
ND_PRINT((ndo,", 03 draft"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (ni6->ni_code) {
case ICMP6_NI_SUBJ_IPV6:
if (!ND_TTEST2(*dp,
sizeof(*ni6) + sizeof(struct in6_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in6_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ip6addr_string(ndo, ni6 + 1)));
break;
case ICMP6_NI_SUBJ_FQDN:
ND_PRINT((ndo,", subject=DNS name"));
cp = (const u_char *)(ni6 + 1);
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
break;
case ICMP6_NI_SUBJ_IPV4:
if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ipaddr_string(ndo, ni6 + 1)));
break;
default:
ND_PRINT((ndo,", unknown subject"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
case ICMP6_NI_REPLY:
if (icmp6len > siz) {
ND_PRINT((ndo,"[|icmp6: node information reply]"));
break;
}
needcomma = 0;
ND_TCHECK2(*dp, sizeof(*ni6));
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," node information reply"));
ND_PRINT((ndo," (")); /*)*/
switch (ni6->ni_code) {
case ICMP6_NI_SUCCESS:
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"success"));
needcomma++;
}
break;
case ICMP6_NI_REFUSED:
ND_PRINT((ndo,"refused"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case ICMP6_NI_UNKNOWN:
ND_PRINT((ndo,"unknown"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
}
if (ni6->ni_code != ICMP6_NI_SUCCESS) {
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"noop"));
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case NI_QTYPE_SUPTYPES:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"DNS name"));
cp = (const u_char *)(ni6 + 1) + 4;
ND_TCHECK(cp[0]);
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
if ((EXTRACT_16BITS(&ni6->ni_flags) & 0x01) != 0)
ND_PRINT((ndo," [TTL=%u]", EXTRACT_32BITS(ni6 + 1)));
break;
case NI_QTYPE_NODEADDR:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"node addresses"));
i = sizeof(*ni6);
while (i < siz) {
if (i + sizeof(struct in6_addr) + sizeof(int32_t) > siz)
break;
ND_PRINT((ndo," %s", ip6addr_string(ndo, bp + i)));
i += sizeof(struct in6_addr);
ND_PRINT((ndo,"(%d)", (int32_t)EXTRACT_32BITS(bp + i)));
i += sizeof(int32_t);
}
i = ni6->ni_flags;
if (!i)
break;
ND_PRINT((ndo," [%s%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : "",
(i & NI_NODEADDR_FLAG_TRUNCATE) ? "T" : ""));
break;
default:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"unknown"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|icmp6]"));
}
| 1 | CVE-2018-14882 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 2,342 |
FreeRDP | 0773bb9303d24473fe1185d85a424dfe159aff53 | void* sspi_SecureHandleGetLowerPointer(SecHandle* handle)
{
void* pointer;
if (!handle)
return NULL;
pointer = (void*) ~((size_t) handle->dwLower);
return pointer;
}
| 1 | CVE-2013-4119 | 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. | 5,119 |
tensorflow | 3ade2efec2e90c6237de32a19680caaa3ebc2845 | static inline Status ParseAndCheckBoxSizes(const Tensor& boxes,
const Tensor& box_index,
int* num_boxes) {
if (boxes.NumElements() == 0 && box_index.NumElements() == 0) {
*num_boxes = 0;
return Status::OK();
}
// The shape of 'boxes' is [num_boxes, 4].
if (boxes.dims() != 2) {
return errors::InvalidArgument("boxes must be 2-D",
boxes.shape().DebugString());
}
*num_boxes = boxes.dim_size(0);
if (boxes.dim_size(1) != 4) {
return errors::InvalidArgument("boxes must have 4 columns");
}
// The shape of 'box_index' is [num_boxes].
if (box_index.dims() != 1) {
return errors::InvalidArgument("box_index must be 1-D",
box_index.shape().DebugString());
}
if (box_index.dim_size(0) != *num_boxes) {
return errors::InvalidArgument("box_index has incompatible shape");
}
return Status::OK();
} | 1 | CVE-2020-15266 | CWE-787 | Out-of-bounds Write | The product writes data past the end, or before the beginning, of the intended buffer. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333].
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 4,490 |
vim | 6f98371532fcff911b462d51bc64f2ce8a6ae682 | do_arg_all(
int count,
int forceit, // hide buffers in current windows
int keep_tabs) // keep current tabs, for ":tab drop file"
{
int i;
win_T *wp, *wpnext;
char_u *opened; // Array of weight for which args are open:
// 0: not opened
// 1: opened in other tab
// 2: opened in curtab
// 3: opened in curtab and curwin
//
int opened_len; // length of opened[]
int use_firstwin = FALSE; // use first window for arglist
int tab_drop_empty_window = FALSE;
int split_ret = OK;
int p_ea_save;
alist_T *alist; // argument list to be used
buf_T *buf;
tabpage_T *tpnext;
int had_tab = cmdmod.cmod_tab;
win_T *old_curwin, *last_curwin;
tabpage_T *old_curtab, *last_curtab;
win_T *new_curwin = NULL;
tabpage_T *new_curtab = NULL;
#ifdef FEAT_CMDWIN
if (cmdwin_type != 0)
{
emsg(_(e_invalid_in_cmdline_window));
return;
}
#endif
if (ARGCOUNT <= 0)
{
// Don't give an error message. We don't want it when the ":all"
// command is in the .vimrc.
return;
}
setpcmark();
opened_len = ARGCOUNT;
opened = alloc_clear(opened_len);
if (opened == NULL)
return;
// Autocommands may do anything to the argument list. Make sure it's not
// freed while we are working here by "locking" it. We still have to
// watch out for its size to be changed.
alist = curwin->w_alist;
++alist->al_refcount;
old_curwin = curwin;
old_curtab = curtab;
# ifdef FEAT_GUI
need_mouse_correct = TRUE;
# endif
// Try closing all windows that are not in the argument list.
// Also close windows that are not full width;
// When 'hidden' or "forceit" set the buffer becomes hidden.
// Windows that have a changed buffer and can't be hidden won't be closed.
// When the ":tab" modifier was used do this for all tab pages.
if (had_tab > 0)
goto_tabpage_tp(first_tabpage, TRUE, TRUE);
for (;;)
{
tpnext = curtab->tp_next;
for (wp = firstwin; wp != NULL; wp = wpnext)
{
wpnext = wp->w_next;
buf = wp->w_buffer;
if (buf->b_ffname == NULL
|| (!keep_tabs && (buf->b_nwindows > 1
|| wp->w_width != Columns)))
i = opened_len;
else
{
// check if the buffer in this window is in the arglist
for (i = 0; i < opened_len; ++i)
{
if (i < alist->al_ga.ga_len
&& (AARGLIST(alist)[i].ae_fnum == buf->b_fnum
|| fullpathcmp(alist_name(&AARGLIST(alist)[i]),
buf->b_ffname, TRUE, TRUE) & FPC_SAME))
{
int weight = 1;
if (old_curtab == curtab)
{
++weight;
if (old_curwin == wp)
++weight;
}
if (weight > (int)opened[i])
{
opened[i] = (char_u)weight;
if (i == 0)
{
if (new_curwin != NULL)
new_curwin->w_arg_idx = opened_len;
new_curwin = wp;
new_curtab = curtab;
}
}
else if (keep_tabs)
i = opened_len;
if (wp->w_alist != alist)
{
// Use the current argument list for all windows
// containing a file from it.
alist_unlink(wp->w_alist);
wp->w_alist = alist;
++wp->w_alist->al_refcount;
}
break;
}
}
}
wp->w_arg_idx = i;
if (i == opened_len && !keep_tabs)// close this window
{
if (buf_hide(buf) || forceit || buf->b_nwindows > 1
|| !bufIsChanged(buf))
{
// If the buffer was changed, and we would like to hide it,
// try autowriting.
if (!buf_hide(buf) && buf->b_nwindows <= 1
&& bufIsChanged(buf))
{
bufref_T bufref;
set_bufref(&bufref, buf);
(void)autowrite(buf, FALSE);
// check if autocommands removed the window
if (!win_valid(wp) || !bufref_valid(&bufref))
{
wpnext = firstwin; // start all over...
continue;
}
}
// don't close last window
if (ONE_WINDOW
&& (first_tabpage->tp_next == NULL || !had_tab))
use_firstwin = TRUE;
else
{
win_close(wp, !buf_hide(buf) && !bufIsChanged(buf));
// check if autocommands removed the next window
if (!win_valid(wpnext))
wpnext = firstwin; // start all over...
}
}
}
}
// Without the ":tab" modifier only do the current tab page.
if (had_tab == 0 || tpnext == NULL)
break;
// check if autocommands removed the next tab page
if (!valid_tabpage(tpnext))
tpnext = first_tabpage; // start all over...
goto_tabpage_tp(tpnext, TRUE, TRUE);
}
// Open a window for files in the argument list that don't have one.
// ARGCOUNT may change while doing this, because of autocommands.
if (count > opened_len || count <= 0)
count = opened_len;
// Don't execute Win/Buf Enter/Leave autocommands here.
++autocmd_no_enter;
++autocmd_no_leave;
last_curwin = curwin;
last_curtab = curtab;
win_enter(lastwin, FALSE);
// ":tab drop file" should re-use an empty window to avoid "--remote-tab"
// leaving an empty tab page when executed locally.
if (keep_tabs && BUFEMPTY() && curbuf->b_nwindows == 1
&& curbuf->b_ffname == NULL && !curbuf->b_changed)
{
use_firstwin = TRUE;
tab_drop_empty_window = TRUE;
}
for (i = 0; i < count && !got_int; ++i)
{
if (alist == &global_alist && i == global_alist.al_ga.ga_len - 1)
arg_had_last = TRUE;
if (opened[i] > 0)
{
// Move the already present window to below the current window
if (curwin->w_arg_idx != i)
{
FOR_ALL_WINDOWS(wpnext)
{
if (wpnext->w_arg_idx == i)
{
if (keep_tabs)
{
new_curwin = wpnext;
new_curtab = curtab;
}
else if (wpnext->w_frame->fr_parent
!= curwin->w_frame->fr_parent)
{
emsg(_("E249: window layout changed unexpectedly"));
i = count;
break;
}
else
win_move_after(wpnext, curwin);
break;
}
}
}
}
else if (split_ret == OK)
{
// trigger events for tab drop
if (tab_drop_empty_window && i == count - 1)
--autocmd_no_enter;
if (!use_firstwin) // split current window
{
p_ea_save = p_ea;
p_ea = TRUE; // use space from all windows
split_ret = win_split(0, WSP_ROOM | WSP_BELOW);
p_ea = p_ea_save;
if (split_ret == FAIL)
continue;
}
else // first window: do autocmd for leaving this buffer
--autocmd_no_leave;
// edit file "i"
curwin->w_arg_idx = i;
if (i == 0)
{
new_curwin = curwin;
new_curtab = curtab;
}
(void)do_ecmd(0, alist_name(&AARGLIST(alist)[i]), NULL, NULL,
ECMD_ONE,
((buf_hide(curwin->w_buffer)
|| bufIsChanged(curwin->w_buffer)) ? ECMD_HIDE : 0)
+ ECMD_OLDBUF, curwin);
if (tab_drop_empty_window && i == count - 1)
++autocmd_no_enter;
if (use_firstwin)
++autocmd_no_leave;
use_firstwin = FALSE;
}
ui_breakcheck();
// When ":tab" was used open a new tab for a new window repeatedly.
if (had_tab > 0 && tabpage_index(NULL) <= p_tpm)
cmdmod.cmod_tab = 9999;
}
// Remove the "lock" on the argument list.
alist_unlink(alist);
--autocmd_no_enter;
// restore last referenced tabpage's curwin
if (last_curtab != new_curtab)
{
if (valid_tabpage(last_curtab))
goto_tabpage_tp(last_curtab, TRUE, TRUE);
if (win_valid(last_curwin))
win_enter(last_curwin, FALSE);
}
// to window with first arg
if (valid_tabpage(new_curtab))
goto_tabpage_tp(new_curtab, TRUE, TRUE);
if (win_valid(new_curwin))
win_enter(new_curwin, FALSE);
--autocmd_no_leave;
vim_free(opened);
} | 1 | CVE-2021-4166 | CWE-416 | Use After Free | The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
Phase: Architecture and Design
Strategy: Language Selection
Choose a language that provides automatic memory management.
Phase: Implementation
Strategy: Attack Surface Reduction
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.
Effectiveness: Defense in Depth
Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution. | 4,432 |
linux | 06b6a1cf6e776426766298d055bb3991957d90a7 | static int rds_next_incoming(struct rds_sock *rs, struct rds_incoming **inc)
{
unsigned long flags;
if (!*inc) {
read_lock_irqsave(&rs->rs_recv_lock, flags);
if (!list_empty(&rs->rs_recv_queue)) {
*inc = list_entry(rs->rs_recv_queue.next,
struct rds_incoming,
i_item);
rds_inc_addref(*inc);
}
read_unlock_irqrestore(&rs->rs_recv_lock, flags);
}
return *inc != NULL;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,517 |
Subsets and Splits