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
|
---|---|---|---|---|---|---|---|---|---|
WAVM | 31d670b6489e6d708c3b04b911cdf14ac43d846d | bool resolve(const std::string& moduleName,
const std::string& exportName,
ObjectType type,
Object*& outObject) override
{
auto namedInstance = moduleNameToInstanceMap.get(moduleName);
if(namedInstance)
{
outObject = getInstanceExport(*namedInstance, exportName);
if(outObject)
{
if(isA(outObject, type)) { return true; }
else
{
Log::printf(Log::error,
"Resolved import %s.%s to a %s, but was expecting %s\n",
moduleName.c_str(),
exportName.c_str(),
asString(getObjectType(outObject)).c_str(),
asString(type).c_str());
return false;
}
}
}
Log::printf(Log::error,
"Generated stub for missing import %s.%s : %s\n",
moduleName.c_str(),
exportName.c_str(),
asString(type).c_str());
outObject = getStubObject(exportName, type);
return true;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,751 |
linux | 82262a46627bebb0febcc26664746c25cef08563 | static int snd_ctl_elem_add(struct snd_ctl_file *file,
struct snd_ctl_elem_info *info, int replace)
{
struct snd_card *card = file->card;
struct snd_kcontrol kctl, *_kctl;
unsigned int access;
long private_size;
struct user_element *ue;
int idx, err;
if (!replace && card->user_ctl_count >= MAX_USER_CONTROLS)
return -ENOMEM;
if (info->count < 1)
return -EINVAL;
access = info->access == 0 ? SNDRV_CTL_ELEM_ACCESS_READWRITE :
(info->access & (SNDRV_CTL_ELEM_ACCESS_READWRITE|
SNDRV_CTL_ELEM_ACCESS_INACTIVE|
SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE));
info->id.numid = 0;
memset(&kctl, 0, sizeof(kctl));
down_write(&card->controls_rwsem);
_kctl = snd_ctl_find_id(card, &info->id);
err = 0;
if (_kctl) {
if (replace)
err = snd_ctl_remove(card, _kctl);
else
err = -EBUSY;
} else {
if (replace)
err = -ENOENT;
}
up_write(&card->controls_rwsem);
if (err < 0)
return err;
memcpy(&kctl.id, &info->id, sizeof(info->id));
kctl.count = info->owner ? info->owner : 1;
access |= SNDRV_CTL_ELEM_ACCESS_USER;
if (info->type == SNDRV_CTL_ELEM_TYPE_ENUMERATED)
kctl.info = snd_ctl_elem_user_enum_info;
else
kctl.info = snd_ctl_elem_user_info;
if (access & SNDRV_CTL_ELEM_ACCESS_READ)
kctl.get = snd_ctl_elem_user_get;
if (access & SNDRV_CTL_ELEM_ACCESS_WRITE)
kctl.put = snd_ctl_elem_user_put;
if (access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE) {
kctl.tlv.c = snd_ctl_elem_user_tlv;
access |= SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
}
switch (info->type) {
case SNDRV_CTL_ELEM_TYPE_BOOLEAN:
case SNDRV_CTL_ELEM_TYPE_INTEGER:
private_size = sizeof(long);
if (info->count > 128)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_INTEGER64:
private_size = sizeof(long long);
if (info->count > 64)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_ENUMERATED:
private_size = sizeof(unsigned int);
if (info->count > 128 || info->value.enumerated.items == 0)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_BYTES:
private_size = sizeof(unsigned char);
if (info->count > 512)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_IEC958:
private_size = sizeof(struct snd_aes_iec958);
if (info->count != 1)
return -EINVAL;
break;
default:
return -EINVAL;
}
private_size *= info->count;
ue = kzalloc(sizeof(struct user_element) + private_size, GFP_KERNEL);
if (ue == NULL)
return -ENOMEM;
ue->card = card;
ue->info = *info;
ue->info.access = 0;
ue->elem_data = (char *)ue + sizeof(*ue);
ue->elem_data_size = private_size;
if (ue->info.type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) {
err = snd_ctl_elem_init_enum_names(ue);
if (err < 0) {
kfree(ue);
return err;
}
}
kctl.private_free = snd_ctl_elem_user_free;
_kctl = snd_ctl_new(&kctl, access);
if (_kctl == NULL) {
kfree(ue->priv_data);
kfree(ue);
return -ENOMEM;
}
_kctl->private_data = ue;
for (idx = 0; idx < _kctl->count; idx++)
_kctl->vd[idx].owner = file;
err = snd_ctl_add(card, _kctl);
if (err < 0)
return err;
down_write(&card->controls_rwsem);
card->user_ctl_count++;
up_write(&card->controls_rwsem);
return 0;
}
| 1 | CVE-2014-4655 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 5,249 |
postgres | 31400a673325147e1205326008e32135a78b4d8a | hstore_from_array(PG_FUNCTION_ARGS)
{
ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
int ndims = ARR_NDIM(in_array);
int count;
int32 buflen;
HStore *out;
Pairs *pairs;
Datum *in_datums;
bool *in_nulls;
int in_count;
int i;
Assert(ARR_ELEMTYPE(in_array) == TEXTOID);
switch (ndims)
{
case 0:
out = hstorePairs(NULL, 0, 0);
PG_RETURN_POINTER(out);
case 1:
if ((ARR_DIMS(in_array)[0]) % 2)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("array must have even number of elements")));
break;
case 2:
if ((ARR_DIMS(in_array)[1]) != 2)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("array must have two columns")));
break;
default:
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("wrong number of array subscripts")));
}
deconstruct_array(in_array,
TEXTOID, -1, false, 'i',
&in_datums, &in_nulls, &in_count);
count = in_count / 2;
pairs = palloc(count * sizeof(Pairs));
for (i = 0; i < count; ++i)
{
if (in_nulls[i * 2])
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("null value not allowed for hstore key")));
if (in_nulls[i * 2 + 1])
{
pairs[i].key = VARDATA_ANY(in_datums[i * 2]);
pairs[i].val = NULL;
pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2]));
pairs[i].vallen = 4;
pairs[i].isnull = true;
pairs[i].needfree = false;
}
else
{
pairs[i].key = VARDATA_ANY(in_datums[i * 2]);
pairs[i].val = VARDATA_ANY(in_datums[i * 2 + 1]);
pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2]));
pairs[i].vallen = hstoreCheckValLen(VARSIZE_ANY_EXHDR(in_datums[i * 2 + 1]));
pairs[i].isnull = false;
pairs[i].needfree = false;
}
}
count = hstoreUniquePairs(pairs, count, &buflen);
out = hstorePairs(pairs, count, buflen);
PG_RETURN_POINTER(out);
}
| 1 | CVE-2014-2669 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 715 |
Chrome | 3c8e4852477d5b1e2da877808c998dc57db9460f | void InspectorHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
host_ = frame_host;
}
| 1 | CVE-2018-6111 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 1,336 |
Little-CMS | 5ca71a7bc18b6897ab21d815d15e218e204581e2 | void Type_MPE_Free(struct _cms_typehandler_struct* self, void *Ptr)
{
cmsPipelineFree((cmsPipeline*) Ptr);
return;
cmsUNUSED_PARAMETER(self);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,937 |
linux | 983d8e60f50806f90534cc5373d0ce867e5aaf79 | xfs_find_handle(
unsigned int cmd,
xfs_fsop_handlereq_t *hreq)
{
int hsize;
xfs_handle_t handle;
struct inode *inode;
struct fd f = {NULL};
struct path path;
int error;
struct xfs_inode *ip;
if (cmd == XFS_IOC_FD_TO_HANDLE) {
f = fdget(hreq->fd);
if (!f.file)
return -EBADF;
inode = file_inode(f.file);
} else {
error = user_path_at(AT_FDCWD, hreq->path, 0, &path);
if (error)
return error;
inode = d_inode(path.dentry);
}
ip = XFS_I(inode);
/*
* We can only generate handles for inodes residing on a XFS filesystem,
* and only for regular files, directories or symbolic links.
*/
error = -EINVAL;
if (inode->i_sb->s_magic != XFS_SB_MAGIC)
goto out_put;
error = -EBADF;
if (!S_ISREG(inode->i_mode) &&
!S_ISDIR(inode->i_mode) &&
!S_ISLNK(inode->i_mode))
goto out_put;
memcpy(&handle.ha_fsid, ip->i_mount->m_fixedfsid, sizeof(xfs_fsid_t));
if (cmd == XFS_IOC_PATH_TO_FSHANDLE) {
/*
* This handle only contains an fsid, zero the rest.
*/
memset(&handle.ha_fid, 0, sizeof(handle.ha_fid));
hsize = sizeof(xfs_fsid_t);
} else {
handle.ha_fid.fid_len = sizeof(xfs_fid_t) -
sizeof(handle.ha_fid.fid_len);
handle.ha_fid.fid_pad = 0;
handle.ha_fid.fid_gen = inode->i_generation;
handle.ha_fid.fid_ino = ip->i_ino;
hsize = sizeof(xfs_handle_t);
}
error = -EFAULT;
if (copy_to_user(hreq->ohandle, &handle, hsize) ||
copy_to_user(hreq->ohandlen, &hsize, sizeof(__s32)))
goto out_put;
error = 0;
out_put:
if (cmd == XFS_IOC_FD_TO_HANDLE)
fdput(f);
else
path_put(&path);
return error;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,529 |
ImageMagick | a47e7a994766b92b10d4a87df8c1c890c8b170f3 | MagickExport MagickBooleanType SetImageAlphaChannel(Image *image,
const AlphaChannelOption alpha_type,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
status=MagickTrue;
switch (alpha_type)
{
case ActivateAlphaChannel:
{
image->alpha_trait=BlendPixelTrait;
break;
}
case AssociateAlphaChannel:
{
/*
Associate alpha.
*/
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
register ssize_t
i;
gamma=QuantumScale*GetPixelAlpha(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (channel == AlphaPixelChannel)
continue;
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(gamma*q[i]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->alpha_trait=CopyPixelTrait;
return(status);
}
case BackgroundAlphaChannel:
{
/*
Set transparent pixels to background color.
*/
if (image->alpha_trait == UndefinedPixelTrait)
break;
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,q) == TransparentAlpha)
{
SetPixelViaPixelInfo(image,&image->background_color,q);
SetPixelChannel(image,AlphaPixelChannel,TransparentAlpha,q);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
case CopyAlphaChannel:
{
image->alpha_trait=UpdatePixelTrait;
status=CompositeImage(image,image,IntensityCompositeOp,MagickTrue,0,0,
exception);
break;
}
case DeactivateAlphaChannel:
{
if (image->alpha_trait == UndefinedPixelTrait)
status=SetImageAlpha(image,OpaqueAlpha,exception);
image->alpha_trait=CopyPixelTrait;
break;
}
case DisassociateAlphaChannel:
{
/*
Disassociate alpha.
*/
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image->alpha_trait=BlendPixelTrait;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma,
Sa;
register ssize_t
i;
Sa=QuantumScale*GetPixelAlpha(image,q);
gamma=PerceptibleReciprocal(Sa);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (channel == AlphaPixelChannel)
continue;
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(gamma*q[i]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->alpha_trait=UndefinedPixelTrait;
return(status);
}
case DiscreteAlphaChannel:
{
if (image->alpha_trait == UndefinedPixelTrait)
status=SetImageAlpha(image,OpaqueAlpha,exception);
image->alpha_trait=UpdatePixelTrait;
break;
}
case ExtractAlphaChannel:
{
status=CompositeImage(image,image,AlphaCompositeOp,MagickTrue,0,0,
exception);
image->alpha_trait=UndefinedPixelTrait;
break;
}
case OffAlphaChannel:
{
image->alpha_trait=UndefinedPixelTrait;
break;
}
case OnAlphaChannel:
{
if (image->alpha_trait == UndefinedPixelTrait)
status=SetImageAlpha(image,OpaqueAlpha,exception);
image->alpha_trait=BlendPixelTrait;
break;
}
case OpaqueAlphaChannel:
{
status=SetImageAlpha(image,OpaqueAlpha,exception);
break;
}
case RemoveAlphaChannel:
{
/*
Remove transparency.
*/
if (image->alpha_trait == UndefinedPixelTrait)
break;
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
FlattenPixelInfo(image,&image->background_color,
image->background_color.alpha,q,(double) GetPixelAlpha(image,q),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->alpha_trait=image->background_color.alpha_trait;
break;
}
case SetAlphaChannel:
{
if (image->alpha_trait == UndefinedPixelTrait)
status=SetImageAlpha(image,OpaqueAlpha,exception);
break;
}
case ShapeAlphaChannel:
{
/*
Remove transparency.
*/
image->alpha_trait=BlendPixelTrait;
status=SetImageStorageClass(image,DirectClass,exception);
if (status == MagickFalse)
break;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
background;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
ConformPixelInfo(image,&image->background_color,&background,exception);
background.alpha_trait=BlendPixelTrait;
for (x=0; x < (ssize_t) image->columns; x++)
{
background.alpha=GetPixelIntensity(image,q);
SetPixelViaPixelInfo(image,&background,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
break;
}
case TransparentAlphaChannel:
{
status=SetImageAlpha(image,TransparentAlpha,exception);
break;
}
case UndefinedAlphaChannel:
break;
}
if (status == MagickFalse)
return(status);
(void) SetPixelChannelMask(image,image->channel_mask);
return(SyncImagePixelCache(image,exception));
} | 1 | CVE-2020-25663 | 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. | 551 |
linux | dbcc7d57bffc0c8cac9dac11bec548597d59a6a5 | get_old_root(struct btrfs_root *root, u64 time_seq)
{
struct btrfs_fs_info *fs_info = root->fs_info;
struct tree_mod_elem *tm;
struct extent_buffer *eb = NULL;
struct extent_buffer *eb_root;
u64 eb_root_owner = 0;
struct extent_buffer *old;
struct tree_mod_root *old_root = NULL;
u64 old_generation = 0;
u64 logical;
int level;
eb_root = btrfs_read_lock_root_node(root);
tm = __tree_mod_log_oldest_root(eb_root, time_seq);
if (!tm)
return eb_root;
if (tm->op == MOD_LOG_ROOT_REPLACE) {
old_root = &tm->old_root;
old_generation = tm->generation;
logical = old_root->logical;
level = old_root->level;
} else {
logical = eb_root->start;
level = btrfs_header_level(eb_root);
}
tm = tree_mod_log_search(fs_info, logical, time_seq);
if (old_root && tm && tm->op != MOD_LOG_KEY_REMOVE_WHILE_FREEING) {
btrfs_tree_read_unlock(eb_root);
free_extent_buffer(eb_root);
old = read_tree_block(fs_info, logical, root->root_key.objectid,
0, level, NULL);
if (WARN_ON(IS_ERR(old) || !extent_buffer_uptodate(old))) {
if (!IS_ERR(old))
free_extent_buffer(old);
btrfs_warn(fs_info,
"failed to read tree block %llu from get_old_root",
logical);
} else {
eb = btrfs_clone_extent_buffer(old);
free_extent_buffer(old);
}
} else if (old_root) {
eb_root_owner = btrfs_header_owner(eb_root);
btrfs_tree_read_unlock(eb_root);
free_extent_buffer(eb_root);
eb = alloc_dummy_extent_buffer(fs_info, logical);
} else {
eb = btrfs_clone_extent_buffer(eb_root);
btrfs_tree_read_unlock(eb_root);
free_extent_buffer(eb_root);
}
if (!eb)
return NULL;
if (old_root) {
btrfs_set_header_bytenr(eb, eb->start);
btrfs_set_header_backref_rev(eb, BTRFS_MIXED_BACKREF_REV);
btrfs_set_header_owner(eb, eb_root_owner);
btrfs_set_header_level(eb, old_root->level);
btrfs_set_header_generation(eb, old_generation);
}
btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb), eb,
btrfs_header_level(eb));
btrfs_tree_read_lock(eb);
if (tm)
__tree_mod_log_rewind(fs_info, eb, time_seq, tm);
else
WARN_ON(btrfs_header_level(eb) != 0);
WARN_ON(btrfs_header_nritems(eb) > BTRFS_NODEPTRS_PER_BLOCK(fs_info));
return eb;
} | 1 | CVE-2021-28964 | CWE-362 | Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') | The product contains a concurrent code sequence that requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence operating concurrently. | Phase: Architecture and Design
In languages that support it, use synchronization primitives. Only wrap these around critical code to minimize the impact on performance.
Phase: Architecture and Design
Use thread-safe capabilities such as the data access abstraction in Spring.
Phase: Architecture and Design
Minimize the usage of shared resources in order to remove as much complexity as possible from the control flow and to reduce the likelihood of unexpected conditions occurring.
Additionally, this will minimize the amount of synchronization necessary and may even help to reduce the likelihood of a denial of service where an attacker may be able to repeatedly trigger a critical section (CWE-400).
Phase: Implementation
When using multithreading and operating on shared variables, only use thread-safe functions.
Phase: Implementation
Use atomic operations on shared variables. Be wary of innocent-looking constructs such as "x++". This may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read, followed by a computation, followed by a write.
Phase: Implementation
Use a mutex if available, but be sure to avoid related weaknesses such as CWE-412.
Phase: Implementation
Avoid double-checked locking (CWE-609) and other implementation errors that arise when trying to avoid the overhead of synchronization.
Phase: Implementation
Disable interrupts or signals over critical parts of the code, but also make sure that the code does not go into a large or infinite loop.
Phase: Implementation
Use the volatile type modifier for critical variables to avoid unexpected compiler optimization or reordering. This does not necessarily solve the synchronization problem, but it can help.
Phases: Architecture and Design; Operation
Strategy: Environment Hardening
Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations | 3,879 |
kamailio | e1d8008a09d9390ebaf698abe8909e10dfec4097 | int tmx_check_pretran(sip_msg_t *msg)
{
unsigned int chid;
unsigned int slotid;
int dsize;
struct via_param *vbr;
str scallid;
str scseqmet;
str scseqnum;
str sftag;
str svbranch = {NULL, 0};
pretran_t *it;
if(_tmx_ptran_table==NULL) {
LM_ERR("pretran hash table not initialized yet\n");
return -1;
}
if(get_route_type()!=REQUEST_ROUTE) {
LM_ERR("invalid usage - not in request route\n");
return -1;
}
if(msg->first_line.type!=SIP_REQUEST) {
LM_ERR("invalid usage - not a sip request\n");
return -1;
}
if(parse_headers(msg, HDR_FROM_F|HDR_VIA1_F|HDR_CALLID_F|HDR_CSEQ_F, 0)<0) {
LM_ERR("failed to parse required headers\n");
return -1;
}
if(msg->cseq==NULL || msg->cseq->parsed==NULL) {
LM_ERR("failed to parse cseq headers\n");
return -1;
}
if(get_cseq(msg)->method_id==METHOD_ACK
|| get_cseq(msg)->method_id==METHOD_CANCEL) {
LM_DBG("no pre-transaction management for ACK or CANCEL\n");
return -1;
}
if (msg->via1==0) {
LM_ERR("failed to get Via header\n");
return -1;
}
if (parse_from_header(msg)<0 || get_from(msg)->tag_value.len==0) {
LM_ERR("failed to get From header\n");
return -1;
}
if (msg->callid==NULL || msg->callid->body.s==NULL) {
LM_ERR("failed to parse callid headers\n");
return -1;
}
vbr = msg->via1->branch;
scallid = msg->callid->body;
trim(&scallid);
scseqmet = get_cseq(msg)->method;
trim(&scseqmet);
scseqnum = get_cseq(msg)->number;
trim(&scseqnum);
sftag = get_from(msg)->tag_value;
trim(&sftag);
chid = get_hash1_raw(msg->callid->body.s, msg->callid->body.len);
slotid = chid & (_tmx_ptran_size-1);
if(unlikely(_tmx_proc_ptran == NULL)) {
_tmx_proc_ptran = (pretran_t*)shm_malloc(sizeof(pretran_t));
if(_tmx_proc_ptran == NULL) {
LM_ERR("not enough memory for pretran structure\n");
return -1;
}
memset(_tmx_proc_ptran, 0, sizeof(pretran_t));
_tmx_proc_ptran->pid = my_pid();
}
dsize = scallid.len + scseqnum.len + scseqmet.len
+ sftag.len + 4;
if(likely(vbr!=NULL)) {
svbranch = vbr->value;
trim(&svbranch);
dsize += svbranch.len;
}
if(dsize<256) dsize = 256;
tmx_pretran_unlink();
if(dsize > _tmx_proc_ptran->dbuf.len) {
if(_tmx_proc_ptran->dbuf.s) shm_free(_tmx_proc_ptran->dbuf.s);
_tmx_proc_ptran->dbuf.s = (char*)shm_malloc(dsize);
if(_tmx_proc_ptran->dbuf.s==NULL) {
LM_ERR("not enough memory for pretran data\n");
return -1;
}
_tmx_proc_ptran->dbuf.len = dsize;
}
_tmx_proc_ptran->hid = chid;
_tmx_proc_ptran->cseqmetid = (get_cseq(msg))->method_id;
_tmx_proc_ptran->callid.s = _tmx_proc_ptran->dbuf.s;
memcpy(_tmx_proc_ptran->callid.s, scallid.s, scallid.len);
_tmx_proc_ptran->callid.len = scallid.len;
_tmx_proc_ptran->callid.s[_tmx_proc_ptran->callid.len] = '\0';
_tmx_proc_ptran->ftag.s = _tmx_proc_ptran->callid.s
+ _tmx_proc_ptran->callid.len + 1;
memcpy(_tmx_proc_ptran->ftag.s, sftag.s, sftag.len);
_tmx_proc_ptran->ftag.len = sftag.len;
_tmx_proc_ptran->ftag.s[_tmx_proc_ptran->ftag.len] = '\0';
_tmx_proc_ptran->cseqnum.s = _tmx_proc_ptran->ftag.s
+ _tmx_proc_ptran->ftag.len + 1;
memcpy(_tmx_proc_ptran->cseqnum.s, scseqnum.s, scseqnum.len);
_tmx_proc_ptran->cseqnum.len = scseqnum.len;
_tmx_proc_ptran->cseqnum.s[_tmx_proc_ptran->cseqnum.len] = '\0';
_tmx_proc_ptran->cseqmet.s = _tmx_proc_ptran->cseqnum.s
+ _tmx_proc_ptran->cseqnum.len + 1;
memcpy(_tmx_proc_ptran->cseqmet.s, scseqmet.s, scseqmet.len);
_tmx_proc_ptran->cseqmet.len = scseqmet.len;
_tmx_proc_ptran->cseqmet.s[_tmx_proc_ptran->cseqmet.len] = '\0';
if(likely(vbr!=NULL)) {
_tmx_proc_ptran->vbranch.s = _tmx_proc_ptran->cseqmet.s
+ _tmx_proc_ptran->cseqmet.len + 1;
memcpy(_tmx_proc_ptran->vbranch.s, svbranch.s, svbranch.len);
_tmx_proc_ptran->vbranch.len = svbranch.len;
_tmx_proc_ptran->vbranch.s[_tmx_proc_ptran->vbranch.len] = '\0';
} else {
_tmx_proc_ptran->vbranch.s = NULL;
_tmx_proc_ptran->vbranch.len = 0;
}
lock_get(&_tmx_ptran_table[slotid].lock);
it = _tmx_ptran_table[slotid].plist;
tmx_pretran_link_safe(slotid);
for(; it!=NULL; it=it->next) {
if(_tmx_proc_ptran->hid != it->hid
|| _tmx_proc_ptran->cseqmetid != it->cseqmetid
|| _tmx_proc_ptran->callid.len != it->callid.len
|| _tmx_proc_ptran->ftag.len != it->ftag.len
|| _tmx_proc_ptran->cseqmet.len != it->cseqmet.len
|| _tmx_proc_ptran->cseqnum.len != it->cseqnum.len)
continue;
if(_tmx_proc_ptran->vbranch.s != NULL && it->vbranch.s != NULL) {
if(_tmx_proc_ptran->vbranch.len != it->vbranch.len)
continue;
/* shortcut - check last char in Via branch
* - kamailio/ser adds there branch index => in case of paralel
* forking by previous hop, catch it here quickly */
if(_tmx_proc_ptran->vbranch.s[it->vbranch.len-1]
!= it->vbranch.s[it->vbranch.len-1])
continue;
if(memcmp(_tmx_proc_ptran->vbranch.s,
it->vbranch.s, it->vbranch.len)!=0)
continue;
/* shall stop by matching magic cookie?
* if (vbr && vbr->value.s && vbr->value.len > MCOOKIE_LEN
* && memcmp(vbr->value.s, MCOOKIE, MCOOKIE_LEN)==0) {
* LM_DBG("rfc3261 cookie found in Via branch\n");
* }
*/
}
if(memcmp(_tmx_proc_ptran->callid.s,
it->callid.s, it->callid.len)!=0
|| memcmp(_tmx_proc_ptran->ftag.s,
it->ftag.s, it->ftag.len)!=0
|| memcmp(_tmx_proc_ptran->cseqnum.s,
it->cseqnum.s, it->cseqnum.len)!=0)
continue;
if((it->cseqmetid==METHOD_OTHER || it->cseqmetid==METHOD_UNDEF)
&& memcmp(_tmx_proc_ptran->cseqmet.s,
it->cseqmet.s, it->cseqmet.len)!=0)
continue;
LM_DBG("matched another pre-transaction by pid %d for [%.*s]\n",
it->pid, it->callid.len, it->callid.s);
lock_release(&_tmx_ptran_table[slotid].lock);
return 1;
}
lock_release(&_tmx_ptran_table[slotid].lock);
return 0;
}
| 1 | CVE-2018-8828 | 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,702 |
Chrome | bc1f34b9be509f1404f0bb1ba1947614d5f0bcd1 | std::unique_ptr<service_manager::Service> CreateMediaService() {
return std::unique_ptr<service_manager::Service>(
new ::media::MediaService(base::MakeUnique<CdmMojoMediaClient>()));
}
| 1 | CVE-2015-1280 | 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,763 |
ghostscript | 6d444c273da5499a4cd72f21cb6d4c9a5256807d | gs_main_init1(gs_main_instance * minst)
{
if (minst->init_done < 1) {
gs_dual_memory_t idmem;
int code =
ialloc_init(&idmem, minst->heap,
minst->memory_clump_size, gs_have_level2());
if (code < 0)
return code;
code = gs_lib_init1((gs_memory_t *)idmem.space_system);
if (code < 0)
return code;
alloc_save_init(&idmem);
{
gs_memory_t *mem = (gs_memory_t *)idmem.space_system;
name_table *nt = names_init(minst->name_table_size,
idmem.space_system);
if (nt == 0)
return_error(gs_error_VMerror);
mem->gs_lib_ctx->gs_name_table = nt;
code = gs_register_struct_root(mem, NULL,
(void **)&mem->gs_lib_ctx->gs_name_table,
"the_gs_name_table");
"the_gs_name_table");
if (code < 0)
return code;
}
code = obj_init(&minst->i_ctx_p, &idmem); /* requires name_init */
if (code < 0)
if (code < 0)
return code;
code = i_iodev_init(minst->i_ctx_p);
if (code < 0)
return code;
minst->init_done = 1;
}
return 0;
}
| 1 | CVE-2016-7976 | 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,582 |
file | c0c0032b9e9eb57b91fefef905a3b018bab492d9 | check_fmt(struct magic_set *ms, struct magic *m)
{
regex_t rx;
int rc, rv = -1;
char *old_lc_ctype;
if (strchr(m->desc, '%') == NULL)
return 0;
old_lc_ctype = setlocale(LC_CTYPE, NULL);
assert(old_lc_ctype != NULL);
old_lc_ctype = strdup(old_lc_ctype);
assert(old_lc_ctype != NULL);
(void)setlocale(LC_CTYPE, "C");
rc = regcomp(&rx, "%[-0-9\\.]*s", REG_EXTENDED|REG_NOSUB);
if (rc) {
char errmsg[512];
(void)regerror(rc, &rx, errmsg, sizeof(errmsg));
file_magerror(ms, "regex error %d, (%s)", rc, errmsg);
} else {
rc = regexec(&rx, m->desc, 0, 0, 0);
regfree(&rx);
rv = !rc;
}
(void)setlocale(LC_CTYPE, old_lc_ctype);
free(old_lc_ctype);
return rv;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,336 |
Android | 6fe85f7e15203e48df2cc3e8e1c4bc6ad49dc968 | MPEG4Source::MPEG4Source(
const sp<MPEG4Extractor> &owner,
const sp<MetaData> &format,
const sp<DataSource> &dataSource,
int32_t timeScale,
const sp<SampleTable> &sampleTable,
Vector<SidxEntry> &sidx,
const Trex *trex,
off64_t firstMoofOffset)
: mOwner(owner),
mFormat(format),
mDataSource(dataSource),
mTimescale(timeScale),
mSampleTable(sampleTable),
mCurrentSampleIndex(0),
mCurrentFragmentIndex(0),
mSegments(sidx),
mTrex(trex),
mFirstMoofOffset(firstMoofOffset),
mCurrentMoofOffset(firstMoofOffset),
mCurrentTime(0),
mCurrentSampleInfoAllocSize(0),
mCurrentSampleInfoSizes(NULL),
mCurrentSampleInfoOffsetsAllocSize(0),
mCurrentSampleInfoOffsets(NULL),
mIsAVC(false),
mIsHEVC(false),
mNALLengthSize(0),
mStarted(false),
mGroup(NULL),
mBuffer(NULL),
mWantsNALFragments(false),
mSrcBuffer(NULL) {
memset(&mTrackFragmentHeaderInfo, 0, sizeof(mTrackFragmentHeaderInfo));
mFormat->findInt32(kKeyCryptoMode, &mCryptoMode);
mDefaultIVSize = 0;
mFormat->findInt32(kKeyCryptoDefaultIVSize, &mDefaultIVSize);
uint32_t keytype;
const void *key;
size_t keysize;
if (mFormat->findData(kKeyCryptoKey, &keytype, &key, &keysize)) {
CHECK(keysize <= 16);
memset(mCryptoKey, 0, 16);
memcpy(mCryptoKey, key, keysize);
}
const char *mime;
bool success = mFormat->findCString(kKeyMIMEType, &mime);
CHECK(success);
mIsAVC = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC);
mIsHEVC = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_HEVC);
if (mIsAVC) {
uint32_t type;
const void *data;
size_t size;
CHECK(format->findData(kKeyAVCC, &type, &data, &size));
const uint8_t *ptr = (const uint8_t *)data;
CHECK(size >= 7);
CHECK_EQ((unsigned)ptr[0], 1u); // configurationVersion == 1
mNALLengthSize = 1 + (ptr[4] & 3);
} else if (mIsHEVC) {
uint32_t type;
const void *data;
size_t size;
CHECK(format->findData(kKeyHVCC, &type, &data, &size));
const uint8_t *ptr = (const uint8_t *)data;
CHECK(size >= 7);
CHECK_EQ((unsigned)ptr[0], 1u); // configurationVersion == 1
mNALLengthSize = 1 + (ptr[14 + 7] & 3);
}
CHECK(format->findInt32(kKeyTrackID, &mTrackId));
if (mFirstMoofOffset != 0) {
off64_t offset = mFirstMoofOffset;
parseChunk(&offset);
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,453 |
haproxy | efbbdf72992cd20458259962346044cafd9331c0 | static struct dns_resolution *dns_pick_resolution(struct dns_resolvers *resolvers,
char **hostname_dn, int hostname_dn_len,
int query_type)
{
struct dns_resolution *res;
if (!*hostname_dn)
goto from_pool;
/* Search for same hostname and query type in resolutions.curr */
list_for_each_entry(res, &resolvers->resolutions.curr, list) {
if (!res->hostname_dn)
continue;
if ((query_type == res->prefered_query_type) &&
hostname_dn_len == res->hostname_dn_len &&
!memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
return res;
}
/* Search for same hostname and query type in resolutions.wait */
list_for_each_entry(res, &resolvers->resolutions.wait, list) {
if (!res->hostname_dn)
continue;
if ((query_type == res->prefered_query_type) &&
hostname_dn_len == res->hostname_dn_len &&
!memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
return res;
}
from_pool:
/* No resolution could be found, so let's allocate a new one */
res = pool_alloc(dns_resolution_pool);
if (res) {
memset(res, 0, sizeof(*res));
res->resolvers = resolvers;
res->uuid = resolution_uuid;
res->status = RSLV_STATUS_NONE;
res->step = RSLV_STEP_NONE;
res->last_valid = now_ms;
LIST_INIT(&res->requesters);
LIST_INIT(&res->response.answer_list);
res->prefered_query_type = query_type;
res->query_type = query_type;
res->hostname_dn = *hostname_dn;
res->hostname_dn_len = hostname_dn_len;
++resolution_uuid;
/* Move the resolution to the resolvers wait queue */
LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
}
return res;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,377 |
linux | bc3aae2bbac46dd894c89db5d5e98f7f0ef9e205 | void ipv4_redirect(struct sk_buff *skb, struct net *net,
int oif, u32 mark, u8 protocol, int flow_flags)
{
const struct iphdr *iph = (const struct iphdr *) skb->data;
struct flowi4 fl4;
struct rtable *rt;
__build_flow_key(net, &fl4, NULL, iph, oif,
RT_TOS(iph->tos), protocol, mark, flow_flags);
rt = __ip_route_output_key(net, &fl4);
if (!IS_ERR(rt)) {
__ip_do_redirect(rt, skb, &fl4, false);
ip_rt_put(rt);
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,402 |
Chrome | 2953a669ec0a32a25c6250d34bf895ec0eb63d27 | getMyanmarCharClass (HB_UChar16 ch)
{
if (ch == Mymr_C_SIGN_ZWJ)
return Mymr_CC_ZERO_WIDTH_J_MARK;
if (ch == Mymr_C_SIGN_ZWNJ)
return Mymr_CC_ZERO_WIDTH_NJ_MARK;
if (ch < 0x1000 || ch > 0x105f)
return Mymr_CC_RESERVED;
return mymrCharClasses[ch - 0x1000];
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,205 |
Chrome | 67e38708af8e99569365326e378b806088c83f5a | const char** GetSavableSchemes() {
return const_cast<const char**>(g_savable_schemes);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,015 |
Android | 560ccdb509a7b86186fac0fce1b25bd9a3e6a6e8 | OMX_ERRORTYPE omx_vdec::set_config(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_INDEXTYPE configIndex,
OMX_IN OMX_PTR configData)
{
(void) hComp;
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("Get Config in Invalid State");
return OMX_ErrorInvalidState;
}
OMX_ERRORTYPE ret = OMX_ErrorNone;
OMX_VIDEO_CONFIG_NALSIZE *pNal;
DEBUG_PRINT_LOW("Set Config Called");
if (configIndex == (OMX_INDEXTYPE)OMX_IndexVendorVideoExtraData) {
OMX_VENDOR_EXTRADATATYPE *config = (OMX_VENDOR_EXTRADATATYPE *) configData;
DEBUG_PRINT_LOW("Index OMX_IndexVendorVideoExtraData called");
if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.avc") ||
!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mvc")) {
DEBUG_PRINT_LOW("Index OMX_IndexVendorVideoExtraData AVC");
OMX_U32 extra_size;
nal_length = (config->pData[4] & 0x03) + 1;
extra_size = 0;
if (nal_length > 2) {
/* Presently we assume that only one SPS and one PPS in AvC1 Atom */
extra_size = (nal_length - 2) * 2;
}
OMX_U8 *pSrcBuf = (OMX_U8 *) (&config->pData[6]);
OMX_U8 *pDestBuf;
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize - 6 - 1 + extra_size;
m_vendor_config.pData = (OMX_U8 *) malloc(m_vendor_config.nDataSize);
OMX_U32 len;
OMX_U8 index = 0;
pDestBuf = m_vendor_config.pData;
DEBUG_PRINT_LOW("Rxd SPS+PPS nPortIndex[%u] len[%u] data[%p]",
(unsigned int)m_vendor_config.nPortIndex,
(unsigned int)m_vendor_config.nDataSize,
m_vendor_config.pData);
while (index < 2) {
uint8 *psize;
len = *pSrcBuf;
len = len << 8;
len |= *(pSrcBuf + 1);
psize = (uint8 *) & len;
memcpy(pDestBuf + nal_length, pSrcBuf + 2,len);
for (unsigned int i = 0; i < nal_length; i++) {
pDestBuf[i] = psize[nal_length - 1 - i];
}
pDestBuf += len + nal_length;
pSrcBuf += len + 2;
index++;
pSrcBuf++; // skip picture param set
len = 0;
}
} else if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg4") ||
!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg2")) {
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize;
m_vendor_config.pData = (OMX_U8 *) malloc((config->nDataSize));
memcpy(m_vendor_config.pData, config->pData,config->nDataSize);
} else if (!strcmp(drv_ctx.kind, "OMX.qcom.video.decoder.vc1")) {
if (m_vendor_config.pData) {
free(m_vendor_config.pData);
m_vendor_config.pData = NULL;
m_vendor_config.nDataSize = 0;
}
if (((*((OMX_U32 *) config->pData)) &
VC1_SP_MP_START_CODE_MASK) ==
VC1_SP_MP_START_CODE) {
DEBUG_PRINT_LOW("set_config - VC1 simple/main profile");
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize;
m_vendor_config.pData =
(OMX_U8 *) malloc(config->nDataSize);
memcpy(m_vendor_config.pData, config->pData,
config->nDataSize);
m_vc1_profile = VC1_SP_MP_RCV;
} else if (*((OMX_U32 *) config->pData) == VC1_AP_SEQ_START_CODE) {
DEBUG_PRINT_LOW("set_config - VC1 Advance profile");
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize;
m_vendor_config.pData =
(OMX_U8 *) malloc((config->nDataSize));
memcpy(m_vendor_config.pData, config->pData,
config->nDataSize);
m_vc1_profile = VC1_AP;
} else if ((config->nDataSize == VC1_STRUCT_C_LEN)) {
DEBUG_PRINT_LOW("set_config - VC1 Simple/Main profile struct C only");
m_vendor_config.nPortIndex = config->nPortIndex;
m_vendor_config.nDataSize = config->nDataSize;
m_vendor_config.pData = (OMX_U8*)malloc(config->nDataSize);
memcpy(m_vendor_config.pData,config->pData,config->nDataSize);
m_vc1_profile = VC1_SP_MP_RCV;
} else {
DEBUG_PRINT_LOW("set_config - Error: Unknown VC1 profile");
}
}
return ret;
} else if (configIndex == OMX_IndexConfigVideoNalSize) {
struct v4l2_control temp;
temp.id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT;
pNal = reinterpret_cast < OMX_VIDEO_CONFIG_NALSIZE * >(configData);
switch (pNal->nNaluBytes) {
case 0:
temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_STARTCODES;
break;
case 2:
temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_TWO_BYTE_LENGTH;
break;
case 4:
temp.value = V4L2_MPEG_VIDC_VIDEO_NAL_FORMAT_FOUR_BYTE_LENGTH;
break;
default:
return OMX_ErrorUnsupportedSetting;
}
if (!arbitrary_bytes) {
/* In arbitrary bytes mode, the assembler strips out nal size and replaces
* with start code, so only need to notify driver in frame by frame mode */
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &temp)) {
DEBUG_PRINT_ERROR("Failed to set V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT");
return OMX_ErrorHardware;
}
}
nal_length = pNal->nNaluBytes;
m_frame_parser.init_nal_length(nal_length);
DEBUG_PRINT_LOW("OMX_IndexConfigVideoNalSize called with Size %d", nal_length);
return ret;
} else if ((int)configIndex == (int)OMX_IndexVendorVideoFrameRate) {
OMX_VENDOR_VIDEOFRAMERATE *config = (OMX_VENDOR_VIDEOFRAMERATE *) configData;
DEBUG_PRINT_HIGH("Index OMX_IndexVendorVideoFrameRate %u", (unsigned int)config->nFps);
if (config->nPortIndex == OMX_CORE_INPUT_PORT_INDEX) {
if (config->bEnabled) {
if ((config->nFps >> 16) > 0) {
DEBUG_PRINT_HIGH("set_config: frame rate set by omx client : %u",
(unsigned int)config->nFps >> 16);
Q16ToFraction(config->nFps, drv_ctx.frame_rate.fps_numerator,
drv_ctx.frame_rate.fps_denominator);
if (!drv_ctx.frame_rate.fps_numerator) {
DEBUG_PRINT_ERROR("Numerator is zero setting to 30");
drv_ctx.frame_rate.fps_numerator = 30;
}
if (drv_ctx.frame_rate.fps_denominator) {
drv_ctx.frame_rate.fps_numerator = (int)
drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator;
}
drv_ctx.frame_rate.fps_denominator = 1;
frm_int = drv_ctx.frame_rate.fps_denominator * 1e6 /
drv_ctx.frame_rate.fps_numerator;
struct v4l2_outputparm oparm;
/*XXX: we're providing timing info as seconds per frame rather than frames
* per second.*/
oparm.timeperframe.numerator = drv_ctx.frame_rate.fps_denominator;
oparm.timeperframe.denominator = drv_ctx.frame_rate.fps_numerator;
struct v4l2_streamparm sparm;
sparm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
sparm.parm.output = oparm;
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_PARM, &sparm)) {
DEBUG_PRINT_ERROR("Unable to convey fps info to driver, \
performance might be affected");
ret = OMX_ErrorHardware;
}
client_set_fps = true;
} else {
DEBUG_PRINT_ERROR("Frame rate not supported.");
ret = OMX_ErrorUnsupportedSetting;
}
} else {
DEBUG_PRINT_HIGH("set_config: Disabled client's frame rate");
client_set_fps = false;
}
} else {
DEBUG_PRINT_ERROR(" Set_config: Bad Port idx %d",
(int)config->nPortIndex);
ret = OMX_ErrorBadPortIndex;
}
return ret;
} else if ((int)configIndex == (int)OMX_QcomIndexConfigPerfLevel) {
OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf =
(OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData;
struct v4l2_control control;
DEBUG_PRINT_LOW("Set perf level: %d", perf->ePerfLevel);
control.id = V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL;
switch (perf->ePerfLevel) {
case OMX_QCOM_PerfLevelNominal:
control.value = V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL;
break;
case OMX_QCOM_PerfLevelTurbo:
control.value = V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO;
break;
default:
ret = OMX_ErrorUnsupportedSetting;
break;
}
if (ret == OMX_ErrorNone) {
ret = (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control) < 0) ?
OMX_ErrorUnsupportedSetting : OMX_ErrorNone;
}
return ret;
} else if ((int)configIndex == (int)OMX_IndexConfigPriority) {
OMX_PARAM_U32TYPE *priority = (OMX_PARAM_U32TYPE *)configData;
DEBUG_PRINT_LOW("Set_config: priority %d", priority->nU32);
struct v4l2_control control;
control.id = V4L2_CID_MPEG_VIDC_VIDEO_PRIORITY;
if (priority->nU32 == 0)
control.value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_ENABLE;
else
control.value = V4L2_MPEG_VIDC_VIDEO_PRIORITY_REALTIME_DISABLE;
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) {
DEBUG_PRINT_ERROR("Failed to set Priority");
ret = OMX_ErrorUnsupportedSetting;
}
return ret;
} else if ((int)configIndex == (int)OMX_IndexConfigOperatingRate) {
OMX_PARAM_U32TYPE *rate = (OMX_PARAM_U32TYPE *)configData;
DEBUG_PRINT_LOW("Set_config: operating-rate %u fps", rate->nU32 >> 16);
struct v4l2_control control;
control.id = V4L2_CID_MPEG_VIDC_VIDEO_OPERATING_RATE;
control.value = rate->nU32;
if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) {
ret = errno == -EBUSY ? OMX_ErrorInsufficientResources :
OMX_ErrorUnsupportedSetting;
DEBUG_PRINT_ERROR("Failed to set operating rate %u fps (%s)",
rate->nU32 >> 16, errno == -EBUSY ? "HW Overload" : strerror(errno));
}
return ret;
}
return OMX_ErrorNotImplemented;
}
| 1 | CVE-2016-2480 | 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. | 453 |
FFmpeg | e724bd1dd9efea3abb8586d6644ec07694afceae | static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
UtvideoContext *c = avctx->priv_data;
int i, j;
const uint8_t *plane_start[5];
int plane_size, max_slice_size = 0, slice_start, slice_end, slice_size;
int ret;
GetByteContext gb;
ThreadFrame frame = { .f = data };
if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
return ret;
/* parse plane structure to get frame flags and validate slice offsets */
bytestream2_init(&gb, buf, buf_size);
for (i = 0; i < c->planes; i++) {
plane_start[i] = gb.buffer;
if (bytestream2_get_bytes_left(&gb) < 256 + 4 * c->slices) {
av_log(avctx, AV_LOG_ERROR, "Insufficient data for a plane\n");
return AVERROR_INVALIDDATA;
}
bytestream2_skipu(&gb, 256);
slice_start = 0;
slice_end = 0;
for (j = 0; j < c->slices; j++) {
slice_end = bytestream2_get_le32u(&gb);
slice_size = slice_end - slice_start;
if (slice_end < 0 || slice_size < 0 ||
bytestream2_get_bytes_left(&gb) < slice_end) {
av_log(avctx, AV_LOG_ERROR, "Incorrect slice size\n");
return AVERROR_INVALIDDATA;
}
slice_start = slice_end;
max_slice_size = FFMAX(max_slice_size, slice_size);
}
plane_size = slice_end;
bytestream2_skipu(&gb, plane_size);
}
plane_start[c->planes] = gb.buffer;
if (bytestream2_get_bytes_left(&gb) < c->frame_info_size) {
av_log(avctx, AV_LOG_ERROR, "Not enough data for frame information\n");
return AVERROR_INVALIDDATA;
}
c->frame_info = bytestream2_get_le32u(&gb);
av_log(avctx, AV_LOG_DEBUG, "frame information flags %"PRIX32"\n",
c->frame_info);
c->frame_pred = (c->frame_info >> 8) & 3;
if (c->frame_pred == PRED_GRADIENT) {
avpriv_request_sample(avctx, "Frame with gradient prediction");
return AVERROR_PATCHWELCOME;
}
av_fast_malloc(&c->slice_bits, &c->slice_bits_size,
max_slice_size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!c->slice_bits) {
av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer\n");
return AVERROR(ENOMEM);
}
switch (c->avctx->pix_fmt) {
case AV_PIX_FMT_RGB24:
case AV_PIX_FMT_RGBA:
for (i = 0; i < c->planes; i++) {
ret = decode_plane(c, i, frame.f->data[0] + ff_ut_rgb_order[i],
c->planes, frame.f->linesize[0], avctx->width,
avctx->height, plane_start[i],
c->frame_pred == PRED_LEFT);
if (ret)
return ret;
if (c->frame_pred == PRED_MEDIAN) {
if (!c->interlaced) {
restore_median(frame.f->data[0] + ff_ut_rgb_order[i],
c->planes, frame.f->linesize[0], avctx->width,
avctx->height, c->slices, 0);
} else {
restore_median_il(frame.f->data[0] + ff_ut_rgb_order[i],
c->planes, frame.f->linesize[0],
avctx->width, avctx->height, c->slices,
0);
}
}
}
restore_rgb_planes(frame.f->data[0], c->planes, frame.f->linesize[0],
avctx->width, avctx->height);
break;
case AV_PIX_FMT_YUV420P:
for (i = 0; i < 3; i++) {
ret = decode_plane(c, i, frame.f->data[i], 1, frame.f->linesize[i],
avctx->width >> !!i, avctx->height >> !!i,
plane_start[i], c->frame_pred == PRED_LEFT);
if (ret)
return ret;
if (c->frame_pred == PRED_MEDIAN) {
if (!c->interlaced) {
restore_median(frame.f->data[i], 1, frame.f->linesize[i],
avctx->width >> !!i, avctx->height >> !!i,
c->slices, !i);
} else {
restore_median_il(frame.f->data[i], 1, frame.f->linesize[i],
avctx->width >> !!i,
avctx->height >> !!i,
c->slices, !i);
}
}
}
break;
case AV_PIX_FMT_YUV422P:
for (i = 0; i < 3; i++) {
ret = decode_plane(c, i, frame.f->data[i], 1, frame.f->linesize[i],
avctx->width >> !!i, avctx->height,
plane_start[i], c->frame_pred == PRED_LEFT);
if (ret)
return ret;
if (c->frame_pred == PRED_MEDIAN) {
if (!c->interlaced) {
restore_median(frame.f->data[i], 1, frame.f->linesize[i],
avctx->width >> !!i, avctx->height,
c->slices, 0);
} else {
restore_median_il(frame.f->data[i], 1, frame.f->linesize[i],
avctx->width >> !!i, avctx->height,
c->slices, 0);
}
}
}
break;
}
frame.f->key_frame = 1;
frame.f->pict_type = AV_PICTURE_TYPE_I;
frame.f->interlaced_frame = !!c->interlaced;
*got_frame = 1;
/* always report that the buffer was completely consumed */
return buf_size;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,029 |
exiv2 | 6fa2e31206127bd8bcac0269311f3775a8d6ea21 | void PngImage::readMetadata()
{
#ifdef DEBUG
std::cerr << "Exiv2::PngImage::readMetadata: Reading PNG file " << io_->path() << std::endl;
#endif
if (io_->open() != 0)
{
throw Error(kerDataSourceOpenFailed, io_->path(), strError());
}
IoCloser closer(*io_);
if (!isPngType(*io_, true)) {
throw Error(kerNotAnImage, "PNG");
}
clearMetadata();
const long imgSize = (long) io_->size();
DataBuf cheaderBuf(8); // Chunk header: 4 bytes (data size) + 4 bytes (chunk type).
while(!io_->eof())
{
std::memset(cheaderBuf.pData_, 0x0, cheaderBuf.size_);
readChunk(cheaderBuf, *io_); // Read chunk header.
// Decode chunk data length.
uint32_t chunkLength = Exiv2::getULong(cheaderBuf.pData_, Exiv2::bigEndian);
long pos = io_->tell();
if (pos == -1 ||
chunkLength > uint32_t(0x7FFFFFFF) ||
static_cast<long>(chunkLength) > imgSize - pos) {
throw Exiv2::Error(kerFailedToReadImageData);
}
std::string chunkType(reinterpret_cast<char *>(cheaderBuf.pData_) + 4, 4);
#ifdef DEBUG
std::cout << "Exiv2::PngImage::readMetadata: chunk type: " << chunkType
<< " length: " << chunkLength << std::endl;
#endif
/// \todo analyse remaining chunks of the standard
// Perform a chunk triage for item that we need.
if (chunkType == "IEND" || chunkType == "IHDR" || chunkType == "tEXt" || chunkType == "zTXt" ||
chunkType == "iTXt" || chunkType == "iCCP") {
DataBuf chunkData(chunkLength);
readChunk(chunkData, *io_); // Extract chunk data.
if (chunkType == "IEND") {
return; // Last chunk found: we stop parsing.
} else if (chunkType == "IHDR" && chunkData.size_ >= 8) {
PngChunk::decodeIHDRChunk(chunkData, &pixelWidth_, &pixelHeight_);
} else if (chunkType == "tEXt") {
PngChunk::decodeTXTChunk(this, chunkData, PngChunk::tEXt_Chunk);
} else if (chunkType == "zTXt") {
PngChunk::decodeTXTChunk(this, chunkData, PngChunk::zTXt_Chunk);
} else if (chunkType == "iTXt") {
PngChunk::decodeTXTChunk(this, chunkData, PngChunk::iTXt_Chunk);
} else if (chunkType == "iCCP") {
// The ICC profile name can vary from 1-79 characters.
uint32_t iccOffset = 0;
while (iccOffset < 80 && iccOffset < chunkLength) {
if (chunkData.pData_[iccOffset++] == 0x00) {
break;
}
}
profileName_ = std::string(reinterpret_cast<char *>(chunkData.pData_), iccOffset-1);
++iccOffset; // +1 = 'compressed' flag
zlibToDataBuf(chunkData.pData_ + iccOffset, chunkLength - iccOffset, iccProfile_);
#ifdef DEBUG
std::cout << "Exiv2::PngImage::readMetadata: profile name: " << profileName_ << std::endl;
std::cout << "Exiv2::PngImage::readMetadata: iccProfile.size_ (uncompressed) : "
<< iccProfile_.size_ << std::endl;
#endif
}
// Set chunkLength to 0 in case we have read a supported chunk type. Otherwise, we need to seek the
// file to the next chunk position.
chunkLength = 0;
}
// Move to the next chunk: chunk data size + 4 CRC bytes.
#ifdef DEBUG
std::cout << "Exiv2::PngImage::readMetadata: Seek to offset: " << chunkLength + 4 << std::endl;
#endif
io_->seek(chunkLength + 4 , BasicIo::cur);
if (io_->error() || io_->eof()) {
throw Error(kerFailedToReadImageData);
}
}
} // PngImage::readMetadata | 1 | CVE-2019-13109 | 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. | 5,564 |
ImageMagick | e92492afac23315358850e5e050144930049e9cb | static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
SGIInfo
iris_info;
size_t
bytes_per_pixel,
quantum;
ssize_t
count,
y,
z;
unsigned char
*pixels;
/*
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 SGI raster header.
*/
(void) memset(&iris_info,0,sizeof(iris_info));
iris_info.magic=ReadBlobMSBShort(image);
do
{
/*
Verify SGI identifier.
*/
if (iris_info.magic != 0x01DA)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.storage=(unsigned char) ReadBlobByte(image);
switch (iris_info.storage)
{
case 0x00: image->compression=NoCompression; break;
case 0x01: image->compression=RLECompression; break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image);
if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.dimension=ReadBlobMSBShort(image);
if ((iris_info.dimension == 0) || (iris_info.dimension > 3))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.columns=ReadBlobMSBShort(image);
iris_info.rows=ReadBlobMSBShort(image);
iris_info.depth=ReadBlobMSBShort(image);
if ((iris_info.depth == 0) || (iris_info.depth > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.minimum_value=ReadBlobMSBLong(image);
iris_info.maximum_value=ReadBlobMSBLong(image);
iris_info.sans=ReadBlobMSBLong(image);
count=ReadBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
if ((size_t) count != sizeof(iris_info.name))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.name[sizeof(iris_info.name)-1]='\0';
if (*iris_info.name != '\0')
(void) SetImageProperty(image,"label",iris_info.name,exception);
iris_info.pixel_format=ReadBlobMSBLong(image);
if (iris_info.pixel_format != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler);
if ((size_t) count != sizeof(iris_info.filler))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=iris_info.columns;
image->rows=iris_info.rows;
image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.pixel_format == 0)
image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,
MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.depth < 3)
{
image->storage_class=PseudoClass;
image->colors=(size_t) (iris_info.bytes_per_pixel > 1 ? 65535 : 256);
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
(void) SetImageBackgroundColor(image,exception);
/*
Allocate SGI pixels.
*/
bytes_per_pixel=(size_t) iris_info.bytes_per_pixel;
number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows;
if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t)
(4*bytes_per_pixel*number_pixels)))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
(void) memset(pixels,0,iris_info.columns*iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if ((int) iris_info.storage != 0x01)
{
unsigned char
*scanline;
/*
Read standard image format.
*/
scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns,
bytes_per_pixel*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels+bytes_per_pixel*z;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline);
if (EOFBlob(image) != MagickFalse)
break;
if (bytes_per_pixel == 2)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[2*x];
*(p+1)=scanline[2*x+1];
p+=8;
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[x];
p+=4;
}
}
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
}
else
{
MemoryInfo
*packet_info;
size_t
*runlength;
ssize_t
offset,
*offsets;
unsigned char
*packets;
unsigned int
data_order;
/*
Read runlength-encoded image format.
*/
offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL*
sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info != (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
offsets[i]=(ssize_t) ReadBlobMSBSignedLong(image);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
{
runlength[i]=ReadBlobMSBLong(image);
if (runlength[i] > (4*(size_t) iris_info.columns+10))
{
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
}
/*
Check data order.
*/
offset=0;
data_order=0;
for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++)
for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++)
{
if (offsets[y+z*iris_info.rows] < offset)
data_order=1;
offset=offsets[y+z*iris_info.rows];
}
offset=(ssize_t) TellBlob(image);
if (data_order == 1)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset,
SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
(ssize_t) iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
{
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
p+=(iris_info.columns*4*bytes_per_pixel);
}
}
}
else
{
MagickOffsetType
position;
position=TellBlob(image);
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset,
SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
(ssize_t) iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
{
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
}
p+=(iris_info.columns*4*bytes_per_pixel);
}
offset=(ssize_t) SeekBlob(image,position,SEEK_SET);
}
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
}
/*
Convert SGI raster image to pixel packets.
*/
if (image->storage_class == DirectClass)
{
/*
Convert SGI image to DirectClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleShortToQuantum((unsigned short)
((*(p+0) << 8) | (*(p+1)))),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short)
((*(p+2) << 8) | (*(p+3)))),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short)
((*(p+4) << 8) | (*(p+5)))),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleShortToQuantum((unsigned short)
((*(p+6) << 8) | (*(p+7)))),q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create grayscale map.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Convert SGI image to PseudoClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=(*p << 8);
quantum|=(*(p+1));
SetPixelIndex(image,(Quantum) quantum,q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p,q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
iris_info.magic=ReadBlobMSBShort(image);
if (iris_info.magic == 0x01DA)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (iris_info.magic == 0x01DA);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,696 |
libxkbcommon | 842e4351c2c97de6051cab6ce36b4a81e709a0e1 | lex(struct scanner *s, union lvalue *val)
{
skip_more_whitespace_and_comments:
/* Skip spaces. */
while (is_space(peek(s)))
if (next(s) == '\n')
return TOK_END_OF_LINE;
/* Skip comments. */
if (chr(s, '#')) {
skip_to_eol(s);
goto skip_more_whitespace_and_comments;
}
/* See if we're done. */
if (eof(s)) return TOK_END_OF_FILE;
/* New token. */
s->token_line = s->line;
s->token_column = s->column;
s->buf_pos = 0;
/* LHS Keysym. */
if (chr(s, '<')) {
while (peek(s) != '>' && !eol(s) && !eof(s))
buf_append(s, next(s));
if (!chr(s, '>')) {
scanner_err(s, "unterminated keysym literal");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "keysym literal is too long");
return TOK_ERROR;
}
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_LHS_KEYSYM;
}
/* Colon. */
if (chr(s, ':'))
return TOK_COLON;
if (chr(s, '!'))
return TOK_BANG;
if (chr(s, '~'))
return TOK_TILDE;
/* String literal. */
if (chr(s, '\"')) {
while (!eof(s) && !eol(s) && peek(s) != '\"') {
if (chr(s, '\\')) {
uint8_t o;
if (chr(s, '\\')) {
buf_append(s, '\\');
}
else if (chr(s, '"')) {
buf_append(s, '"');
}
else if (chr(s, 'x') || chr(s, 'X')) {
if (hex(s, &o))
buf_append(s, (char) o);
else
scanner_warn(s, "illegal hexadecimal escape sequence in string literal");
}
else if (oct(s, &o)) {
buf_append(s, (char) o);
}
else {
scanner_warn(s, "unknown escape sequence (%c) in string literal", peek(s));
/* Ignore. */
}
} else {
buf_append(s, next(s));
}
}
if (!chr(s, '\"')) {
scanner_err(s, "unterminated string literal");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "string literal is too long");
return TOK_ERROR;
}
if (!is_valid_utf8(s->buf, s->buf_pos - 1)) {
scanner_err(s, "string literal is not a valid UTF-8 string");
return TOK_ERROR;
}
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_STRING;
}
/* Identifier or include. */
if (is_alpha(peek(s)) || peek(s) == '_') {
s->buf_pos = 0;
while (is_alnum(peek(s)) || peek(s) == '_')
buf_append(s, next(s));
if (!buf_append(s, '\0')) {
scanner_err(s, "identifier is too long");
return TOK_ERROR;
}
if (streq(s->buf, "include"))
return TOK_INCLUDE;
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_IDENT;
}
/* Discard rest of line. */
skip_to_eol(s);
scanner_err(s, "unrecognized token");
return TOK_ERROR;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,485 |
ast | c7de8b641266bac7c77942239ac659edfee9ecd2 | Sfdouble_t sh_strnum(Shell_t *shp, const char *str, char **ptr, int mode) {
Sfdouble_t d;
char *last;
if (*str == 0) {
d = 0.0;
last = (char *)str;
} else {
d = number(str, &last, shp->inarith ? 0 : 10, NULL);
if (*last && !shp->inarith && sh_isstate(shp, SH_INIT)) {
// This call is to handle "base#value" literals if we're importing untrusted env vars.
d = number(str, &last, 0, NULL);
}
if (*last) {
if (sh_isstate(shp, SH_INIT)) {
// Initializing means importing untrusted env vars. Since the string does not appear
// to be a recognized numeric literal give up. We can't safely call strval() since
// that allows arbitrary expressions which would create a security vulnerability.
d = 0.0;
} else {
if (*last != '.' || last[1] != '.') {
d = strval(shp, str, &last, arith, mode);
Varsubscript = true;
}
if (!ptr && *last && mode > 0) {
errormsg(SH_DICT, ERROR_exit(1), e_lexbadchar, *last, str);
}
}
} else if (d == 0.0 && *str == '-') {
d = -0.0;
}
}
if (ptr) *ptr = last;
return d;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,086 |
grep | 8fcf61523644df42e1905c81bed26838e0b04f91 | grep (int fd, char const *file, struct stats *stats)
{
int nlines, i;
int not_text;
size_t residue, save;
char oldc;
char *beg;
char *lim;
char eol = eolbyte;
if (!reset (fd, file, stats))
return 0;
if (file && directories == RECURSE_DIRECTORIES
&& S_ISDIR (stats->stat.st_mode))
{
/* Close fd now, so that we don't open a lot of file descriptors
when we recurse deeply. */
if (close (fd) != 0)
suppressible_error (file, errno);
return grepdir (file, stats) - 2;
}
totalcc = 0;
lastout = 0;
totalnl = 0;
outleft = max_count;
after_last_match = 0;
pending = 0;
nlines = 0;
residue = 0;
save = 0;
if (! fillbuf (save, stats))
{
suppressible_error (filename, errno);
return 0;
}
not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet)
|| binary_files == WITHOUT_MATCH_BINARY_FILES)
&& memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg));
if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES)
return 0;
done_on_match += not_text;
out_quiet += not_text;
for (;;)
{
lastnl = bufbeg;
if (lastout)
lastout = bufbeg;
beg = bufbeg + save;
/* no more data to scan (eof) except for maybe a residue -> break */
if (beg == buflim)
break;
/* Determine new residue (the length of an incomplete line at the end of
the buffer, 0 means there is no incomplete last line). */
oldc = beg[-1];
beg[-1] = eol;
for (lim = buflim; lim[-1] != eol; lim--)
continue;
beg[-1] = oldc;
if (lim == beg)
lim = beg - residue;
beg -= residue;
residue = buflim - lim;
if (beg < lim)
{
if (outleft)
nlines += grepbuf (beg, lim);
if (pending)
prpending (lim);
if ((!outleft && !pending) || (nlines && done_on_match && !out_invert))
goto finish_grep;
}
/* The last OUT_BEFORE lines at the end of the buffer will be needed as
leading context if there is a matching line at the begin of the
next data. Make beg point to their begin. */
i = 0;
beg = lim;
while (i < out_before && beg > bufbeg && beg != lastout)
{
++i;
do
--beg;
while (beg[-1] != eol);
}
/* detect if leading context is discontinuous from last printed line. */
if (beg != lastout)
lastout = 0;
/* Handle some details and read more data to scan. */
save = residue + lim - beg;
if (out_byte)
totalcc = add_count (totalcc, buflim - bufbeg - save);
if (out_line)
nlscan (beg);
if (! fillbuf (save, stats))
{
suppressible_error (filename, errno);
goto finish_grep;
}
}
if (residue)
{
*buflim++ = eol;
if (outleft)
nlines += grepbuf (bufbeg + save - residue, buflim);
if (pending)
prpending (buflim);
}
finish_grep:
done_on_match -= not_text;
out_quiet -= not_text;
if ((not_text & ~out_quiet) && nlines != 0)
printf (_("Binary file %s matches\n"), filename);
return nlines;
} | 1 | CVE-2012-5667 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 6,550 |
samba | 1e7a32924b22d1f786b6f490ce8590656f578f91 | static int check_mtab(const char *progname, const char *devname,
const char *dir)
{
if (check_newline(progname, devname) == -1 ||
check_newline(progname, dir) == -1)
return EX_USAGE;
return 0;
}
| 1 | CVE-2011-2724 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 3,215 |
ImageMagick | f595a1985233c399a05c0c37cc41de16a90dd025 | static MagickBooleanType RenderType(Image *image,const DrawInfo *draw_info,
const PointInfo *offset,TypeMetric *metrics,ExceptionInfo *exception)
{
const TypeInfo
*type_info;
DrawInfo
*annotate_info;
MagickBooleanType
status;
type_info=(const TypeInfo *) NULL;
if (draw_info->font != (char *) NULL)
{
if (*draw_info->font == '@')
{
status=RenderFreetype(image,draw_info,draw_info->encoding,offset,
metrics,exception);
return(status);
}
if (*draw_info->font == '-')
return(RenderX11(image,draw_info,offset,metrics,exception));
if (*draw_info->font == '^')
return(RenderPostscript(image,draw_info,offset,metrics,exception));
if (IsPathAccessible(draw_info->font) != MagickFalse)
{
status=RenderFreetype(image,draw_info,draw_info->encoding,offset,
metrics,exception);
return(status);
}
type_info=GetTypeInfo(draw_info->font,exception);
if (type_info == (const TypeInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"UnableToReadFont","`%s'",draw_info->font);
}
if ((type_info == (const TypeInfo *) NULL) &&
(draw_info->family != (const char *) NULL))
{
type_info=GetTypeInfoByFamily(draw_info->family,draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
{
char
**family;
int
number_families;
register ssize_t
i;
/*
Parse font family list.
*/
family=StringToArgv(draw_info->family,&number_families);
for (i=1; i < (ssize_t) number_families; i++)
{
type_info=GetTypeInfoByFamily(family[i],draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info != (const TypeInfo *) NULL)
break;
}
for (i=0; i < (ssize_t) number_families; i++)
family[i]=DestroyString(family[i]);
family=(char **) RelinquishMagickMemory(family);
if (type_info == (const TypeInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"UnableToReadFont","`%s'",draw_info->family);
}
}
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Arial",draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Helvetica",draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Century Schoolbook",draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily("Sans",draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfoByFamily((const char *) NULL,draw_info->style,
draw_info->stretch,draw_info->weight,exception);
if (type_info == (const TypeInfo *) NULL)
type_info=GetTypeInfo("*",exception);
if (type_info == (const TypeInfo *) NULL)
{
status=RenderFreetype(image,draw_info,draw_info->encoding,offset,metrics,
exception);
return(status);
}
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
annotate_info->face=type_info->face;
if (type_info->metrics != (char *) NULL)
(void) CloneString(&annotate_info->metrics,type_info->metrics);
if (type_info->glyphs != (char *) NULL)
(void) CloneString(&annotate_info->font,type_info->glyphs);
status=RenderFreetype(image,annotate_info,type_info->encoding,offset,metrics,
exception);
annotate_info=DestroyDrawInfo(annotate_info);
return(status);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,247 |
FFmpeg | 8001e9f7d17e90b4b0898ba64e3b8bbd716c513c | static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n)
{
uint8_t Stlm, ST, SP, tile_tlm, i;
bytestream2_get_byte(&s->g); /* Ztlm: skipped */
Stlm = bytestream2_get_byte(&s->g);
// too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
ST = (Stlm >> 4) & 0x03;
// TODO: Manage case of ST = 0b11 --> raise error
SP = (Stlm >> 6) & 0x01;
tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);
for (i = 0; i < tile_tlm; i++) {
switch (ST) {
case 0:
break;
case 1:
bytestream2_get_byte(&s->g);
break;
case 2:
bytestream2_get_be16(&s->g);
break;
case 3:
bytestream2_get_be32(&s->g);
break;
}
if (SP == 0) {
bytestream2_get_be16(&s->g);
} else {
bytestream2_get_be32(&s->g);
}
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,293 |
linux-2.6 | 16175a796d061833aacfbd9672235f2d2725df65 | static void update_tpr_threshold(struct kvm_vcpu *vcpu)
{
int max_irr, tpr;
if (!vm_need_tpr_shadow(vcpu->kvm))
return;
if (!kvm_lapic_enabled(vcpu) ||
((max_irr = kvm_lapic_find_highest_irr(vcpu)) == -1)) {
vmcs_write32(TPR_THRESHOLD, 0);
return;
}
tpr = (kvm_lapic_get_cr8(vcpu) & 0x0f) << 4;
vmcs_write32(TPR_THRESHOLD, (max_irr > tpr) ? tpr >> 4 : max_irr >> 4);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,804 |
linux | 401e7e88d4ef80188ffa07095ac00456f901b8c4 | int ipmi_si_port_setup(struct si_sm_io *io)
{
unsigned int addr = io->addr_data;
int idx;
if (!addr)
return -ENODEV;
io->io_cleanup = port_cleanup;
/*
* Figure out the actual inb/inw/inl/etc routine to use based
* upon the register size.
*/
switch (io->regsize) {
case 1:
io->inputb = port_inb;
io->outputb = port_outb;
break;
case 2:
io->inputb = port_inw;
io->outputb = port_outw;
break;
case 4:
io->inputb = port_inl;
io->outputb = port_outl;
break;
default:
dev_warn(io->dev, "Invalid register size: %d\n",
io->regsize);
return -EINVAL;
}
/*
* Some BIOSes reserve disjoint I/O regions in their ACPI
* tables. This causes problems when trying to register the
* entire I/O region. Therefore we must register each I/O
* port separately.
*/
for (idx = 0; idx < io->io_size; idx++) {
if (request_region(addr + idx * io->regspacing,
io->regsize, DEVICE_NAME) == NULL) {
/* Undo allocations */
while (idx--)
release_region(addr + idx * io->regspacing,
io->regsize);
return -EIO;
}
}
return 0;
}
| 1 | CVE-2019-11811 | 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,475 |
tcpdump | 29e5470e6ab84badbc31f4532bb7554a796d9d52 | rfc1048_print(netdissect_options *ndo,
register const u_char *bp)
{
register uint16_t tag;
register u_int len;
register const char *cp;
register char c;
int first, idx;
uint32_t ul;
uint16_t us;
uint8_t uc, subopt, suboptlen;
ND_PRINT((ndo, "\n\t Vendor-rfc1048 Extensions"));
/* Step over magic cookie */
ND_PRINT((ndo, "\n\t Magic Cookie 0x%08x", EXTRACT_32BITS(bp)));
bp += sizeof(int32_t);
/* Loop while we there is a tag left in the buffer */
while (ND_TTEST2(*bp, 1)) {
tag = *bp++;
if (tag == TAG_PAD && ndo->ndo_vflag < 3)
continue;
if (tag == TAG_END && ndo->ndo_vflag < 3)
return;
if (tag == TAG_EXTENDED_OPTION) {
ND_TCHECK2(*(bp + 1), 2);
tag = EXTRACT_16BITS(bp + 1);
/* XXX we don't know yet if the IANA will
* preclude overlap of 1-byte and 2-byte spaces.
* If not, we need to offset tag after this step.
*/
cp = tok2str(xtag2str, "?xT%u", tag);
} else
cp = tok2str(tag2str, "?T%u", tag);
c = *cp++;
if (tag == TAG_PAD || tag == TAG_END)
len = 0;
else {
/* Get the length; check for truncation */
ND_TCHECK2(*bp, 1);
len = *bp++;
}
ND_PRINT((ndo, "\n\t %s Option %u, length %u%s", cp, tag, len,
len > 0 ? ": " : ""));
if (tag == TAG_PAD && ndo->ndo_vflag > 2) {
u_int ntag = 1;
while (ND_TTEST2(*bp, 1) && *bp == TAG_PAD) {
bp++;
ntag++;
}
if (ntag > 1)
ND_PRINT((ndo, ", occurs %u", ntag));
}
if (!ND_TTEST2(*bp, len)) {
ND_PRINT((ndo, "[|rfc1048 %u]", len));
return;
}
if (tag == TAG_DHCP_MESSAGE && len == 1) {
uc = *bp++;
ND_PRINT((ndo, "%s", tok2str(dhcp_msg_values, "Unknown (%u)", uc)));
continue;
}
if (tag == TAG_PARM_REQUEST) {
idx = 0;
while (len-- > 0) {
uc = *bp++;
cp = tok2str(tag2str, "?Option %u", uc);
if (idx % 4 == 0)
ND_PRINT((ndo, "\n\t "));
else
ND_PRINT((ndo, ", "));
ND_PRINT((ndo, "%s", cp + 1));
idx++;
}
continue;
}
if (tag == TAG_EXTENDED_REQUEST) {
first = 1;
while (len > 1) {
len -= 2;
us = EXTRACT_16BITS(bp);
bp += 2;
cp = tok2str(xtag2str, "?xT%u", us);
if (!first)
ND_PRINT((ndo, "+"));
ND_PRINT((ndo, "%s", cp + 1));
first = 0;
}
continue;
}
/* Print data */
if (c == '?') {
/* Base default formats for unknown tags on data size */
if (len & 1)
c = 'b';
else if (len & 2)
c = 's';
else
c = 'l';
}
first = 1;
switch (c) {
case 'a':
/* ASCII strings */
ND_PRINT((ndo, "\""));
if (fn_printn(ndo, bp, len, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
bp += len;
len = 0;
break;
case 'i':
case 'l':
case 'L':
/* ip addresses/32-bit words */
while (len >= sizeof(ul)) {
if (!first)
ND_PRINT((ndo, ","));
ul = EXTRACT_32BITS(bp);
if (c == 'i') {
ul = htonl(ul);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, &ul)));
} else if (c == 'L')
ND_PRINT((ndo, "%d", ul));
else
ND_PRINT((ndo, "%u", ul));
bp += sizeof(ul);
len -= sizeof(ul);
first = 0;
}
break;
case 'p':
/* IP address pairs */
while (len >= 2*sizeof(ul)) {
if (!first)
ND_PRINT((ndo, ","));
memcpy((char *)&ul, (const char *)bp, sizeof(ul));
ND_PRINT((ndo, "(%s:", ipaddr_string(ndo, &ul)));
bp += sizeof(ul);
memcpy((char *)&ul, (const char *)bp, sizeof(ul));
ND_PRINT((ndo, "%s)", ipaddr_string(ndo, &ul)));
bp += sizeof(ul);
len -= 2*sizeof(ul);
first = 0;
}
break;
case 's':
/* shorts */
while (len >= sizeof(us)) {
if (!first)
ND_PRINT((ndo, ","));
us = EXTRACT_16BITS(bp);
ND_PRINT((ndo, "%u", us));
bp += sizeof(us);
len -= sizeof(us);
first = 0;
}
break;
case 'B':
/* boolean */
while (len > 0) {
if (!first)
ND_PRINT((ndo, ","));
switch (*bp) {
case 0:
ND_PRINT((ndo, "N"));
break;
case 1:
ND_PRINT((ndo, "Y"));
break;
default:
ND_PRINT((ndo, "%u?", *bp));
break;
}
++bp;
--len;
first = 0;
}
break;
case 'b':
case 'x':
default:
/* Bytes */
while (len > 0) {
if (!first)
ND_PRINT((ndo, c == 'x' ? ":" : "."));
if (c == 'x')
ND_PRINT((ndo, "%02x", *bp));
else
ND_PRINT((ndo, "%u", *bp));
++bp;
--len;
first = 0;
}
break;
case '$':
/* Guys we can't handle with one of the usual cases */
switch (tag) {
case TAG_NETBIOS_NODE:
/* this option should be at least 1 byte long */
if (len < 1) {
ND_PRINT((ndo, "ERROR: length < 1 bytes"));
break;
}
tag = *bp++;
--len;
ND_PRINT((ndo, "%s", tok2str(nbo2str, NULL, tag)));
break;
case TAG_OPT_OVERLOAD:
/* this option should be at least 1 byte long */
if (len < 1) {
ND_PRINT((ndo, "ERROR: length < 1 bytes"));
break;
}
tag = *bp++;
--len;
ND_PRINT((ndo, "%s", tok2str(oo2str, NULL, tag)));
break;
case TAG_CLIENT_FQDN:
/* this option should be at least 3 bytes long */
if (len < 3) {
ND_PRINT((ndo, "ERROR: length < 3 bytes"));
bp += len;
len = 0;
break;
}
if (*bp)
ND_PRINT((ndo, "[%s] ", client_fqdn_flags(*bp)));
bp++;
if (*bp || *(bp+1))
ND_PRINT((ndo, "%u/%u ", *bp, *(bp+1)));
bp += 2;
ND_PRINT((ndo, "\""));
if (fn_printn(ndo, bp, len - 3, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
bp += len - 3;
len = 0;
break;
case TAG_CLIENT_ID:
{
int type;
/* this option should be at least 1 byte long */
if (len < 1) {
ND_PRINT((ndo, "ERROR: length < 1 bytes"));
break;
}
type = *bp++;
len--;
if (type == 0) {
ND_PRINT((ndo, "\""));
if (fn_printn(ndo, bp, len, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
bp += len;
len = 0;
break;
} else {
ND_PRINT((ndo, "%s ", tok2str(arp2str, "hardware-type %u,", type)));
while (len > 0) {
if (!first)
ND_PRINT((ndo, ":"));
ND_PRINT((ndo, "%02x", *bp));
++bp;
--len;
first = 0;
}
}
break;
}
case TAG_AGENT_CIRCUIT:
while (len >= 2) {
subopt = *bp++;
suboptlen = *bp++;
len -= 2;
if (suboptlen > len) {
ND_PRINT((ndo, "\n\t %s SubOption %u, length %u: length goes past end of option",
tok2str(agent_suboption_values, "Unknown", subopt),
subopt,
suboptlen));
bp += len;
len = 0;
break;
}
ND_PRINT((ndo, "\n\t %s SubOption %u, length %u: ",
tok2str(agent_suboption_values, "Unknown", subopt),
subopt,
suboptlen));
switch (subopt) {
case AGENT_SUBOPTION_CIRCUIT_ID: /* fall through */
case AGENT_SUBOPTION_REMOTE_ID:
case AGENT_SUBOPTION_SUBSCRIBER_ID:
if (fn_printn(ndo, bp, suboptlen, ndo->ndo_snapend))
goto trunc;
break;
default:
print_unknown_data(ndo, bp, "\n\t\t", suboptlen);
}
len -= suboptlen;
bp += suboptlen;
}
break;
case TAG_CLASSLESS_STATIC_RT:
case TAG_CLASSLESS_STA_RT_MS:
{
u_int mask_width, significant_octets, i;
/* this option should be at least 5 bytes long */
if (len < 5) {
ND_PRINT((ndo, "ERROR: length < 5 bytes"));
bp += len;
len = 0;
break;
}
while (len > 0) {
if (!first)
ND_PRINT((ndo, ","));
mask_width = *bp++;
len--;
/* mask_width <= 32 */
if (mask_width > 32) {
ND_PRINT((ndo, "[ERROR: Mask width (%d) > 32]", mask_width));
bp += len;
len = 0;
break;
}
significant_octets = (mask_width + 7) / 8;
/* significant octets + router(4) */
if (len < significant_octets + 4) {
ND_PRINT((ndo, "[ERROR: Remaining length (%u) < %u bytes]", len, significant_octets + 4));
bp += len;
len = 0;
break;
}
ND_PRINT((ndo, "("));
if (mask_width == 0)
ND_PRINT((ndo, "default"));
else {
for (i = 0; i < significant_octets ; i++) {
if (i > 0)
ND_PRINT((ndo, "."));
ND_PRINT((ndo, "%d", *bp++));
}
for (i = significant_octets ; i < 4 ; i++)
ND_PRINT((ndo, ".0"));
ND_PRINT((ndo, "/%d", mask_width));
}
memcpy((char *)&ul, (const char *)bp, sizeof(ul));
ND_PRINT((ndo, ":%s)", ipaddr_string(ndo, &ul)));
bp += sizeof(ul);
len -= (significant_octets + 4);
first = 0;
}
break;
}
case TAG_USER_CLASS:
{
u_int suboptnumber = 1;
first = 1;
if (len < 2) {
ND_PRINT((ndo, "ERROR: length < 2 bytes"));
bp += len;
len = 0;
break;
}
while (len > 0) {
suboptlen = *bp++;
len--;
ND_PRINT((ndo, "\n\t "));
ND_PRINT((ndo, "instance#%u: ", suboptnumber));
if (suboptlen == 0) {
ND_PRINT((ndo, "ERROR: suboption length must be non-zero"));
bp += len;
len = 0;
break;
}
if (len < suboptlen) {
ND_PRINT((ndo, "ERROR: invalid option"));
bp += len;
len = 0;
break;
}
ND_PRINT((ndo, "\""));
if (fn_printn(ndo, bp, suboptlen, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
ND_PRINT((ndo, ", length %d", suboptlen));
suboptnumber++;
len -= suboptlen;
bp += suboptlen;
}
break;
}
default:
ND_PRINT((ndo, "[unknown special tag %u, size %u]",
tag, len));
bp += len;
len = 0;
break;
}
break;
}
/* Data left over? */
if (len) {
ND_PRINT((ndo, "\n\t trailing data length %u", len));
bp += len;
}
}
return;
trunc:
ND_PRINT((ndo, "|[rfc1048]"));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,573 |
linux | 8f44c9a41386729fea410e688959ddaa9d51be7c | brcmf_cfg80211_connect(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct ieee80211_channel *chan = sme->channel;
struct brcmf_join_params join_params;
size_t join_params_size;
const struct brcmf_tlv *rsn_ie;
const struct brcmf_vs_tlv *wpa_ie;
const void *ie;
u32 ie_len;
struct brcmf_ext_join_params_le *ext_join_params;
u16 chanspec;
s32 err = 0;
u32 ssid_len;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
if (!sme->ssid) {
brcmf_err("Invalid ssid\n");
return -EOPNOTSUPP;
}
if (ifp->vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif) {
/* A normal (non P2P) connection request setup. */
ie = NULL;
ie_len = 0;
/* find the WPA_IE */
wpa_ie = brcmf_find_wpaie((u8 *)sme->ie, sme->ie_len);
if (wpa_ie) {
ie = wpa_ie;
ie_len = wpa_ie->len + TLV_HDR_LEN;
} else {
/* find the RSN_IE */
rsn_ie = brcmf_parse_tlvs((const u8 *)sme->ie,
sme->ie_len,
WLAN_EID_RSN);
if (rsn_ie) {
ie = rsn_ie;
ie_len = rsn_ie->len + TLV_HDR_LEN;
}
}
brcmf_fil_iovar_data_set(ifp, "wpaie", ie, ie_len);
}
err = brcmf_vif_set_mgmt_ie(ifp->vif, BRCMF_VNDR_IE_ASSOCREQ_FLAG,
sme->ie, sme->ie_len);
if (err)
brcmf_err("Set Assoc REQ IE Failed\n");
else
brcmf_dbg(TRACE, "Applied Vndr IEs for Assoc request\n");
set_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
if (chan) {
cfg->channel =
ieee80211_frequency_to_channel(chan->center_freq);
chanspec = channel_to_chanspec(&cfg->d11inf, chan);
brcmf_dbg(CONN, "channel=%d, center_req=%d, chanspec=0x%04x\n",
cfg->channel, chan->center_freq, chanspec);
} else {
cfg->channel = 0;
chanspec = 0;
}
brcmf_dbg(INFO, "ie (%p), ie_len (%zd)\n", sme->ie, sme->ie_len);
err = brcmf_set_wpa_version(ndev, sme);
if (err) {
brcmf_err("wl_set_wpa_version failed (%d)\n", err);
goto done;
}
sme->auth_type = brcmf_war_auth_type(ifp, sme->auth_type);
err = brcmf_set_auth_type(ndev, sme);
if (err) {
brcmf_err("wl_set_auth_type failed (%d)\n", err);
goto done;
}
err = brcmf_set_wsec_mode(ndev, sme);
if (err) {
brcmf_err("wl_set_set_cipher failed (%d)\n", err);
goto done;
}
err = brcmf_set_key_mgmt(ndev, sme);
if (err) {
brcmf_err("wl_set_key_mgmt failed (%d)\n", err);
goto done;
}
err = brcmf_set_sharedkey(ndev, sme);
if (err) {
brcmf_err("brcmf_set_sharedkey failed (%d)\n", err);
goto done;
}
if (sme->crypto.psk) {
if (WARN_ON(profile->use_fwsup != BRCMF_PROFILE_FWSUP_NONE)) {
err = -EINVAL;
goto done;
}
brcmf_dbg(INFO, "using PSK offload\n");
profile->use_fwsup = BRCMF_PROFILE_FWSUP_PSK;
}
if (profile->use_fwsup != BRCMF_PROFILE_FWSUP_NONE) {
/* enable firmware supplicant for this interface */
err = brcmf_fil_iovar_int_set(ifp, "sup_wpa", 1);
if (err < 0) {
brcmf_err("failed to enable fw supplicant\n");
goto done;
}
}
if (profile->use_fwsup == BRCMF_PROFILE_FWSUP_PSK) {
err = brcmf_set_pmk(ifp, sme->crypto.psk,
BRCMF_WSEC_MAX_PSK_LEN);
if (err)
goto done;
}
/* Join with specific BSSID and cached SSID
* If SSID is zero join based on BSSID only
*/
join_params_size = offsetof(struct brcmf_ext_join_params_le, assoc_le) +
offsetof(struct brcmf_assoc_params_le, chanspec_list);
if (cfg->channel)
join_params_size += sizeof(u16);
ext_join_params = kzalloc(join_params_size, GFP_KERNEL);
if (ext_join_params == NULL) {
err = -ENOMEM;
goto done;
}
ssid_len = min_t(u32, sme->ssid_len, IEEE80211_MAX_SSID_LEN);
ext_join_params->ssid_le.SSID_len = cpu_to_le32(ssid_len);
memcpy(&ext_join_params->ssid_le.SSID, sme->ssid, ssid_len);
if (ssid_len < IEEE80211_MAX_SSID_LEN)
brcmf_dbg(CONN, "SSID \"%s\", len (%d)\n",
ext_join_params->ssid_le.SSID, ssid_len);
/* Set up join scan parameters */
ext_join_params->scan_le.scan_type = -1;
ext_join_params->scan_le.home_time = cpu_to_le32(-1);
if (sme->bssid)
memcpy(&ext_join_params->assoc_le.bssid, sme->bssid, ETH_ALEN);
else
eth_broadcast_addr(ext_join_params->assoc_le.bssid);
if (cfg->channel) {
ext_join_params->assoc_le.chanspec_num = cpu_to_le32(1);
ext_join_params->assoc_le.chanspec_list[0] =
cpu_to_le16(chanspec);
/* Increase dwell time to receive probe response or detect
* beacon from target AP at a noisy air only during connect
* command.
*/
ext_join_params->scan_le.active_time =
cpu_to_le32(BRCMF_SCAN_JOIN_ACTIVE_DWELL_TIME_MS);
ext_join_params->scan_le.passive_time =
cpu_to_le32(BRCMF_SCAN_JOIN_PASSIVE_DWELL_TIME_MS);
/* To sync with presence period of VSDB GO send probe request
* more frequently. Probe request will be stopped when it gets
* probe response from target AP/GO.
*/
ext_join_params->scan_le.nprobes =
cpu_to_le32(BRCMF_SCAN_JOIN_ACTIVE_DWELL_TIME_MS /
BRCMF_SCAN_JOIN_PROBE_INTERVAL_MS);
} else {
ext_join_params->scan_le.active_time = cpu_to_le32(-1);
ext_join_params->scan_le.passive_time = cpu_to_le32(-1);
ext_join_params->scan_le.nprobes = cpu_to_le32(-1);
}
brcmf_set_join_pref(ifp, &sme->bss_select);
err = brcmf_fil_bsscfg_data_set(ifp, "join", ext_join_params,
join_params_size);
kfree(ext_join_params);
if (!err)
/* This is it. join command worked, we are done */
goto done;
/* join command failed, fallback to set ssid */
memset(&join_params, 0, sizeof(join_params));
join_params_size = sizeof(join_params.ssid_le);
memcpy(&join_params.ssid_le.SSID, sme->ssid, ssid_len);
join_params.ssid_le.SSID_len = cpu_to_le32(ssid_len);
if (sme->bssid)
memcpy(join_params.params_le.bssid, sme->bssid, ETH_ALEN);
else
eth_broadcast_addr(join_params.params_le.bssid);
if (cfg->channel) {
join_params.params_le.chanspec_list[0] = cpu_to_le16(chanspec);
join_params.params_le.chanspec_num = cpu_to_le32(1);
join_params_size += sizeof(join_params.params_le);
}
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, join_params_size);
if (err)
brcmf_err("BRCMF_C_SET_SSID failed (%d)\n", err);
done:
if (err)
clear_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,296 |
file | ce90e05774dd77d86cfc8dfa6da57b32816841c4 | donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap, size_t align, int *flags)
{
Elf32_Nhdr nh32;
Elf64_Nhdr nh64;
size_t noff, doff;
#ifdef ELFCORE
int os_style = -1;
#endif
uint32_t namesz, descsz;
unsigned char *nbuf = CAST(unsigned char *, vbuf);
char sbuf[512];
if (xnh_sizeof + offset > size) {
/*
* We're out of note headers.
*/
return xnh_sizeof + offset;
}
(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
offset += xnh_sizeof;
namesz = xnh_namesz;
descsz = xnh_descsz;
if ((namesz == 0) && (descsz == 0)) {
/*
* We're out of note headers.
*/
return (offset >= size) ? offset : size;
}
if (namesz & 0x80000000) {
(void)file_printf(ms, ", bad note name size 0x%lx",
(unsigned long)namesz);
return 0;
}
if (descsz & 0x80000000) {
(void)file_printf(ms, ", bad note description size 0x%lx",
(unsigned long)descsz);
return 0;
}
noff = offset;
doff = ELF_ALIGN(offset + namesz);
if (offset + namesz > size) {
/*
* We're past the end of the buffer.
*/
return doff;
}
offset = ELF_ALIGN(doff + descsz);
if (doff + descsz > size) {
/*
* We're past the end of the buffer.
*/
return (offset >= size) ? offset : size;
}
if ((*flags & (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) ==
(FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID))
goto core;
if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 2) {
file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]);
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 16) {
uint32_t desc[4];
(void)memcpy(desc, &nbuf[doff], sizeof(desc));
if (file_printf(ms, ", for GNU/") == -1)
return size;
switch (elf_getu32(swap, desc[0])) {
case GNU_OS_LINUX:
if (file_printf(ms, "Linux") == -1)
return size;
break;
case GNU_OS_HURD:
if (file_printf(ms, "Hurd") == -1)
return size;
break;
case GNU_OS_SOLARIS:
if (file_printf(ms, "Solaris") == -1)
return size;
break;
case GNU_OS_KFREEBSD:
if (file_printf(ms, "kFreeBSD") == -1)
return size;
break;
case GNU_OS_KNETBSD:
if (file_printf(ms, "kNetBSD") == -1)
return size;
break;
default:
if (file_printf(ms, "<unknown>") == -1)
return size;
}
if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]),
elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) {
uint8_t desc[20];
uint32_t i;
if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" :
"sha1") == -1)
return size;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return size;
*flags |= FLAGS_DID_BUILD_ID;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 &&
xnh_type == NT_NETBSD_PAX && descsz == 4) {
static const char *pax[] = {
"+mprotect",
"-mprotect",
"+segvguard",
"-segvguard",
"+ASLR",
"-ASLR",
};
uint32_t desc;
size_t i;
int did = 0;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (desc && file_printf(ms, ", PaX: ") == -1)
return size;
for (i = 0; i < __arraycount(pax); i++) {
if (((1 << i) & desc) == 0)
continue;
if (file_printf(ms, "%s%s", did++ ? "," : "",
pax[i]) == -1)
return size;
}
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
switch (xnh_type) {
case NT_NETBSD_VERSION:
if (descsz == 4) {
do_note_netbsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
break;
case NT_NETBSD_MARCH:
if (file_printf(ms, ", compiled for: %.*s", (int)descsz,
(const char *)&nbuf[doff]) == -1)
return size;
break;
case NT_NETBSD_CMODEL:
if (file_printf(ms, ", compiler model: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return size;
break;
default:
if (file_printf(ms, ", note=%u", xnh_type) == -1)
return size;
break;
}
return size;
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) {
if (xnh_type == NT_FREEBSD_VERSION && descsz == 4) {
do_note_freebsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 &&
xnh_type == NT_OPENBSD_VERSION && descsz == 4) {
if (file_printf(ms, ", for OpenBSD") == -1)
return size;
/* Content of note is always 0 */
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 &&
xnh_type == NT_DRAGONFLY_VERSION && descsz == 4) {
uint32_t desc;
if (file_printf(ms, ", for DragonFly") == -1)
return size;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, " %d.%d.%d", desc / 100000,
desc / 10000 % 10, desc % 10000) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
core:
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
#ifdef ELFCORE
if ((*flags & FLAGS_DID_CORE) != 0)
return size;
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return size;
*flags |= FLAGS_DID_CORE_STYLE;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (xnh_type == NT_NETBSD_CORE_PROCINFO) {
uint32_t signo;
/*
* Extract the program name. It is at
* offset 0x7c, and is up to 32-bytes,
* including the terminating NUL.
*/
if (file_printf(ms, ", from '%.31s'",
file_printable(sbuf, sizeof(sbuf),
(const char *)&nbuf[doff + 0x7c])) == -1)
return size;
/*
* Extract the signal number. It is at
* offset 0x08.
*/
(void)memcpy(&signo, &nbuf[doff + 0x08],
sizeof(signo));
if (file_printf(ms, " (signal %u)",
elf_getu32(swap, signo)) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
}
break;
default:
if (xnh_type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS ; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; *cp && isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
tryanother:
;
}
}
break;
}
#endif
return offset;
}
| 1 | CVE-2014-9620 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 2,879 |
ImageMagick | 3320955045e5a2a22c13a04fa9422bb809e75eda | static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
page_geometry[MaxTextExtent];
Image
*image;
MagickBooleanType
logging;
volatile int
first_mng_object,
object_id,
term_chunk_found,
skip_to_iend;
volatile ssize_t
image_count=0;
MagickBooleanType
status;
MagickOffsetType
offset;
MngBox
default_fb,
fb,
previous_fb;
#if defined(MNG_INSERT_LAYERS)
PixelPacket
mng_background_color;
#endif
register unsigned char
*p;
register ssize_t
i;
size_t
count;
ssize_t
loop_level;
volatile short
skipping_loop;
#if defined(MNG_INSERT_LAYERS)
unsigned int
mandatory_back=0;
#endif
volatile unsigned int
#ifdef MNG_OBJECT_BUFFERS
mng_background_object=0,
#endif
mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */
size_t
default_frame_timeout,
frame_timeout,
#if defined(MNG_INSERT_LAYERS)
image_height,
image_width,
#endif
length;
/* These delays are all measured in image ticks_per_second,
* not in MNG ticks_per_second
*/
volatile size_t
default_frame_delay,
final_delay,
final_image_delay,
frame_delay,
#if defined(MNG_INSERT_LAYERS)
insert_layers,
#endif
mng_iterations=1,
simplicity=0,
subframe_height=0,
subframe_width=0;
previous_fb.top=0;
previous_fb.bottom=0;
previous_fb.left=0;
previous_fb.right=0;
default_fb.top=0;
default_fb.bottom=0;
default_fb.left=0;
default_fb.right=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneMNGImage()");
image=mng_info->image;
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
char
magic_number[MaxTextExtent];
/* Verify MNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Initialize some nonzero members of the MngInfo structure. */
for (i=0; i < MNG_MAX_OBJECTS; i++)
{
mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX;
mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX;
}
mng_info->exists[0]=MagickTrue;
}
skipping_loop=(-1);
first_mng_object=MagickTrue;
mng_type=0;
#if defined(MNG_INSERT_LAYERS)
insert_layers=MagickFalse; /* should be False when converting or mogrifying */
#endif
default_frame_delay=0;
default_frame_timeout=0;
frame_delay=0;
final_delay=1;
mng_info->ticks_per_second=1UL*image->ticks_per_second;
object_id=0;
skip_to_iend=MagickFalse;
term_chunk_found=MagickFalse;
mng_info->framing_mode=1;
#if defined(MNG_INSERT_LAYERS)
mandatory_back=MagickFalse;
#endif
#if defined(MNG_INSERT_LAYERS)
mng_background_color=image->background_color;
#endif
default_fb=mng_info->frame;
previous_fb=mng_info->frame;
do
{
char
type[MaxTextExtent];
if (LocaleCompare(image_info->magick,"MNG") == 0)
{
unsigned char
*chunk;
/*
Read a new chunk.
*/
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(size_t) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading MNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX)
{
status=MagickFalse;
break;
}
if (count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
if (length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
chunk=(unsigned char *) AcquireQuantumMemory(length+
MagickPathExtent,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
#if !defined(JNG_SUPPORTED)
if (memcmp(type,mng_JHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->jhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"JNGCompressNotSupported","`%s'",image->filename);
mng_info->jhdr_warning++;
}
#endif
if (memcmp(type,mng_DHDR,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->dhdr_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DeltaPNGNotSupported","`%s'",image->filename);
mng_info->dhdr_warning++;
}
if (memcmp(type,mng_MEND,4) == 0)
break;
if (skip_to_iend)
{
if (memcmp(type,mng_IEND,4) == 0)
skip_to_iend=MagickFalse;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skip to IEND.");
continue;
}
if (memcmp(type,mng_MHDR,4) == 0)
{
if (length != 28)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"CorruptImage");
}
mng_info->mng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
mng_info->mng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG width: %.20g",(double) mng_info->mng_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" MNG height: %.20g",(double) mng_info->mng_height);
}
p+=8;
mng_info->ticks_per_second=(size_t) mng_get_long(p);
if (mng_info->ticks_per_second == 0)
default_frame_delay=0;
else
default_frame_delay=1UL*image->ticks_per_second/
mng_info->ticks_per_second;
frame_delay=default_frame_delay;
simplicity=0;
/* Skip nominal layer count, frame count, and play time */
p+=16;
simplicity=(size_t) mng_get_long(p);
mng_type=1; /* Full MNG */
if ((simplicity != 0) && ((simplicity | 11) == 11))
mng_type=2; /* LC */
if ((simplicity != 0) && ((simplicity | 9) == 9))
mng_type=3; /* VLC */
#if defined(MNG_INSERT_LAYERS)
if (mng_type != 3)
insert_layers=MagickTrue;
#endif
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
mng_info->image=image;
}
if ((mng_info->mng_width > 65535L) ||
(mng_info->mng_height > 65535L))
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit");
}
(void) FormatLocaleString(page_geometry,MaxTextExtent,
"%.20gx%.20g+0+0",(double) mng_info->mng_width,(double)
mng_info->mng_height);
mng_info->frame.left=0;
mng_info->frame.right=(ssize_t) mng_info->mng_width;
mng_info->frame.top=0;
mng_info->frame.bottom=(ssize_t) mng_info->mng_height;
mng_info->clip=default_fb=previous_fb=mng_info->frame;
for (i=0; i < MNG_MAX_OBJECTS; i++)
mng_info->object_clip[i]=mng_info->frame;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_TERM,4) == 0)
{
int
repeat=0;
if (length != 0)
repeat=p[0];
if (repeat == 3 && length > 8)
{
final_delay=(png_uint_32) mng_get_long(&p[2]);
mng_iterations=(png_uint_32) mng_get_long(&p[6]);
if (mng_iterations == PNG_UINT_31_MAX)
mng_iterations=0;
image->iterations=mng_iterations;
term_chunk_found=MagickTrue;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" repeat=%d, final_delay=%.20g, iterations=%.20g",
repeat,(double) final_delay, (double) image->iterations);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_DEFI,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'",
image->filename);
if (length > 1)
{
object_id=(p[0] << 8) | p[1];
if (mng_type == 2 && object_id != 0)
(void) ThrowMagickException(&image->exception,
GetMagickModule(),
CoderError,"Nonzero object_id in MNG-LC datastream",
"`%s'", image->filename);
if (object_id > MNG_MAX_OBJECTS)
{
/*
Instead of using a warning we should allocate a larger
MngInfo structure and continue.
*/
(void) ThrowMagickException(&image->exception,
GetMagickModule(), CoderError,
"object id too large","`%s'",image->filename);
object_id=MNG_MAX_OBJECTS;
}
if (mng_info->exists[object_id])
if (mng_info->frozen[object_id])
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"DEFI cannot redefine a frozen MNG object","`%s'",
image->filename);
continue;
}
mng_info->exists[object_id]=MagickTrue;
if (length > 2)
mng_info->invisible[object_id]=p[2];
/*
Extract object offset info.
*/
if (length > 11)
{
mng_info->x_off[object_id]=(ssize_t) ((p[4] << 24) |
(p[5] << 16) | (p[6] << 8) | p[7]);
mng_info->y_off[object_id]=(ssize_t) ((p[8] << 24) |
(p[9] << 16) | (p[10] << 8) | p[11]);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_off[%d]: %.20g, y_off[%d]: %.20g",
object_id,(double) mng_info->x_off[object_id],
object_id,(double) mng_info->y_off[object_id]);
}
}
/*
Extract object clipping info.
*/
if (length > 27)
mng_info->object_clip[object_id]=
mng_read_box(mng_info->frame,0, &p[12]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
mng_info->have_global_bkgd=MagickFalse;
if (length > 5)
{
mng_info->mng_global_bkgd.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_info->mng_global_bkgd.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_info->mng_global_bkgd.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_info->have_global_bkgd=MagickTrue;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_BACK,4) == 0)
{
#if defined(MNG_INSERT_LAYERS)
if (length > 6)
mandatory_back=p[6];
else
mandatory_back=0;
if (mandatory_back && length > 5)
{
mng_background_color.red=
ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1]));
mng_background_color.green=
ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3]));
mng_background_color.blue=
ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5]));
mng_background_color.opacity=OpaqueOpacity;
}
#ifdef MNG_OBJECT_BUFFERS
if (length > 8)
mng_background_object=(p[7] << 8) | p[8];
#endif
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_PLTE,4) == 0)
{
/* Read global PLTE. */
if (length && (length < 769))
{
if (mng_info->global_plte == (png_colorp) NULL)
mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256,
sizeof(*mng_info->global_plte));
for (i=0; i < (ssize_t) (length/3); i++)
{
mng_info->global_plte[i].red=p[3*i];
mng_info->global_plte[i].green=p[3*i+1];
mng_info->global_plte[i].blue=p[3*i+2];
}
mng_info->global_plte_length=(unsigned int) (length/3);
}
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
{
mng_info->global_plte[i].red=i;
mng_info->global_plte[i].green=i;
mng_info->global_plte[i].blue=i;
}
if (length != 0)
mng_info->global_plte_length=256;
#endif
else
mng_info->global_plte_length=0;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_tRNS,4) == 0)
{
/* read global tRNS */
if (length > 0 && length < 257)
for (i=0; i < (ssize_t) length; i++)
mng_info->global_trns[i]=p[i];
#ifdef MNG_LOOSE
for ( ; i < 256; i++)
mng_info->global_trns[i]=255;
#endif
mng_info->global_trns_length=(unsigned int) length;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
{
ssize_t
igamma;
igamma=mng_get_long(p);
mng_info->global_gamma=((float) igamma)*0.00001;
mng_info->have_global_gama=MagickTrue;
}
else
mng_info->have_global_gama=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
/* Read global cHRM */
if (length == 32)
{
mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p);
mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]);
mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]);
mng_info->global_chrm.red_primary.y=0.00001*
mng_get_long(&p[12]);
mng_info->global_chrm.green_primary.x=0.00001*
mng_get_long(&p[16]);
mng_info->global_chrm.green_primary.y=0.00001*
mng_get_long(&p[20]);
mng_info->global_chrm.blue_primary.x=0.00001*
mng_get_long(&p[24]);
mng_info->global_chrm.blue_primary.y=0.00001*
mng_get_long(&p[28]);
mng_info->have_global_chrm=MagickTrue;
}
else
mng_info->have_global_chrm=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
/*
Read global sRGB.
*/
if (length != 0)
{
mng_info->global_srgb_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
mng_info->have_global_srgb=MagickTrue;
}
else
mng_info->have_global_srgb=MagickFalse;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
/*
Read global iCCP.
*/
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_FRAM,4) == 0)
{
if (mng_type == 3)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'",
image->filename);
if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4))
image->delay=frame_delay;
frame_delay=default_frame_delay;
frame_timeout=default_frame_timeout;
fb=default_fb;
if (length > 0)
if (p[0])
mng_info->framing_mode=p[0];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_mode=%d",mng_info->framing_mode);
if (length > 6)
{
/* Note the delay and frame clipping boundaries. */
p++; /* framing mode */
while (*p && ((p-chunk) < (ssize_t) length))
p++; /* frame name */
p++; /* frame name terminator */
if ((p-chunk) < (ssize_t) (length-4))
{
int
change_delay,
change_timeout,
change_clipping;
change_delay=(*p++);
change_timeout=(*p++);
change_clipping=(*p++);
p++; /* change_sync */
if (change_delay && (p-chunk) < (ssize_t) (length-4))
{
frame_delay=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_delay/=mng_info->ticks_per_second;
else
frame_delay=PNG_UINT_31_MAX;
if (change_delay == 2)
default_frame_delay=frame_delay;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_delay=%.20g",(double) frame_delay);
}
if (change_timeout && (p-chunk) < (ssize_t) (length-4))
{
frame_timeout=1UL*image->ticks_per_second*
mng_get_long(p);
if (mng_info->ticks_per_second != 0)
frame_timeout/=mng_info->ticks_per_second;
else
frame_timeout=PNG_UINT_31_MAX;
if (change_timeout == 2)
default_frame_timeout=frame_timeout;
p+=4;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Framing_timeout=%.20g",(double) frame_timeout);
}
if (change_clipping && (p-chunk) < (ssize_t) (length-17))
{
fb=mng_read_box(previous_fb,(char) p[0],&p[1]);
p+=17;
previous_fb=fb;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g",
(double) fb.left,(double) fb.right,(double) fb.top,
(double) fb.bottom);
if (change_clipping == 2)
default_fb=fb;
}
}
}
mng_info->clip=fb;
mng_info->clip=mng_minimum_box(fb,mng_info->frame);
subframe_width=(size_t) (mng_info->clip.right
-mng_info->clip.left);
subframe_height=(size_t) (mng_info->clip.bottom
-mng_info->clip.top);
/*
Insert a background layer behind the frame if framing_mode is 4.
*/
#if defined(MNG_INSERT_LAYERS)
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" subframe_width=%.20g, subframe_height=%.20g",(double)
subframe_width,(double) subframe_height);
if (insert_layers && (mng_info->framing_mode == 4) &&
(subframe_width) && (subframe_height))
{
/* Allocate next image structure. */
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
image->delay=0;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLIP,4) == 0)
{
unsigned int
first_object,
last_object;
/*
Read CLIP.
*/
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(int) first_object; i <= (int) last_object; i++)
{
if (mng_info->exists[i] && !mng_info->frozen[i])
{
MngBox
box;
box=mng_info->object_clip[i];
if ((p-chunk) < (ssize_t) (length-17))
mng_info->object_clip[i]=
mng_read_box(box,(char) p[0],&p[1]);
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_SAVE,4) == 0)
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
if (mng_info->exists[i])
{
mng_info->frozen[i]=MagickTrue;
#ifdef MNG_OBJECT_BUFFERS
if (mng_info->ob[i] != (MngBuffer *) NULL)
mng_info->ob[i]->frozen=MagickTrue;
#endif
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0))
{
/* Read DISC or SEEK. */
if ((length == 0) || !memcmp(type,mng_SEEK,4))
{
for (i=1; i < MNG_MAX_OBJECTS; i++)
MngInfoDiscardObject(mng_info,i);
}
else
{
register ssize_t
j;
for (j=1; j < (ssize_t) length; j+=2)
{
i=p[j-1] << 8 | p[j];
MngInfoDiscardObject(mng_info,i);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_MOVE,4) == 0)
{
size_t
first_object,
last_object;
/* read MOVE */
if (length > 3)
{
first_object=(p[0] << 8) | p[1];
last_object=(p[2] << 8) | p[3];
p+=4;
for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++)
{
if ((i < 0) || (i >= MNG_MAX_OBJECTS))
continue;
if (mng_info->exists[i] && !mng_info->frozen[i] &&
(p-chunk) < (ssize_t) (length-8))
{
MngPair
new_pair;
MngPair
old_pair;
old_pair.a=mng_info->x_off[i];
old_pair.b=mng_info->y_off[i];
new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]);
mng_info->x_off[i]=new_pair.a;
mng_info->y_off[i]=new_pair.b;
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_LOOP,4) == 0)
{
ssize_t loop_iters=1;
if (length > 4)
{
loop_level=chunk[0];
mng_info->loop_active[loop_level]=1; /* mark loop active */
/* Record starting point. */
loop_iters=mng_get_long(&chunk[1]);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" LOOP level %.20g has %.20g iterations ",
(double) loop_level, (double) loop_iters);
if (loop_iters == 0)
skipping_loop=loop_level;
else
{
mng_info->loop_jump[loop_level]=TellBlob(image);
mng_info->loop_count[loop_level]=loop_iters;
}
mng_info->loop_iteration[loop_level]=0;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_ENDL,4) == 0)
{
if (length > 0)
{
loop_level=chunk[0];
if (skipping_loop > 0)
{
if (skipping_loop == loop_level)
{
/*
Found end of zero-iteration loop.
*/
skipping_loop=(-1);
mng_info->loop_active[loop_level]=0;
}
}
else
{
if (mng_info->loop_active[loop_level] == 1)
{
mng_info->loop_count[loop_level]--;
mng_info->loop_iteration[loop_level]++;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ENDL: LOOP level %.20g has %.20g remaining iters ",
(double) loop_level,(double)
mng_info->loop_count[loop_level]);
if (mng_info->loop_count[loop_level] != 0)
{
offset=SeekBlob(image,
mng_info->loop_jump[loop_level], SEEK_SET);
if (offset < 0)
{
chunk=(unsigned char *) RelinquishMagickMemory(
chunk);
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
}
else
{
short
last_level;
/*
Finished loop.
*/
mng_info->loop_active[loop_level]=0;
last_level=(-1);
for (i=0; i < loop_level; i++)
if (mng_info->loop_active[i] == 1)
last_level=(short) i;
loop_level=last_level;
}
}
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_CLON,4) == 0)
{
if (mng_info->clon_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CLON is not implemented yet","`%s'",
image->filename);
mng_info->clon_warning++;
}
if (memcmp(type,mng_MAGN,4) == 0)
{
png_uint_16
magn_first,
magn_last,
magn_mb,
magn_ml,
magn_mr,
magn_mt,
magn_mx,
magn_my,
magn_methx,
magn_methy;
if (length > 1)
magn_first=(p[0] << 8) | p[1];
else
magn_first=0;
if (length > 3)
magn_last=(p[2] << 8) | p[3];
else
magn_last=magn_first;
#ifndef MNG_OBJECT_BUFFERS
if (magn_first || magn_last)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"MAGN is not implemented yet for nonzero objects",
"`%s'",image->filename);
mng_info->magn_warning++;
}
#endif
if (length > 4)
magn_methx=p[4];
else
magn_methx=0;
if (length > 6)
magn_mx=(p[5] << 8) | p[6];
else
magn_mx=1;
if (magn_mx == 0)
magn_mx=1;
if (length > 8)
magn_my=(p[7] << 8) | p[8];
else
magn_my=magn_mx;
if (magn_my == 0)
magn_my=1;
if (length > 10)
magn_ml=(p[9] << 8) | p[10];
else
magn_ml=magn_mx;
if (magn_ml == 0)
magn_ml=1;
if (length > 12)
magn_mr=(p[11] << 8) | p[12];
else
magn_mr=magn_mx;
if (magn_mr == 0)
magn_mr=1;
if (length > 14)
magn_mt=(p[13] << 8) | p[14];
else
magn_mt=magn_my;
if (magn_mt == 0)
magn_mt=1;
if (length > 16)
magn_mb=(p[15] << 8) | p[16];
else
magn_mb=magn_my;
if (magn_mb == 0)
magn_mb=1;
if (length > 17)
magn_methy=p[17];
else
magn_methy=magn_methx;
if (magn_methx > 5 || magn_methy > 5)
if (mng_info->magn_warning == 0)
{
(void) ThrowMagickException(&image->exception,
GetMagickModule(),CoderError,
"Unknown MAGN method in MNG datastream","`%s'",
image->filename);
mng_info->magn_warning++;
}
#ifdef MNG_OBJECT_BUFFERS
/* Magnify existing objects in the range magn_first to magn_last */
#endif
if (magn_first == 0 || magn_last == 0)
{
/* Save the magnification factors for object 0 */
mng_info->magn_mb=magn_mb;
mng_info->magn_ml=magn_ml;
mng_info->magn_mr=magn_mr;
mng_info->magn_mt=magn_mt;
mng_info->magn_mx=magn_mx;
mng_info->magn_my=magn_my;
mng_info->magn_methx=magn_methx;
mng_info->magn_methy=magn_methy;
}
}
if (memcmp(type,mng_PAST,4) == 0)
{
if (mng_info->past_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"PAST is not implemented yet","`%s'",
image->filename);
mng_info->past_warning++;
}
if (memcmp(type,mng_SHOW,4) == 0)
{
if (mng_info->show_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"SHOW is not implemented yet","`%s'",
image->filename);
mng_info->show_warning++;
}
if (memcmp(type,mng_sBIT,4) == 0)
{
if (length < 4)
mng_info->have_global_sbit=MagickFalse;
else
{
mng_info->global_sbit.gray=p[0];
mng_info->global_sbit.red=p[0];
mng_info->global_sbit.green=p[1];
mng_info->global_sbit.blue=p[2];
mng_info->global_sbit.alpha=p[3];
mng_info->have_global_sbit=MagickTrue;
}
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
mng_info->global_x_pixels_per_unit=
(size_t) mng_get_long(p);
mng_info->global_y_pixels_per_unit=
(size_t) mng_get_long(&p[4]);
mng_info->global_phys_unit_type=p[8];
mng_info->have_global_phys=MagickTrue;
}
else
mng_info->have_global_phys=MagickFalse;
}
if (memcmp(type,mng_pHYg,4) == 0)
{
if (mng_info->phyg_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"pHYg is not implemented.","`%s'",image->filename);
mng_info->phyg_warning++;
}
if (memcmp(type,mng_BASI,4) == 0)
{
skip_to_iend=MagickTrue;
if (mng_info->basi_warning == 0)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"BASI is not implemented yet","`%s'",
image->filename);
mng_info->basi_warning++;
#ifdef MNG_BASI_SUPPORTED
if (length > 11)
{
basi_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
basi_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
basi_color_type=p[8];
basi_compression_method=p[9];
basi_filter_type=p[10];
basi_interlace_method=p[11];
}
if (length > 13)
basi_red=(p[12] << 8) & p[13];
else
basi_red=0;
if (length > 15)
basi_green=(p[14] << 8) & p[15];
else
basi_green=0;
if (length > 17)
basi_blue=(p[16] << 8) & p[17];
else
basi_blue=0;
if (length > 19)
basi_alpha=(p[18] << 8) & p[19];
else
{
if (basi_sample_depth == 16)
basi_alpha=65535L;
else
basi_alpha=255;
}
if (length > 20)
basi_viewable=p[20];
else
basi_viewable=0;
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_IHDR,4)
#if defined(JNG_SUPPORTED)
&& memcmp(type,mng_JHDR,4)
#endif
)
{
/* Not an IHDR or JHDR chunk */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
/* Process IHDR */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]);
mng_info->exists[object_id]=MagickTrue;
mng_info->viewable[object_id]=MagickTrue;
if (mng_info->invisible[object_id])
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Skipping invisible object");
skip_to_iend=MagickTrue;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if defined(MNG_INSERT_LAYERS)
if (length < 8)
{
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image_width=(size_t) mng_get_long(p);
image_height=(size_t) mng_get_long(&p[4]);
#endif
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
/*
Insert a transparent background layer behind the entire animation
if it is not full screen.
*/
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && mng_type && first_mng_object)
{
if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) ||
(image_width < mng_info->mng_width) ||
(mng_info->clip.right < (ssize_t) mng_info->mng_width) ||
(image_height < mng_info->mng_height) ||
(mng_info->clip.bottom < (ssize_t) mng_info->mng_height))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
/* Make a background rectangle. */
image->delay=0;
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Inserted transparent background layer, W=%.20g, H=%.20g",
(double) mng_info->mng_width,(double) mng_info->mng_height);
}
}
/*
Insert a background layer behind the upcoming image if
framing_mode is 3, and we haven't already inserted one.
*/
if (insert_layers && (mng_info->framing_mode == 3) &&
(subframe_width) && (subframe_height) && (simplicity == 0 ||
(simplicity & 0x08)))
{
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
image->iterations=mng_iterations;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
image->delay=0;
image->columns=subframe_width;
image->rows=subframe_height;
image->page.width=subframe_width;
image->page.height=subframe_height;
image->page.x=mng_info->clip.left;
image->page.y=mng_info->clip.top;
image->background_color=mng_background_color;
image->matte=MagickFalse;
(void) SetImageBackgroundColor(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g",
(double) mng_info->clip.left,(double) mng_info->clip.right,
(double) mng_info->clip.top,(double) mng_info->clip.bottom);
}
#endif /* MNG_INSERT_LAYERS */
first_mng_object=MagickFalse;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
if (term_chunk_found)
{
image->start_loop=MagickTrue;
term_chunk_found=MagickFalse;
}
else
image->start_loop=MagickFalse;
if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3)
{
image->delay=frame_delay;
frame_delay=default_frame_delay;
}
else
image->delay=0;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=mng_info->x_off[object_id];
image->page.y=mng_info->y_off[object_id];
image->iterations=mng_iterations;
/*
Seek back to the beginning of the IHDR or JHDR chunk's length field.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Seeking back to beginning of %c%c%c%c chunk",type[0],type[1],
type[2],type[3]);
offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
mng_info->image=image;
mng_info->mng_type=mng_type;
mng_info->object_id=object_id;
if (memcmp(type,mng_IHDR,4) == 0)
image=ReadOnePNGImage(mng_info,image_info,exception);
#if defined(JNG_SUPPORTED)
else
image=ReadOneJNGImage(mng_info,image_info,exception);
#endif
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
if (image->columns == 0 || image->rows == 0)
{
(void) CloseBlob(image);
return(DestroyImageList(image));
}
mng_info->image=image;
if (mng_type)
{
MngBox
crop_box;
if (mng_info->magn_methx || mng_info->magn_methy)
{
png_uint_32
magnified_height,
magnified_width;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Processing MNG MAGN chunk");
if (mng_info->magn_methx == 1)
{
magnified_width=mng_info->magn_ml;
if (image->columns > 1)
magnified_width += mng_info->magn_mr;
if (image->columns > 2)
magnified_width += (png_uint_32)
((image->columns-2)*(mng_info->magn_mx));
}
else
{
magnified_width=(png_uint_32) image->columns;
if (image->columns > 1)
magnified_width += mng_info->magn_ml-1;
if (image->columns > 2)
magnified_width += mng_info->magn_mr-1;
if (image->columns > 3)
magnified_width += (png_uint_32)
((image->columns-3)*(mng_info->magn_mx-1));
}
if (mng_info->magn_methy == 1)
{
magnified_height=mng_info->magn_mt;
if (image->rows > 1)
magnified_height += mng_info->magn_mb;
if (image->rows > 2)
magnified_height += (png_uint_32)
((image->rows-2)*(mng_info->magn_my));
}
else
{
magnified_height=(png_uint_32) image->rows;
if (image->rows > 1)
magnified_height += mng_info->magn_mt-1;
if (image->rows > 2)
magnified_height += mng_info->magn_mb-1;
if (image->rows > 3)
magnified_height += (png_uint_32)
((image->rows-3)*(mng_info->magn_my-1));
}
if (magnified_height > image->rows ||
magnified_width > image->columns)
{
Image
*large_image;
int
yy;
ssize_t
m,
y;
register ssize_t
x;
register PixelPacket
*n,
*q;
PixelPacket
*next,
*prev;
png_uint_16
magn_methx,
magn_methy;
/* Allocate next image structure. */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocate magnified image");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
large_image=SyncNextImageInList(image);
large_image->columns=magnified_width;
large_image->rows=magnified_height;
magn_methx=mng_info->magn_methx;
magn_methy=mng_info->magn_methy;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
#define QM unsigned short
if (magn_methx != 1 || magn_methy != 1)
{
/*
Scale pixels to unsigned shorts to prevent
overflow of intermediate values of interpolations
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,
exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleQuantumToShort(
GetPixelRed(q)));
SetPixelGreen(q,ScaleQuantumToShort(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleQuantumToShort(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleQuantumToShort(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#else
#define QM Quantum
#endif
if (image->matte != MagickFalse)
(void) SetImageBackgroundColor(large_image);
else
{
large_image->background_color.opacity=OpaqueOpacity;
(void) SetImageBackgroundColor(large_image);
if (magn_methx == 4)
magn_methx=2;
if (magn_methx == 5)
magn_methx=3;
if (magn_methy == 4)
magn_methy=2;
if (magn_methy == 5)
magn_methy=3;
}
/* magnify the rows into the right side of the large image */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the rows to %.20g",(double) large_image->rows);
m=(ssize_t) mng_info->magn_mt;
yy=0;
length=(size_t) image->columns;
next=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*next));
prev=(PixelPacket *) AcquireQuantumMemory(length,sizeof(*prev));
if ((prev == (PixelPacket *) NULL) ||
(next == (PixelPacket *) NULL))
{
image=DestroyImageList(image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
n=GetAuthenticPixels(image,0,0,image->columns,1,exception);
(void) CopyMagickMemory(next,n,length);
for (y=0; y < (ssize_t) image->rows; y++)
{
if (y == 0)
m=(ssize_t) mng_info->magn_mt;
else if (magn_methy > 1 && y == (ssize_t) image->rows-2)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy <= 1 && y == (ssize_t) image->rows-1)
m=(ssize_t) mng_info->magn_mb;
else if (magn_methy > 1 && y == (ssize_t) image->rows-1)
m=1;
else
m=(ssize_t) mng_info->magn_my;
n=prev;
prev=next;
next=n;
if (y < (ssize_t) image->rows-1)
{
n=GetAuthenticPixels(image,0,y+1,image->columns,1,
exception);
(void) CopyMagickMemory(next,n,length);
}
for (i=0; i < m; i++, yy++)
{
register PixelPacket
*pixels;
assert(yy < (ssize_t) large_image->rows);
pixels=prev;
n=next;
q=GetAuthenticPixels(large_image,0,yy,large_image->columns,
1,exception);
q+=(large_image->columns-image->columns);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
/* To do: get color as function of indexes[x] */
/*
if (image->storage_class == PseudoClass)
{
}
*/
if (magn_methy <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methy == 2 || magn_methy == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
else
{
/* Interpolate */
SetPixelRed(q,
((QM) (((ssize_t)
(2*i*(GetPixelRed(n)
-GetPixelRed(pixels)+m))/
((ssize_t) (m*2))
+GetPixelRed(pixels)))));
SetPixelGreen(q,
((QM) (((ssize_t)
(2*i*(GetPixelGreen(n)
-GetPixelGreen(pixels)+m))/
((ssize_t) (m*2))
+GetPixelGreen(pixels)))));
SetPixelBlue(q,
((QM) (((ssize_t)
(2*i*(GetPixelBlue(n)
-GetPixelBlue(pixels)+m))/
((ssize_t) (m*2))
+GetPixelBlue(pixels)))));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
((QM) (((ssize_t)
(2*i*(GetPixelOpacity(n)
-GetPixelOpacity(pixels)+m))
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)))));
}
if (magn_methy == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
SetPixelOpacity(q,
(*pixels).opacity+0);
else
SetPixelOpacity(q,
(*n).opacity+0);
}
}
else /* if (magn_methy == 3 || magn_methy == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methy == 5)
{
SetPixelOpacity(q,
(QM) (((ssize_t) (2*i*
(GetPixelOpacity(n)
-GetPixelOpacity(pixels))
+m))/((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
n++;
q++;
pixels++;
} /* x */
if (SyncAuthenticPixels(large_image,exception) == 0)
break;
} /* i */
} /* y */
prev=(PixelPacket *) RelinquishMagickMemory(prev);
next=(PixelPacket *) RelinquishMagickMemory(next);
length=image->columns;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Delete original image");
DeleteImageFromList(&image);
image=large_image;
mng_info->image=image;
/* magnify the columns */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Magnify the columns to %.20g",(double) image->columns);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*pixels;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
pixels=q+(image->columns-length);
n=pixels+1;
for (x=(ssize_t) (image->columns-length);
x < (ssize_t) image->columns; x++)
{
/* To do: Rewrite using Get/Set***PixelComponent() */
if (x == (ssize_t) (image->columns-length))
m=(ssize_t) mng_info->magn_ml;
else if (magn_methx > 1 && x == (ssize_t) image->columns-2)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx <= 1 && x == (ssize_t) image->columns-1)
m=(ssize_t) mng_info->magn_mr;
else if (magn_methx > 1 && x == (ssize_t) image->columns-1)
m=1;
else
m=(ssize_t) mng_info->magn_mx;
for (i=0; i < m; i++)
{
if (magn_methx <= 1)
{
/* replicate previous */
SetPixelRGBO(q,(pixels));
}
else if (magn_methx == 2 || magn_methx == 4)
{
if (i == 0)
{
SetPixelRGBO(q,(pixels));
}
/* To do: Rewrite using Get/Set***PixelComponent() */
else
{
/* Interpolate */
SetPixelRed(q,
(QM) ((2*i*(
GetPixelRed(n)
-GetPixelRed(pixels))+m)
/((ssize_t) (m*2))+
GetPixelRed(pixels)));
SetPixelGreen(q,
(QM) ((2*i*(
GetPixelGreen(n)
-GetPixelGreen(pixels))+m)
/((ssize_t) (m*2))+
GetPixelGreen(pixels)));
SetPixelBlue(q,
(QM) ((2*i*(
GetPixelBlue(n)
-GetPixelBlue(pixels))+m)
/((ssize_t) (m*2))+
GetPixelBlue(pixels)));
if (image->matte != MagickFalse)
SetPixelOpacity(q,
(QM) ((2*i*(
GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)
/((ssize_t) (m*2))+
GetPixelOpacity(pixels)));
}
if (magn_methx == 4)
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelOpacity(q,
GetPixelOpacity(pixels)+0);
}
else
{
SetPixelOpacity(q,
GetPixelOpacity(n)+0);
}
}
}
else /* if (magn_methx == 3 || magn_methx == 5) */
{
/* Replicate nearest */
if (i <= ((m+1) << 1))
{
SetPixelRGBO(q,(pixels));
}
else
{
SetPixelRGBO(q,(n));
}
if (magn_methx == 5)
{
/* Interpolate */
SetPixelOpacity(q,
(QM) ((2*i*( GetPixelOpacity(n)
-GetPixelOpacity(pixels))+m)/
((ssize_t) (m*2))
+GetPixelOpacity(pixels)));
}
}
q++;
}
n++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
if (magn_methx != 1 || magn_methy != 1)
{
/*
Rescale pixels to Quantum
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
for (x=(ssize_t) image->columns-1; x >= 0; x--)
{
SetPixelRed(q,ScaleShortToQuantum(
GetPixelRed(q)));
SetPixelGreen(q,ScaleShortToQuantum(
GetPixelGreen(q)));
SetPixelBlue(q,ScaleShortToQuantum(
GetPixelBlue(q)));
SetPixelOpacity(q,ScaleShortToQuantum(
GetPixelOpacity(q)));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
#endif
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished MAGN processing");
}
}
/*
Crop_box is with respect to the upper left corner of the MNG.
*/
crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id];
crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id];
crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id];
crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id];
crop_box=mng_minimum_box(crop_box,mng_info->clip);
crop_box=mng_minimum_box(crop_box,mng_info->frame);
crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]);
if ((crop_box.left != (mng_info->image_box.left
+mng_info->x_off[object_id])) ||
(crop_box.right != (mng_info->image_box.right
+mng_info->x_off[object_id])) ||
(crop_box.top != (mng_info->image_box.top
+mng_info->y_off[object_id])) ||
(crop_box.bottom != (mng_info->image_box.bottom
+mng_info->y_off[object_id])))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Crop the PNG image");
if ((crop_box.left < crop_box.right) &&
(crop_box.top < crop_box.bottom))
{
Image
*im;
RectangleInfo
crop_info;
/*
Crop_info is with respect to the upper left corner of
the image.
*/
crop_info.x=(crop_box.left-mng_info->x_off[object_id]);
crop_info.y=(crop_box.top-mng_info->y_off[object_id]);
crop_info.width=(size_t) (crop_box.right-crop_box.left);
crop_info.height=(size_t) (crop_box.bottom-crop_box.top);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=0;
image->page.y=0;
im=CropImage(image,&crop_info,exception);
if (im != (Image *) NULL)
{
image->columns=im->columns;
image->rows=im->rows;
im=DestroyImage(im);
image->page.width=image->columns;
image->page.height=image->rows;
image->page.x=crop_box.left;
image->page.y=crop_box.top;
}
}
else
{
/*
No pixels in crop area. The MNG spec still requires
a layer, though, so make a single transparent pixel in
the top left corner.
*/
image->columns=1;
image->rows=1;
image->colors=2;
(void) SetImageBackgroundColor(image);
image->page.width=1;
image->page.height=1;
image->page.x=0;
image->page.y=0;
}
}
#ifndef PNG_READ_EMPTY_PLTE_SUPPORTED
image=mng_info->image;
#endif
}
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy, and promote any depths > 8 to 16.
*/
if (image->depth > 16)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (LosslessReduceDepthOK(image) != MagickFalse)
image->depth = 8;
#endif
GetImageException(image,exception);
if (image_info->number_scenes != 0)
{
if (mng_info->scenes_found >
(ssize_t) (image_info->first_scene+image_info->number_scenes))
break;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading image datastream.");
} while (LocaleCompare(image_info->magick,"MNG") == 0);
(void) CloseBlob(image);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Finished reading all image datastreams.");
#if defined(MNG_INSERT_LAYERS)
if (insert_layers && !mng_info->image_found && (mng_info->mng_width) &&
(mng_info->mng_height))
{
/*
Insert a background layer if nothing else was found.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No images found. Inserting a background layer.");
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocation failed, returning NULL.");
return(DestroyImageList(image));
}
image=SyncNextImageInList(image);
}
image->columns=mng_info->mng_width;
image->rows=mng_info->mng_height;
image->page.width=mng_info->mng_width;
image->page.height=mng_info->mng_height;
image->page.x=0;
image->page.y=0;
image->background_color=mng_background_color;
image->matte=MagickFalse;
if (image_info->ping == MagickFalse)
(void) SetImageBackgroundColor(image);
mng_info->image_found++;
}
#endif
image->iterations=mng_iterations;
if (mng_iterations == 1)
image->start_loop=MagickTrue;
while (GetPreviousImageInList(image) != (Image *) NULL)
{
image_count++;
if (image_count > 10*mng_info->image_found)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted, beginning of list not found",
"`%s'",image_info->filename);
return(DestroyImageList(image));
}
image=GetPreviousImageInList(image);
if (GetNextImageInList(image) == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"Linked list is corrupted; next_image is NULL","`%s'",
image_info->filename);
}
}
if (mng_info->ticks_per_second && mng_info->image_found > 1 &&
GetNextImageInList(image) ==
(Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" First image null");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"image->next for first image is NULL but shouldn't be.",
"`%s'",image_info->filename);
}
if (mng_info->image_found == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No visible images found.");
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"No visible images in file","`%s'",image_info->filename);
return(DestroyImageList(image));
}
if (mng_info->ticks_per_second)
final_delay=1UL*MagickMax(image->ticks_per_second,1L)*
final_delay/mng_info->ticks_per_second;
else
image->start_loop=MagickTrue;
/* Find final nonzero image delay */
final_image_delay=0;
while (GetNextImageInList(image) != (Image *) NULL)
{
if (image->delay)
final_image_delay=image->delay;
image=GetNextImageInList(image);
}
if (final_delay < final_image_delay)
final_delay=final_image_delay;
image->delay=final_delay;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->delay=%.20g, final_delay=%.20g",(double) image->delay,
(double) final_delay);
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Before coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g",(double) image->delay);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g",(double) scene++,(double) image->delay);
}
}
image=GetFirstImageInList(image);
#ifdef MNG_COALESCE_LAYERS
if (insert_layers)
{
Image
*next_image,
*next;
size_t
scene;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Coalesce Images");
scene=image->scene;
next_image=CoalesceImages(image,&image->exception);
if (next_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
image=DestroyImageList(image);
image=next_image;
for (next=image; next != (Image *) NULL; next=next_image)
{
next->page.width=mng_info->mng_width;
next->page.height=mng_info->mng_height;
next->page.x=0;
next->page.y=0;
next->scene=scene++;
next_image=GetNextImageInList(next);
if (next_image == (Image *) NULL)
break;
if (next->delay == 0)
{
scene--;
next_image->previous=GetPreviousImageInList(next);
if (GetPreviousImageInList(next) == (Image *) NULL)
image=next_image;
else
next->previous->next=next_image;
next=DestroyImage(next);
}
}
}
#endif
while (GetNextImageInList(image) != (Image *) NULL)
image=GetNextImageInList(image);
image->dispose=BackgroundDispose;
if (logging != MagickFalse)
{
int
scene;
scene=0;
image=GetFirstImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" After coalesce:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene 0 delay=%.20g dispose=%.20g",(double) image->delay,
(double) image->dispose);
while (GetNextImageInList(image) != (Image *) NULL)
{
image=GetNextImageInList(image);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" scene %.20g delay=%.20g dispose=%.20g",(double) scene++,
(double) image->delay,(double) image->dispose);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage();");
return(image);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,040 |
ImageMagick | cb63560ba25e4a6c51ab282538c24877fff7d471 | static MagickBooleanType WriteWEBPImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
const char
*value;
int
webp_status;
MagickBooleanType
status;
MemoryInfo
*pixel_info;
register uint32_t
*magick_restrict q;
ssize_t
y;
WebPConfig
configure;
WebPPicture
picture;
WebPAuxStats
statistics;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns > 16383UL) || (image->rows > 16383UL))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
if ((WebPPictureInit(&picture) == 0) || (WebPConfigInit(&configure) == 0))
ThrowWriterException(ResourceLimitError,"UnableToEncodeImageFile");
picture.writer=WebPEncodeWriter;
picture.custom_ptr=(void *) image;
#if WEBP_DECODER_ABI_VERSION >= 0x0100
picture.progress_hook=WebPEncodeProgress;
#endif
picture.stats=(&statistics);
picture.width=(int) image->columns;
picture.height=(int) image->rows;
picture.argb_stride=(int) image->columns;
picture.use_argb=1;
if (image->quality != UndefinedCompressionQuality)
configure.quality=(float) image->quality;
if (image->quality >= 100)
configure.lossless=1;
value=GetImageOption(image_info,"webp:lossless");
if (value != (char *) NULL)
configure.lossless=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:method");
if (value != (char *) NULL)
configure.method=StringToInteger(value);
value=GetImageOption(image_info,"webp:image-hint");
if (value != (char *) NULL)
{
if (LocaleCompare(value,"default") == 0)
configure.image_hint=WEBP_HINT_DEFAULT;
if (LocaleCompare(value,"photo") == 0)
configure.image_hint=WEBP_HINT_PHOTO;
if (LocaleCompare(value,"picture") == 0)
configure.image_hint=WEBP_HINT_PICTURE;
#if WEBP_DECODER_ABI_VERSION >= 0x0200
if (LocaleCompare(value,"graph") == 0)
configure.image_hint=WEBP_HINT_GRAPH;
#endif
}
value=GetImageOption(image_info,"webp:target-size");
if (value != (char *) NULL)
configure.target_size=StringToInteger(value);
value=GetImageOption(image_info,"webp:target-psnr");
if (value != (char *) NULL)
configure.target_PSNR=(float) StringToDouble(value,(char **) NULL);
value=GetImageOption(image_info,"webp:segments");
if (value != (char *) NULL)
configure.segments=StringToInteger(value);
value=GetImageOption(image_info,"webp:sns-strength");
if (value != (char *) NULL)
configure.sns_strength=StringToInteger(value);
value=GetImageOption(image_info,"webp:filter-strength");
if (value != (char *) NULL)
configure.filter_strength=StringToInteger(value);
value=GetImageOption(image_info,"webp:filter-sharpness");
if (value != (char *) NULL)
configure.filter_sharpness=StringToInteger(value);
value=GetImageOption(image_info,"webp:filter-type");
if (value != (char *) NULL)
configure.filter_type=StringToInteger(value);
value=GetImageOption(image_info,"webp:auto-filter");
if (value != (char *) NULL)
configure.autofilter=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:alpha-compression");
if (value != (char *) NULL)
configure.alpha_compression=StringToInteger(value);
value=GetImageOption(image_info,"webp:alpha-filtering");
if (value != (char *) NULL)
configure.alpha_filtering=StringToInteger(value);
value=GetImageOption(image_info,"webp:alpha-quality");
if (value != (char *) NULL)
configure.alpha_quality=StringToInteger(value);
value=GetImageOption(image_info,"webp:pass");
if (value != (char *) NULL)
configure.pass=StringToInteger(value);
value=GetImageOption(image_info,"webp:show-compressed");
if (value != (char *) NULL)
configure.show_compressed=StringToInteger(value);
value=GetImageOption(image_info,"webp:preprocessing");
if (value != (char *) NULL)
configure.preprocessing=StringToInteger(value);
value=GetImageOption(image_info,"webp:partitions");
if (value != (char *) NULL)
configure.partitions=StringToInteger(value);
value=GetImageOption(image_info,"webp:partition-limit");
if (value != (char *) NULL)
configure.partition_limit=StringToInteger(value);
#if WEBP_DECODER_ABI_VERSION >= 0x0201
value=GetImageOption(image_info,"webp:emulate-jpeg-size");
if (value != (char *) NULL)
configure.emulate_jpeg_size=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:low-memory");
if (value != (char *) NULL)
configure.low_memory=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:thread-level");
if (value != (char *) NULL)
configure.thread_level=StringToInteger(value);
#endif
if (WebPValidateConfig(&configure) == 0)
ThrowWriterException(ResourceLimitError,"UnableToEncodeImageFile");
/*
Allocate memory for pixels.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
sizeof(*picture.argb));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
picture.argb=(uint32_t *) GetVirtualMemoryBlob(pixel_info);
/*
Convert image to WebP raster pixels.
*/
q=picture.argb;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(uint32_t) (image->alpha_trait != UndefinedPixelTrait ?
ScaleQuantumToChar(GetPixelAlpha(image,p)) << 24 : 0xff000000) |
(ScaleQuantumToChar(GetPixelRed(image,p)) << 16) |
(ScaleQuantumToChar(GetPixelGreen(image,p)) << 8) |
(ScaleQuantumToChar(GetPixelBlue(image,p)));
p+=GetPixelChannels(image);
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
webp_status=WebPEncode(&configure,&picture);
if (webp_status == 0)
{
const char
*message;
switch (picture.error_code)
{
case VP8_ENC_ERROR_OUT_OF_MEMORY:
{
message="out of memory";
break;
}
case VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY:
{
message="bitstream out of memory";
break;
}
case VP8_ENC_ERROR_NULL_PARAMETER:
{
message="NULL parameter";
break;
}
case VP8_ENC_ERROR_INVALID_CONFIGURATION:
{
message="invalid configuration";
break;
}
case VP8_ENC_ERROR_BAD_DIMENSION:
{
message="bad dimension";
break;
}
case VP8_ENC_ERROR_PARTITION0_OVERFLOW:
{
message="partition 0 overflow (> 512K)";
break;
}
case VP8_ENC_ERROR_PARTITION_OVERFLOW:
{
message="partition overflow (> 16M)";
break;
}
case VP8_ENC_ERROR_BAD_WRITE:
{
message="bad write";
break;
}
case VP8_ENC_ERROR_FILE_TOO_BIG:
{
message="file too big (> 4GB)";
break;
}
#if WEBP_DECODER_ABI_VERSION >= 0x0100
case VP8_ENC_ERROR_USER_ABORT:
{
message="user abort";
break;
}
#endif
default:
{
message="unknown exception";
break;
}
}
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
(char *) message,"`%s'",image->filename);
}
picture.argb=(uint32_t *) NULL;
WebPPictureFree(&picture);
pixel_info=RelinquishVirtualMemory(pixel_info);
(void) CloseBlob(image);
return(webp_status == 0 ? MagickFalse : MagickTrue);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,877 |
barebox | 0a9f9a7410681e55362f8311537ebc7be9ad0fbe | int digest_generic_verify(struct digest *d, const unsigned char *md)
{
int ret;
int len = digest_length(d);
unsigned char *tmp;
tmp = xmalloc(len);
ret = digest_final(d, tmp);
if (ret)
goto end;
ret = memcmp(md, tmp, len);
ret = ret ? -EINVAL : 0;
end:
free(tmp);
return ret;
} | 1 | CVE-2021-37847 | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. |
Phase: Architecture and Design
Strategy: Separation of Privilege
Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area.
Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges. | 4,348 |
Chrome | 7cf563aba8f4b3bab68e9bfe43824d952241dcf7 | Core(const OAuthProviderInfo& info,
net::URLRequestContextGetter* request_context_getter)
: provider_info_(info),
request_context_getter_(request_context_getter),
delegate_(NULL) {
}
| 1 | CVE-2012-2890 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 195 |
gimp | c57f9dcf1934a9ab0cd67650f2dea18cb0902270 | save_dialog (void)
{
GtkWidget *dialog;
GtkWidget *table;
GtkWidget *entry;
GtkWidget *spinbutton;
GtkObject *adj;
gboolean run;
dialog = gimp_export_dialog_new (_("Brush"), PLUG_IN_BINARY, SAVE_PROC);
/* The main table */
table = gtk_table_new (2, 2, FALSE);
gtk_container_set_border_width (GTK_CONTAINER (table), 12);
gtk_table_set_row_spacings (GTK_TABLE (table), 6);
gtk_table_set_col_spacings (GTK_TABLE (table), 6);
gtk_box_pack_start (GTK_BOX (gimp_export_dialog_get_content_area (dialog)),
table, TRUE, TRUE, 0);
gtk_widget_show (table);
spinbutton = gimp_spin_button_new (&adj,
info.spacing, 1, 1000, 1, 10, 0, 1, 0);
gtk_entry_set_activates_default (GTK_ENTRY (spinbutton), TRUE);
gimp_table_attach_aligned (GTK_TABLE (table), 0, 0,
_("Spacing:"), 1.0, 0.5,
spinbutton, 1, TRUE);
g_signal_connect (adj, "value-changed",
G_CALLBACK (gimp_int_adjustment_update),
&info.spacing);
entry = gtk_entry_new ();
gtk_widget_set_size_request (entry, 200, -1);
gtk_entry_set_text (GTK_ENTRY (entry), info.description);
gtk_entry_set_activates_default (GTK_ENTRY (entry), TRUE);
gimp_table_attach_aligned (GTK_TABLE (table), 0, 1,
_("Description:"), 1.0, 0.5,
entry, 1, FALSE);
g_signal_connect (entry, "changed",
G_CALLBACK (entry_callback),
info.description);
gtk_widget_show (dialog);
run = (gimp_dialog_run (GIMP_DIALOG (dialog)) == GTK_RESPONSE_OK);
gtk_widget_destroy (dialog);
return run;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,538 |
Chrome | d0947db40187f4708c58e64cbd6013faf9eddeed | xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int cur, l;
xmlChar stop;
int state = ctxt->instate;
int count = 0;
SHRINK;
if (RAW == '"') {
NEXT;
stop = '"';
} else if (RAW == '\'') {
NEXT;
stop = '\'';
} else {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
ctxt->instate = XML_PARSER_SYSTEM_LITERAL;
cur = CUR_CHAR(l);
while ((IS_CHAR(cur)) && (cur != stop)) { /* checked */
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlFree(buf);
xmlErrMemory(ctxt, NULL);
ctxt->instate = (xmlParserInputState) state;
return(NULL);
}
buf = tmp;
}
count++;
if (count > 50) {
GROW;
count = 0;
}
COPY_BUF(l,buf,len,cur);
NEXTL(l);
cur = CUR_CHAR(l);
if (cur == 0) {
GROW;
SHRINK;
cur = CUR_CHAR(l);
}
}
buf[len] = 0;
ctxt->instate = (xmlParserInputState) state;
if (!IS_CHAR(cur)) {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
} else {
NEXT;
}
return(buf);
}
| 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). | 336 |
libx11 | 2fcfcc49f3b1be854bb9085993a01d17c62acf60 | _XimAttributeToValue(
Xic ic,
XIMResourceList res,
CARD16 *data,
INT16 data_len,
XPointer value,
BITMASK32 mode)
{
switch (res->resource_size) {
case XimType_SeparatorOfNestedList:
case XimType_NEST:
break;
case XimType_CARD8:
case XimType_CARD16:
case XimType_CARD32:
case XimType_Window:
case XimType_XIMHotKeyState:
_XCopyToArg((XPointer)data, (XPointer *)&value, data_len);
break;
case XimType_STRING8:
{
char *str;
if (!(value))
return False;
if (!(str = Xmalloc(data_len + 1)))
return False;
(void)memcpy(str, (char *)data, data_len);
str[data_len] = '\0';
*((char **)value) = str;
break;
}
case XimType_XIMStyles:
{
CARD16 num = data[0];
register CARD32 *style_list = (CARD32 *)&data[2];
XIMStyle *style;
XIMStyles *rep;
register int i;
char *p;
unsigned int alloc_len;
if (!(value))
return False;
if (num > (USHRT_MAX / sizeof(XIMStyle)))
return False;
if ((sizeof(num) + (num * sizeof(XIMStyle))) > data_len)
return False;
alloc_len = sizeof(XIMStyles) + sizeof(XIMStyle) * num;
if (alloc_len < sizeof(XIMStyles))
return False;
if (!(p = Xmalloc(alloc_len)))
return False;
rep = (XIMStyles *)p;
style = (XIMStyle *)(p + sizeof(XIMStyles));
for (i = 0; i < num; i++)
style[i] = (XIMStyle)style_list[i];
rep->count_styles = (unsigned short)num;
rep->supported_styles = style;
*((XIMStyles **)value) = rep;
break;
}
case XimType_XRectangle:
{
XRectangle *rep;
if (!(value))
return False;
if (!(rep = Xmalloc(sizeof(XRectangle))))
return False;
rep->x = data[0];
rep->y = data[1];
rep->width = data[2];
rep->height = data[3];
*((XRectangle **)value) = rep;
break;
}
case XimType_XPoint:
{
XPoint *rep;
if (!(value))
return False;
if (!(rep = Xmalloc(sizeof(XPoint))))
return False;
rep->x = data[0];
rep->y = data[1];
*((XPoint **)value) = rep;
break;
}
case XimType_XFontSet:
{
INT16 len = data[0];
char *base_name;
XFontSet rep = (XFontSet)NULL;
char **missing_list = NULL;
int missing_count;
char *def_string;
if (!(value))
return False;
if (!ic)
return False;
if (!(base_name = Xmalloc(len + 1)))
return False;
(void)strncpy(base_name, (char *)&data[1], (int)len);
base_name[len] = '\0';
if (mode & XIM_PREEDIT_ATTR) {
if (!strcmp(base_name, ic->private.proto.preedit_font)) {
rep = ic->core.preedit_attr.fontset;
} else if (!ic->private.proto.preedit_font_length) {
rep = XCreateFontSet(ic->core.im->core.display,
base_name, &missing_list,
&missing_count, &def_string);
}
} else if (mode & XIM_STATUS_ATTR) {
if (!strcmp(base_name, ic->private.proto.status_font)) {
rep = ic->core.status_attr.fontset;
} else if (!ic->private.proto.status_font_length) {
rep = XCreateFontSet(ic->core.im->core.display,
base_name, &missing_list,
&missing_count, &def_string);
}
}
Xfree(base_name);
Xfree(missing_list);
*((XFontSet *)value) = rep;
break;
}
case XimType_XIMHotKeyTriggers:
{
CARD32 num = *((CARD32 *)data);
register CARD32 *key_list = (CARD32 *)&data[2];
XIMHotKeyTrigger *key;
XIMHotKeyTriggers *rep;
register int i;
char *p;
unsigned int alloc_len;
if (!(value))
return False;
if (num > (UINT_MAX / sizeof(XIMHotKeyTrigger)))
return False;
if ((sizeof(num) + (num * sizeof(XIMHotKeyTrigger))) > data_len)
return False;
alloc_len = sizeof(XIMHotKeyTriggers)
+ sizeof(XIMHotKeyTrigger) * num;
if (alloc_len < sizeof(XIMHotKeyTriggers))
return False;
if (!(p = Xmalloc(alloc_len)))
return False;
rep = (XIMHotKeyTriggers *)p;
key = (XIMHotKeyTrigger *)(p + sizeof(XIMHotKeyTriggers));
for (i = 0; i < num; i++, key_list += 3) {
key[i].keysym = (KeySym)key_list[0]; /* keysym */
key[i].modifier = (int)key_list[1]; /* modifier */
key[i].modifier_mask = (int)key_list[2]; /* modifier_mask */
}
rep->num_hot_key = (int)num;
rep->key = key;
*((XIMHotKeyTriggers **)value) = rep;
break;
}
case XimType_XIMStringConversion:
{
break;
}
default:
return False;
}
return True;
} | 1 | CVE-2020-14344 | 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,971 |
linux | 3aa02cb664c5fb1042958c8d1aa8c35055a2ebc4 | static int snd_pcm_lib_read_transfer(struct snd_pcm_substream *substream,
unsigned int hwoff,
unsigned long data, unsigned int off,
snd_pcm_uframes_t frames)
{
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
char __user *buf = (char __user *) data + frames_to_bytes(runtime, off);
if (substream->ops->copy) {
if ((err = substream->ops->copy(substream, -1, hwoff, buf, frames)) < 0)
return err;
} else {
char *hwbuf = runtime->dma_area + frames_to_bytes(runtime, hwoff);
if (copy_to_user(buf, hwbuf, frames_to_bytes(runtime, frames)))
return -EFAULT;
}
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,689 |
mongo | 0a076417d1d7fba3632b73349a1fd29a83e68816 | TEST(ExpressionRangeTest, ComputesRangeWithLargeNegativeStep) {
assertExpectedResults("$range",
{{{Value(3), Value(-5), Value(-3)}, Value(BSON_ARRAY(3 << 0 << -3))}});
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,994 |
Chrome | c13e1da62b5f5f0e6fe8c1f769a5a28415415244 | error::Error GLES2DecoderImpl::HandleVertexAttribPointer(
uint32 immediate_data_size, const gles2::VertexAttribPointer& c) {
if (!bound_array_buffer_ || bound_array_buffer_->IsDeleted()) {
SetGLError(GL_INVALID_VALUE,
"glVertexAttribPointer: no array buffer bound");
return error::kNoError;
}
GLuint indx = c.indx;
GLint size = c.size;
GLenum type = c.type;
GLboolean normalized = c.normalized;
GLsizei stride = c.stride;
GLsizei offset = c.offset;
const void* ptr = reinterpret_cast<const void*>(offset);
if (!validators_->vertex_attrib_type.IsValid(type)) {
SetGLError(GL_INVALID_ENUM,
"glVertexAttribPointer: type GL_INVALID_ENUM");
return error::kNoError;
}
if (!validators_->vertex_attrib_size.IsValid(size)) {
SetGLError(GL_INVALID_VALUE,
"glVertexAttribPointer: size GL_INVALID_VALUE");
return error::kNoError;
}
if (indx >= group_->max_vertex_attribs()) {
SetGLError(GL_INVALID_VALUE, "glVertexAttribPointer: index out of range");
return error::kNoError;
}
if (stride < 0) {
SetGLError(GL_INVALID_VALUE,
"glVertexAttribPointer: stride < 0");
return error::kNoError;
}
if (stride > 255) {
SetGLError(GL_INVALID_VALUE,
"glVertexAttribPointer: stride > 255");
return error::kNoError;
}
if (offset < 0) {
SetGLError(GL_INVALID_VALUE,
"glVertexAttribPointer: offset < 0");
return error::kNoError;
}
GLsizei component_size =
GLES2Util::GetGLTypeSizeForTexturesAndBuffers(type);
if (offset % component_size > 0) {
SetGLError(GL_INVALID_OPERATION,
"glVertexAttribPointer: offset not valid for type");
return error::kNoError;
}
if (stride % component_size > 0) {
SetGLError(GL_INVALID_OPERATION,
"glVertexAttribPointer: stride not valid for type");
return error::kNoError;
}
vertex_attrib_manager_.SetAttribInfo(
indx,
bound_array_buffer_,
size,
type,
normalized,
stride,
stride != 0 ? stride : component_size * size,
offset);
if (type != GL_FIXED) {
glVertexAttribPointer(indx, size, type, normalized, stride, ptr);
}
return error::kNoError;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,121 |
xserver | cad5a1050b7184d828aef9c1dd151c3ab649d37e | XineramaXvShmPutImage(ClientPtr client)
{
REQUEST(xvShmPutImageReq);
PanoramiXRes *draw, *gc, *port;
Bool send_event = stuff->send_event;
Bool isRoot;
int result, i, x, y;
REQUEST_SIZE_MATCH(xvShmPutImageReq);
result = dixLookupResourceByClass((void **) &draw, stuff->drawable,
XRC_DRAWABLE, client, DixWriteAccess);
if (result != Success)
result = dixLookupResourceByType((void **) &gc, stuff->gc,
XRT_GC, client, DixReadAccess);
if (result != Success)
return result;
result = dixLookupResourceByType((void **) &port, stuff->port,
XvXRTPort, client, DixReadAccess);
if (result != Success)
return result;
isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root;
x = stuff->drw_x;
y = stuff->drw_y;
FOR_NSCREENS_BACKWARD(i) {
if (port->info[i].id) {
stuff->drawable = draw->info[i].id;
stuff->port = port->info[i].id;
stuff->gc = gc->info[i].id;
stuff->drw_x = x;
stuff->drw_y = y;
if (isRoot) {
stuff->drw_x -= screenInfo.screens[i]->x;
stuff->drw_y -= screenInfo.screens[i]->y;
}
stuff->send_event = (send_event && !i) ? 1 : 0;
result = ProcXvShmPutImage(client);
}
}
return result;
}
| 1 | CVE-2017-12187 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 4,502 |
teeworlds | c68402fa7e279d42886d5951d1ea8ac2facc1ea5 | int CServerBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason)
{
if(pRange->IsValid())
return BanExt(&m_BanRangePool, pRange, Seconds, pReason);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)");
return -1;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,554 |
Android | 295c883fe3105b19bcd0f9e07d54c6b589fc5bff | OMX_ERRORTYPE SoftMP3::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = mNumChannels;
pcmParams->nSamplingRate = mSamplingRate;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioMp3:
{
OMX_AUDIO_PARAM_MP3TYPE *mp3Params =
(OMX_AUDIO_PARAM_MP3TYPE *)params;
if (mp3Params->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
mp3Params->nChannels = mNumChannels;
mp3Params->nBitRate = 0 /* unknown */;
mp3Params->nSampleRate = mSamplingRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 1 | CVE-2016-2476 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 4,396 |
linux | a8b0ca17b80e92faab46ee7179ba9e99ccb61233 | int handle_ldf_stq(u32 insn, struct pt_regs *regs)
{
unsigned long addr = compute_effective_address(regs, insn, 0);
int freg = ((insn >> 25) & 0x1e) | ((insn >> 20) & 0x20);
struct fpustate *f = FPUSTATE;
int asi = decode_asi(insn, regs);
int flag = (freg < 32) ? FPRS_DL : FPRS_DU;
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0);
save_and_clear_fpu();
current_thread_info()->xfsr[0] &= ~0x1c000;
if (freg & 3) {
current_thread_info()->xfsr[0] |= (6 << 14) /* invalid_fp_register */;
do_fpother(regs);
return 0;
}
if (insn & 0x200000) {
/* STQ */
u64 first = 0, second = 0;
if (current_thread_info()->fpsaved[0] & flag) {
first = *(u64 *)&f->regs[freg];
second = *(u64 *)&f->regs[freg+2];
}
if (asi < 0x80) {
do_privact(regs);
return 1;
}
switch (asi) {
case ASI_P:
case ASI_S: break;
case ASI_PL:
case ASI_SL:
{
/* Need to convert endians */
u64 tmp = __swab64p(&first);
first = __swab64p(&second);
second = tmp;
break;
}
default:
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
if (put_user (first >> 32, (u32 __user *)addr) ||
__put_user ((u32)first, (u32 __user *)(addr + 4)) ||
__put_user (second >> 32, (u32 __user *)(addr + 8)) ||
__put_user ((u32)second, (u32 __user *)(addr + 12))) {
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
} else {
/* LDF, LDDF, LDQF */
u32 data[4] __attribute__ ((aligned(8)));
int size, i;
int err;
if (asi < 0x80) {
do_privact(regs);
return 1;
} else if (asi > ASI_SNFL) {
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
switch (insn & 0x180000) {
case 0x000000: size = 1; break;
case 0x100000: size = 4; break;
default: size = 2; break;
}
for (i = 0; i < size; i++)
data[i] = 0;
err = get_user (data[0], (u32 __user *) addr);
if (!err) {
for (i = 1; i < size; i++)
err |= __get_user (data[i], (u32 __user *)(addr + 4*i));
}
if (err && !(asi & 0x2 /* NF */)) {
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
if (asi & 0x8) /* Little */ {
u64 tmp;
switch (size) {
case 1: data[0] = le32_to_cpup(data + 0); break;
default:*(u64 *)(data + 0) = le64_to_cpup((u64 *)(data + 0));
break;
case 4: tmp = le64_to_cpup((u64 *)(data + 0));
*(u64 *)(data + 0) = le64_to_cpup((u64 *)(data + 2));
*(u64 *)(data + 2) = tmp;
break;
}
}
if (!(current_thread_info()->fpsaved[0] & FPRS_FEF)) {
current_thread_info()->fpsaved[0] = FPRS_FEF;
current_thread_info()->gsr[0] = 0;
}
if (!(current_thread_info()->fpsaved[0] & flag)) {
if (freg < 32)
memset(f->regs, 0, 32*sizeof(u32));
else
memset(f->regs+32, 0, 32*sizeof(u32));
}
memcpy(f->regs + freg, data, size * 4);
current_thread_info()->fpsaved[0] |= flag;
}
advance(regs);
return 1;
}
| 1 | CVE-2011-2918 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 3,990 |
Chrome | 11a4cc4a6d6e665d9a118fada4b7c658d6f70d95 | void RenderLayerScrollableArea::setScrollOffset(const IntPoint& newScrollOffset)
{
if (!box().isMarquee()) {
if (m_scrollDimensionsDirty)
computeScrollDimensions();
}
if (scrollOffset() == toIntSize(newScrollOffset))
return;
setScrollOffset(toIntSize(newScrollOffset));
LocalFrame* frame = box().frame();
ASSERT(frame);
RefPtr<FrameView> frameView = box().frameView();
TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ScrollLayer", "data", InspectorScrollLayerEvent::data(&box()));
InspectorInstrumentation::willScrollLayer(&box());
const RenderLayerModelObject* paintInvalidationContainer = box().containerForPaintInvalidation();
if (!frameView->isInPerformLayout()) {
layer()->clipper().clearClipRectsIncludingDescendants();
box().setPreviousPaintInvalidationRect(box().boundsRectForPaintInvalidation(paintInvalidationContainer));
frameView->updateAnnotatedRegions();
frameView->updateWidgetPositions();
RELEASE_ASSERT(frameView->renderView());
updateCompositingLayersAfterScroll();
}
frame->selection().setCaretRectNeedsUpdate();
FloatQuad quadForFakeMouseMoveEvent = FloatQuad(layer()->renderer()->previousPaintInvalidationRect());
quadForFakeMouseMoveEvent = paintInvalidationContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
frame->eventHandler().dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
bool requiresPaintInvalidation = true;
if (!box().isMarquee() && box().view()->compositor()->inCompositingMode()) {
DisableCompositingQueryAsserts disabler;
bool onlyScrolledCompositedLayers = scrollsOverflow()
&& !layer()->hasVisibleNonLayerContent()
&& !layer()->hasNonCompositedChild()
&& !layer()->hasBlockSelectionGapBounds()
&& box().style()->backgroundLayers().attachment() != LocalBackgroundAttachment;
if (usesCompositedScrolling() || onlyScrolledCompositedLayers)
requiresPaintInvalidation = false;
}
if (requiresPaintInvalidation) {
if (box().frameView()->isInPerformLayout())
box().setShouldDoFullPaintInvalidation(true);
else
box().invalidatePaintUsingContainer(paintInvalidationContainer, layer()->renderer()->previousPaintInvalidationRect(), InvalidationScroll);
}
if (box().node())
box().node()->document().enqueueScrollEventForNode(box().node());
if (AXObjectCache* cache = box().document().existingAXObjectCache())
cache->handleScrollPositionChanged(&box());
InspectorInstrumentation::didScrollLayer(&box());
}
| 1 | CVE-2014-3191 | 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,956 |
openssl | 1421e0c584ae9120ca1b88098f13d6d2e90b83a3 | int ssl3_send_certificate_request(SSL *s)
{
unsigned char *p,*d;
int i,j,nl,off,n;
STACK_OF(X509_NAME) *sk=NULL;
X509_NAME *name;
BUF_MEM *buf;
if (s->state == SSL3_ST_SW_CERT_REQ_A)
{
buf=s->init_buf;
d=p=ssl_handshake_start(s);
/* get the list of acceptable cert types */
p++;
n=ssl3_get_req_cert_type(s,p);
d[0]=n;
p+=n;
n++;
if (SSL_USE_SIGALGS(s))
{
const unsigned char *psigs;
unsigned char *etmp = p;
nl = tls12_get_psigalgs(s, &psigs);
/* Skip over length for now */
p += 2;
nl = tls12_copy_sigalgs(s, p, psigs, nl);
/* Now fill in length */
s2n(nl, etmp);
p += nl;
n += nl + 2;
}
off=n;
p+=2;
n+=2;
sk=SSL_get_client_CA_list(s);
nl=0;
if (sk != NULL)
{
for (i=0; i<sk_X509_NAME_num(sk); i++)
{
name=sk_X509_NAME_value(sk,i);
j=i2d_X509_NAME(name,NULL);
if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2))
{
SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
goto err;
}
p = ssl_handshake_start(s) + n;
if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
{
s2n(j,p);
i2d_X509_NAME(name,&p);
n+=2+j;
nl+=2+j;
}
else
{
d=p;
i2d_X509_NAME(name,&p);
j-=2; s2n(j,d); j+=2;
n+=j;
nl+=j;
}
}
}
/* else no CA names */
p = ssl_handshake_start(s) + off;
s2n(nl,p);
ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
#ifdef NETSCAPE_HANG_BUG
if (!SSL_IS_DTLS(s))
{
if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
{
SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
goto err;
}
p=(unsigned char *)s->init_buf->data + s->init_num;
/* do the header */
*(p++)=SSL3_MT_SERVER_DONE;
*(p++)=0;
*(p++)=0;
*(p++)=0;
s->init_num += 4;
}
#endif
s->state = SSL3_ST_SW_CERT_REQ_B;
}
/* SSL3_ST_SW_CERT_REQ_B */
return ssl_do_write(s);
err:
return(-1);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,493 |
php-src | 70ddc853fd4757004ac488e6ee892897bb6f395a | PHPAPI int php_exec(int type, char *cmd, zval *array, zval *return_value TSRMLS_DC)
{
FILE *fp;
char *buf;
int l = 0, pclose_return;
char *b, *d=NULL;
php_stream *stream;
size_t buflen, bufl = 0;
#if PHP_SIGCHILD
void (*sig_handler)() = NULL;
#endif
#if PHP_SIGCHILD
sig_handler = signal (SIGCHLD, SIG_DFL);
#endif
#ifdef PHP_WIN32
fp = VCWD_POPEN(cmd, "rb");
#else
fp = VCWD_POPEN(cmd, "r");
#endif
if (!fp) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to fork [%s]", cmd);
goto err;
}
stream = php_stream_fopen_from_pipe(fp, "rb");
buf = (char *) emalloc(EXEC_INPUT_BUF);
buflen = EXEC_INPUT_BUF;
if (type != 3) {
b = buf;
while (php_stream_get_line(stream, b, EXEC_INPUT_BUF, &bufl)) {
/* no new line found, let's read some more */
if (b[bufl - 1] != '\n' && !php_stream_eof(stream)) {
if (buflen < (bufl + (b - buf) + EXEC_INPUT_BUF)) {
bufl += b - buf;
buflen = bufl + EXEC_INPUT_BUF;
buf = erealloc(buf, buflen);
b = buf + bufl;
} else {
b += bufl;
}
continue;
} else if (b != buf) {
bufl += b - buf;
}
if (type == 1) {
PHPWRITE(buf, bufl);
if (php_output_get_level(TSRMLS_C) < 1) {
sapi_flush(TSRMLS_C);
}
} else if (type == 2) {
/* strip trailing whitespaces */
l = bufl;
while (l-- && isspace(((unsigned char *)buf)[l]));
if (l != (int)(bufl - 1)) {
bufl = l + 1;
buf[bufl] = '\0';
}
add_next_index_stringl(array, buf, bufl, 1);
}
b = buf;
}
if (bufl) {
/* strip trailing whitespaces if we have not done so already */
if ((type == 2 && buf != b) || type != 2) {
l = bufl;
while (l-- && isspace(((unsigned char *)buf)[l]));
if (l != (int)(bufl - 1)) {
bufl = l + 1;
buf[bufl] = '\0';
}
if (type == 2) {
add_next_index_stringl(array, buf, bufl, 1);
}
}
/* Return last line from the shell command */
RETVAL_STRINGL(buf, bufl);
} else { /* should return NULL, but for BC we return "" */
RETVAL_EMPTY_STRING();
}
} else {
while((bufl = php_stream_read(stream, buf, EXEC_INPUT_BUF)) > 0) {
PHPWRITE(buf, bufl);
}
}
pclose_return = php_stream_close(stream);
efree(buf);
done:
#if PHP_SIGCHILD
if (sig_handler) {
signal(SIGCHLD, sig_handler);
}
#endif
if (d) {
efree(d);
}
return pclose_return;
err:
pclose_return = -1;
goto done;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,822 |
linux | 792039c73cf176c8e39a6e8beef2c94ff46522ed | static struct l2cap_chan *l2cap_sock_new_connection_cb(struct l2cap_chan *chan)
{
struct sock *sk, *parent = chan->data;
/* Check for backlog size */
if (sk_acceptq_is_full(parent)) {
BT_DBG("backlog full %d", parent->sk_ack_backlog);
return NULL;
}
sk = l2cap_sock_alloc(sock_net(parent), NULL, BTPROTO_L2CAP,
GFP_ATOMIC);
if (!sk)
return NULL;
bt_sock_reclassify_lock(sk, BTPROTO_L2CAP);
l2cap_sock_init(sk, parent);
return l2cap_pi(sk)->chan;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,255 |
libcroco | 898e3a8c8c0314d2e6b106809a8e3e93cf9d4394 | cr_input_peek_byte (CRInput const * a_this, enum CRSeekPos a_origin,
gulong a_offset, guchar * a_byte)
{
gulong abs_offset = 0;
g_return_val_if_fail (a_this && PRIVATE (a_this)
&& a_byte, CR_BAD_PARAM_ERROR);
switch (a_origin) {
case CR_SEEK_CUR:
abs_offset = PRIVATE (a_this)->next_byte_index - 1 + a_offset;
break;
case CR_SEEK_BEGIN:
abs_offset = a_offset;
break;
case CR_SEEK_END:
abs_offset = PRIVATE (a_this)->in_buf_size - 1 - a_offset;
break;
default:
return CR_BAD_PARAM_ERROR;
}
if (abs_offset < PRIVATE (a_this)->in_buf_size) {
*a_byte = PRIVATE (a_this)->in_buf[abs_offset];
return CR_OK;
} else {
return CR_END_OF_INPUT_ERROR;
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,436 |
openssl | 5fbc59cac60db4d7c3172152b8bdafe0c675fabd | BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert)
{
int i, j;
BIO *out = NULL, *btmp = NULL, *etmp = NULL, *bio = NULL;
X509_ALGOR *xa;
ASN1_OCTET_STRING *data_body = NULL;
const EVP_MD *evp_md;
const EVP_CIPHER *evp_cipher = NULL;
EVP_CIPHER_CTX *evp_ctx = NULL;
X509_ALGOR *enc_alg = NULL;
STACK_OF(X509_ALGOR) *md_sk = NULL;
STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL;
PKCS7_RECIP_INFO *ri = NULL;
unsigned char *ek = NULL, *tkey = NULL;
int eklen = 0, tkeylen = 0;
if (p7 == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_INVALID_NULL_POINTER);
return NULL;
}
if (p7->d.ptr == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_NO_CONTENT);
return NULL;
}
i = OBJ_obj2nid(p7->type);
p7->state = PKCS7_S_HEADER;
switch (i) {
case NID_pkcs7_signed:
/*
* p7->d.sign->contents is a PKCS7 structure consisting of a contentType
* field and optional content.
* data_body is NULL if that structure has no (=detached) content
* or if the contentType is wrong (i.e., not "data").
*/
data_body = PKCS7_get_octet_string(p7->d.sign->contents);
if (!PKCS7_is_detached(p7) && data_body == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
PKCS7_R_INVALID_SIGNED_DATA_TYPE);
goto err;
}
md_sk = p7->d.sign->md_algs;
break;
case NID_pkcs7_signedAndEnveloped:
rsk = p7->d.signed_and_enveloped->recipientinfo;
md_sk = p7->d.signed_and_enveloped->md_algs;
/* data_body is NULL if the optional EncryptedContent is missing. */
data_body = p7->d.signed_and_enveloped->enc_data->enc_data;
enc_alg = p7->d.signed_and_enveloped->enc_data->algorithm;
evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
goto err;
}
break;
case NID_pkcs7_enveloped:
rsk = p7->d.enveloped->recipientinfo;
enc_alg = p7->d.enveloped->enc_data->algorithm;
/* data_body is NULL if the optional EncryptedContent is missing. */
data_body = p7->d.enveloped->enc_data->enc_data;
evp_cipher = EVP_get_cipherbyobj(enc_alg->algorithm);
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
goto err;
}
break;
default:
PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_UNSUPPORTED_CONTENT_TYPE);
goto err;
}
/* Detached content must be supplied via in_bio instead. */
if (data_body == NULL && in_bio == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, PKCS7_R_NO_CONTENT);
goto err;
}
/* We will be checking the signature */
if (md_sk != NULL) {
for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++) {
xa = sk_X509_ALGOR_value(md_sk, i);
if ((btmp = BIO_new(BIO_f_md())) == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);
goto err;
}
j = OBJ_obj2nid(xa->algorithm);
evp_md = EVP_get_digestbynid(j);
if (evp_md == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
PKCS7_R_UNKNOWN_DIGEST_TYPE);
goto err;
}
BIO_set_md(btmp, evp_md);
if (out == NULL)
out = btmp;
else
BIO_push(out, btmp);
btmp = NULL;
}
}
if (evp_cipher != NULL) {
#if 0
unsigned char key[EVP_MAX_KEY_LENGTH];
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char *p;
int keylen, ivlen;
int max;
X509_OBJECT ret;
#endif
if ((etmp = BIO_new(BIO_f_cipher())) == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE, ERR_R_BIO_LIB);
goto err;
}
/*
* It was encrypted, we need to decrypt the secret key with the
* private key
*/
/*
* Find the recipientInfo which matches the passed certificate (if
* any)
*/
if (pcert) {
for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
if (!pkcs7_cmp_ri(ri, pcert))
break;
ri = NULL;
}
if (ri == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,
PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE);
goto err;
}
}
/* If we haven't got a certificate try each ri in turn */
if (pcert == NULL) {
/*
* Always attempt to decrypt all rinfo even after sucess as a
* defence against MMA timing attacks.
*/
for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rsk); i++) {
ri = sk_PKCS7_RECIP_INFO_value(rsk, i);
if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)
goto err;
ERR_clear_error();
}
} else {
/* Only exit on fatal errors, not decrypt failure */
if (pkcs7_decrypt_rinfo(&ek, &eklen, ri, pkey) < 0)
goto err;
ERR_clear_error();
}
evp_ctx = NULL;
BIO_get_cipher_ctx(etmp, &evp_ctx);
if (EVP_CipherInit_ex(evp_ctx, evp_cipher, NULL, NULL, NULL, 0) <= 0)
goto err;
if (EVP_CIPHER_asn1_to_param(evp_ctx, enc_alg->parameter) < 0)
goto err;
/* Generate random key as MMA defence */
tkeylen = EVP_CIPHER_CTX_key_length(evp_ctx);
tkey = OPENSSL_malloc(tkeylen);
if (!tkey)
goto err;
if (EVP_CIPHER_CTX_rand_key(evp_ctx, tkey) <= 0)
goto err;
if (ek == NULL) {
ek = tkey;
eklen = tkeylen;
tkey = NULL;
}
if (eklen != EVP_CIPHER_CTX_key_length(evp_ctx)) {
/*
* Some S/MIME clients don't use the same key and effective key
* length. The key length is determined by the size of the
* decrypted RSA key.
*/
if (!EVP_CIPHER_CTX_set_key_length(evp_ctx, eklen)) {
/* Use random key as MMA defence */
OPENSSL_cleanse(ek, eklen);
OPENSSL_free(ek);
ek = tkey;
eklen = tkeylen;
tkey = NULL;
}
}
/* Clear errors so we don't leak information useful in MMA */
ERR_clear_error();
if (EVP_CipherInit_ex(evp_ctx, NULL, NULL, ek, NULL, 0) <= 0)
goto err;
if (ek) {
OPENSSL_cleanse(ek, eklen);
OPENSSL_free(ek);
ek = NULL;
}
if (tkey) {
OPENSSL_cleanse(tkey, tkeylen);
OPENSSL_free(tkey);
tkey = NULL;
}
if (out == NULL)
out = etmp;
else
BIO_push(out, etmp);
etmp = NULL;
}
#if 1
if (in_bio != NULL) {
bio = in_bio;
} else {
# if 0
bio = BIO_new(BIO_s_mem());
/*
* We need to set this so that when we have read all the data, the
* encrypt BIO, if present, will read EOF and encode the last few
* bytes
*/
BIO_set_mem_eof_return(bio, 0);
if (data_body->length > 0)
BIO_write(bio, (char *)data_body->data, data_body->length);
# else
if (data_body->length > 0)
bio = BIO_new_mem_buf(data_body->data, data_body->length);
else {
bio = BIO_new(BIO_s_mem());
BIO_set_mem_eof_return(bio, 0);
}
if (bio == NULL)
goto err;
# endif
}
BIO_push(out, bio);
bio = NULL;
#endif
if (0) {
err:
if (ek) {
OPENSSL_cleanse(ek, eklen);
OPENSSL_free(ek);
}
if (tkey) {
OPENSSL_cleanse(tkey, tkeylen);
OPENSSL_free(tkey);
}
if (out != NULL)
BIO_free_all(out);
if (btmp != NULL)
BIO_free_all(btmp);
if (etmp != NULL)
BIO_free_all(etmp);
if (bio != NULL)
BIO_free_all(bio);
out = NULL;
}
return (out);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,975 |
libssh | 391c78de9d0f7baec3a44d86a76f4e1324eb9529 | ssh_scp ssh_scp_new(ssh_session session, int mode, const char *location)
{
ssh_scp scp = NULL;
if (session == NULL) {
goto error;
}
scp = (ssh_scp)calloc(1, sizeof(struct ssh_scp_struct));
if (scp == NULL) {
ssh_set_error(session, SSH_FATAL,
"Error allocating memory for ssh_scp");
goto error;
}
if ((mode & ~SSH_SCP_RECURSIVE) != SSH_SCP_WRITE &&
(mode & ~SSH_SCP_RECURSIVE) != SSH_SCP_READ)
{
ssh_set_error(session, SSH_FATAL,
"Invalid mode %d for ssh_scp_new()", mode);
goto error;
}
if (strlen(location) > 32 * 1024) {
ssh_set_error(session, SSH_FATAL,
"Location path is too long");
goto error;
}
scp->location = strdup(location);
if (scp->location == NULL) {
ssh_set_error(session, SSH_FATAL,
"Error allocating memory for ssh_scp");
goto error;
}
scp->session = session;
scp->mode = mode & ~SSH_SCP_RECURSIVE;
scp->recursive = (mode & SSH_SCP_RECURSIVE) != 0;
scp->channel = NULL;
scp->state = SSH_SCP_NEW;
return scp;
error:
ssh_scp_free(scp);
return NULL;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,336 |
tensorflow | 7cf73a2274732c9d82af51c2bc2cf90d13cd7e6d | TEST(ArrayOpsTest, QuantizeAndDequantizeV2_ShapeFn) {
ShapeInferenceTestOp op("QuantizeAndDequantizeV2");
op.input_tensors.resize(3);
TF_ASSERT_OK(NodeDefBuilder("test", "QuantizeAndDequantizeV2")
.Input("input", 0, DT_FLOAT)
.Input("input_min", 1, DT_FLOAT)
.Input("input_max", 2, DT_FLOAT)
.Attr("signed_input", true)
.Attr("num_bits", 8)
.Attr("range_given", false)
.Attr("narrow_range", false)
.Attr("axis", -1)
.Finalize(&op.node_def));
INFER_OK(op, "?;?;?", "in0");
INFER_OK(op, "[];?;?", "in0");
INFER_OK(op, "[1,2,?,4,5];?;?", "in0");
INFER_ERROR("Shape must be rank 0 but is rank 1", op, "[1,2,?,4,5];[1];[]");
INFER_ERROR("Shapes must be equal rank, but are 1 and 0", op,
"[1,2,?,4,5];[];[1]");
INFER_ERROR("Shape must be rank 0 but is rank 1", op, "[1,2,?,4,5];[1];[1]");
} | 1 | CVE-2021-41205 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 4,788 |
Chrome | dc7b094a338c6c521f918f478e993f0f74bbea0d | static void ConnectionChangeHandler(void* object, bool connected) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->ime_connected_ = connected;
if (connected) {
input_method_library->pending_config_requests_.clear();
input_method_library->pending_config_requests_.insert(
input_method_library->current_config_values_.begin(),
input_method_library->current_config_values_.end());
input_method_library->FlushImeConfig();
input_method_library->ChangeInputMethod(
input_method_library->previous_input_method().id);
input_method_library->ChangeInputMethod(
input_method_library->current_input_method().id);
}
}
| 1 | CVE-2011-2804 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 1,079 |
savannah | 2cdc4562f873237f1c77d43540537c7a721d3fd8 | cf2_hintmap_build( CF2_HintMap hintmap,
CF2_ArrStack hStemHintArray,
CF2_ArrStack vStemHintArray,
CF2_HintMask hintMask,
CF2_Fixed hintOrigin,
FT_Bool initialMap )
{
FT_Byte* maskPtr;
CF2_Font font = hintmap->font;
CF2_HintMaskRec tempHintMask;
size_t bitCount, i;
FT_Byte maskByte;
/* check whether initial map is constructed */
if ( !initialMap && !cf2_hintmap_isValid( hintmap->initialHintMap ) )
{
/* make recursive call with initialHintMap and temporary mask; */
/* temporary mask will get all bits set, below */
cf2_hintmask_init( &tempHintMask, hintMask->error );
cf2_hintmap_build( hintmap->initialHintMap,
hStemHintArray,
vStemHintArray,
&tempHintMask,
hintOrigin,
TRUE );
}
if ( !cf2_hintmask_isValid( hintMask ) )
{
/* without a hint mask, assume all hints are active */
cf2_hintmask_setAll( hintMask,
cf2_arrstack_size( hStemHintArray ) +
cf2_arrstack_size( vStemHintArray ) );
if ( !cf2_hintmask_isValid( hintMask ) )
return; /* too many stem hints */
}
/* begin by clearing the map */
hintmap->count = 0;
hintmap->lastIndex = 0;
/* make a copy of the hint mask so we can modify it */
tempHintMask = *hintMask;
maskPtr = cf2_hintmask_getMaskPtr( &tempHintMask );
/* use the hStem hints only, which are first in the mask */
/* TODO: compare this to cffhintmaskGetBitCount */
bitCount = cf2_arrstack_size( hStemHintArray );
/* synthetic embox hints get highest priority */
if ( font->blues.doEmBoxHints )
{
cf2_hint_initZero( &dummy ); /* invalid hint map element */
/* ghost bottom */
cf2_hintmap_insertHint( hintmap,
&font->blues.emBoxBottomEdge,
&dummy );
/* ghost top */
cf2_hintmap_insertHint( hintmap,
&dummy,
&font->blues.emBoxTopEdge );
}
/* insert hints captured by a blue zone or already locked (higher */
/* priority) */
for ( i = 0, maskByte = 0x80; i < bitCount; i++ )
{
if ( maskByte & *maskPtr )
{
/* expand StemHint into two `CF2_Hint' elements */
CF2_HintRec bottomHintEdge, topHintEdge;
cf2_hint_init( &bottomHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
TRUE /* bottom */ );
cf2_hint_init( &topHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
FALSE /* top */ );
if ( cf2_hint_isLocked( &bottomHintEdge ) ||
cf2_hint_isLocked( &topHintEdge ) ||
cf2_blues_capture( &font->blues,
&bottomHintEdge,
&topHintEdge ) )
{
/* insert captured hint into map */
cf2_hintmap_insertHint( hintmap, &bottomHintEdge, &topHintEdge );
*maskPtr &= ~maskByte; /* turn off the bit for this hint */
}
}
if ( ( i & 7 ) == 7 )
{
/* move to next mask byte */
maskPtr++;
maskByte = 0x80;
}
else
maskByte >>= 1;
}
/* initial hint map includes only captured hints plus maybe one at 0 */
/*
* TODO: There is a problem here because we are trying to build a
* single hint map containing all captured hints. It is
* possible for there to be conflicts between captured hints,
* either because of darkening or because the hints are in
* separate hint zones (we are ignoring hint zones for the
* initial map). An example of the latter is MinionPro-Regular
* v2.030 glyph 883 (Greek Capital Alpha with Psili) at 15ppem.
* A stem hint for the psili conflicts with the top edge hint
* for the base character. The stem hint gets priority because
* of its sort order. In glyph 884 (Greek Capital Alpha with
* Psili and Oxia), the top of the base character gets a stem
* hint, and the psili does not. This creates different initial
* maps for the two glyphs resulting in different renderings of
* the base character. Will probably defer this either as not
* worth the cost or as a font bug. I don't think there is any
* good reason for an accent to be captured by an alignment
* zone. -darnold 2/12/10
*/
if ( initialMap )
{
/* Apply a heuristic that inserts a point for (0,0), unless it's */
/* already covered by a mapping. This locks the baseline for glyphs */
/* that have no baseline hints. */
if ( hintmap->count == 0 ||
hintmap->edge[0].csCoord > 0 ||
hintmap->edge[hintmap->count - 1].csCoord < 0 )
{
/* all edges are above 0 or all edges are below 0; */
/* construct a locked edge hint at 0 */
CF2_HintRec edge, invalid;
cf2_hint_initZero( &edge );
edge.flags = CF2_GhostBottom |
CF2_Locked |
CF2_Synthetic;
edge.scale = hintmap->scale;
cf2_hint_initZero( &invalid );
cf2_hintmap_insertHint( hintmap, &edge, &invalid );
}
}
else
{
/* insert remaining hints */
maskPtr = cf2_hintmask_getMaskPtr( &tempHintMask );
for ( i = 0, maskByte = 0x80; i < bitCount; i++ )
{
if ( maskByte & *maskPtr )
{
CF2_HintRec bottomHintEdge, topHintEdge;
cf2_hint_init( &bottomHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
TRUE /* bottom */ );
cf2_hint_init( &topHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
FALSE /* top */ );
cf2_hintmap_insertHint( hintmap, &bottomHintEdge, &topHintEdge );
}
if ( ( i & 7 ) == 7 )
{
/* move to next mask byte */
maskPtr++;
maskByte = 0x80;
}
else
maskByte >>= 1;
}
}
/*
* Note: The following line is a convenient place to break when
* debugging hinting. Examine `hintmap->edge' for the list of
* enabled hints, then step over the call to see the effect of
* adjustment. We stop here first on the recursive call that
* creates the initial map, and then on each counter group and
* hint zone.
*/
/* adjust positions of hint edges that are not locked to blue zones */
cf2_hintmap_adjustHints( hintmap );
/* save the position of all hints that were used in this hint map; */
/* if we use them again, we'll locate them in the same position */
if ( !initialMap )
{
for ( i = 0; i < hintmap->count; i++ )
{
if ( !cf2_hint_isSynthetic( &hintmap->edge[i] ) )
{
/* Note: include both valid and invalid edges */
/* Note: top and bottom edges are copied back separately */
CF2_StemHint stemhint = (CF2_StemHint)
cf2_arrstack_getPointer( hStemHintArray,
hintmap->edge[i].index );
if ( cf2_hint_isTop( &hintmap->edge[i] ) )
stemhint->maxDS = hintmap->edge[i].dsCoord;
else
stemhint->minDS = hintmap->edge[i].dsCoord;
stemhint->used = TRUE;
}
}
}
/* hint map is ready to use */
hintmap->isValid = TRUE;
/* remember this mask has been used */
cf2_hintmask_setNew( hintMask, FALSE );
}
| 1 | CVE-2014-9659 | 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,294 |
samba | 538d305de91e34a2938f5f219f18bf0e1918763f | struct smb_iconv_handle *get_iconv_testing_handle(TALLOC_CTX *mem_ctx,
const char *dos_charset,
const char *unix_charset,
bool use_builtin_handlers)
{
return smb_iconv_handle_reinit(mem_ctx,
dos_charset, unix_charset, use_builtin_handlers, NULL);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,914 |
libjpeg | 4746b577931e926a49e50de9720a4946de3069a7 | bool SingleComponentLSScan::ParseMCU(void)
{
#if ACCUSOFT_CODE
int lines = m_ulRemaining[0]; // total number of MCU lines processed.
UBYTE preshift = m_ucLowBit + FractionalColorBitsOf();
struct Line *line = CurrentLine(0);
//
// If a DNL marker is present, the number of remaining lines is zero. Fix it.
if (m_pFrame->HeightOf() == 0) {
assert(lines == 0);
lines = 8;
}
assert(m_ucCount == 1);
//
// A "MCU" in respect to the code organization is eight lines.
if (lines > 8) {
lines = 8;
}
if (m_pFrame->HeightOf() > 0)
m_ulRemaining[0] -= lines;
if (lines == 0)
return false;
// Loop over lines and columns
do {
LONG length = m_ulWidth[0];
LONG *lp = line->m_pData;
#ifdef DEBUG_LS
int xpos = 0;
static int linenumber = 0;
printf("\n%4d : ",++linenumber);
#endif
StartLine(0);
if (BeginReadMCU(m_Stream.ByteStreamOf())) { // No error handling strategy. No RST in scans. Bummer!
do {
LONG a,b,c,d; // neighbouring values.
LONG d1,d2,d3; // local gradients.
GetContext(0,a,b,c,d);
d1 = d - b; // compute local gradients
d2 = b - c;
d3 = c - a;
if (isRunMode(d1,d2,d3)) {
LONG run = DecodeRun(length,m_lRunIndex[0]);
//
// Now fill the data.
while(run) {
// Update so that the next process gets the correct value.
UpdateContext(0,a);
// And insert the value into the target line as well.
*lp++ = a << preshift;
#ifdef DEBUG_LS
printf("%4d:<%2x> ",xpos++,a);
#endif
run--,length--;
// As long as there are pixels on the line.
}
//
// More data on the line? I.e. the run did not cover the full m_lJ samples?
// Now decode the run interruption sample.
if (length) {
bool negative; // the sign variable
bool rtype; // run interruption type
LONG errval; // the prediction error
LONG merr; // the mapped error (symbol)
LONG rx; // the reconstructed value
UBYTE k; // golomb parameter
// Get the neighbourhood.
GetContext(0,a,b,c,d);
// Get the prediction mode.
rtype = InterruptedPredictionMode(negative,a,b);
// Get the golomb parameter for run interruption coding.
k = GolombParameter(rtype);
// Golomb-decode the error symbol.
merr = GolombDecode(k,m_lLimit - m_lJ[m_lRunIndex[0]] - 1);
// Inverse the error mapping procedure.
errval = InverseErrorMapping(merr + rtype,ErrorMappingOffset(rtype,rtype || merr,k));
// Compute the reconstructed value.
rx = Reconstruct(negative,rtype?a:b,errval);
// Update so that the next process gets the correct value.
UpdateContext(0,rx);
// Fill in the value into the line
*lp = rx << preshift;
#ifdef DEBUG_LS
printf("%4d:<%2x> ",xpos++,*lp);
#endif
// Update the variables of the run mode.
UpdateState(rtype,errval);
// Update the run index now. This is not part of
// EncodeRun because the non-reduced run-index is
// required for the golomb coder length limit.
if (m_lRunIndex[0] > 0)
m_lRunIndex[0]--;
} else break; // end of line.
} else {
UWORD ctxt;
bool negative; // the sign variable.
LONG px; // the predicted variable.
LONG rx; // the reconstructed value.
LONG errval; // the error value.
LONG merr; // the mapped error value.
UBYTE k; // the Golomb parameter.
// Quantize the gradients.
d1 = QuantizedGradient(d1);
d2 = QuantizedGradient(d2);
d3 = QuantizedGradient(d3);
// Compute the context.
ctxt = Context(negative,d1,d2,d3);
// Compute the predicted value.
px = Predict(a,b,c);
// Correct the prediction.
px = CorrectPrediction(ctxt,negative,px);
// Compute the golomb parameter k from the context.
k = GolombParameter(ctxt);
// Decode the error symbol.
merr = GolombDecode(k,m_lLimit);
// Inverse the error symbol into an error value.
errval = InverseErrorMapping(merr,ErrorMappingOffset(ctxt,k));
// Update the variables.
UpdateState(ctxt,errval);
// Compute the reconstructed value.
rx = Reconstruct(negative,px,errval);
// Update so that the next process gets the correct value.
UpdateContext(0,rx);
// And insert the value into the target line as well.
*lp = rx << preshift;
#ifdef DEBUG_LS
printf("%4d:<%2x> ",xpos++,*lp);
#endif
}
} while(++lp,--length);
} // No error handling here.
EndLine(0);
line = line->m_pNext;
} while(--lines);
//
// If this is the last line, gobble up all the
// bits from bitstuffing the last byte may have left.
// As SkipStuffing is idempotent, we can also do that
// all the time.
m_Stream.SkipStuffing();
#endif
return false;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,492 |
zstd | 3e5cdf1b6a85843e991d7d10f6a2567c15580da0 | ZSTD_buildCTable(void* dst, size_t dstCapacity,
FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type,
U32* count, U32 max,
const BYTE* codeTable, size_t nbSeq,
const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax,
const FSE_CTable* prevCTable, size_t prevCTableSize,
void* workspace, size_t workspaceSize)
{
BYTE* op = (BYTE*)dst;
const BYTE* const oend = op + dstCapacity;
switch (type) {
case set_rle:
*op = codeTable[0];
CHECK_F(FSE_buildCTable_rle(nextCTable, (BYTE)max));
return 1;
case set_repeat:
memcpy(nextCTable, prevCTable, prevCTableSize);
return 0;
case set_basic:
CHECK_F(FSE_buildCTable_wksp(nextCTable, defaultNorm, defaultMax, defaultNormLog, workspace, workspaceSize)); /* note : could be pre-calculated */
return 0;
case set_compressed: {
S16 norm[MaxSeq + 1];
size_t nbSeq_1 = nbSeq;
const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);
if (count[codeTable[nbSeq-1]] > 1) {
count[codeTable[nbSeq-1]]--;
nbSeq_1--;
}
assert(nbSeq_1 > 1);
CHECK_F(FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max));
{ size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */
if (FSE_isError(NCountSize)) return NCountSize;
CHECK_F(FSE_buildCTable_wksp(nextCTable, norm, max, tableLog, workspace, workspaceSize));
return NCountSize;
}
}
default: return assert(0), ERROR(GENERIC);
}
}
| 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 | 1,780 |
linux | b799207e1e1816b09e7a5920fbb2d5fcf6edd681 | static void mark_reg_unknown(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs except FP */
for (regno = 0; regno < BPF_REG_FP; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_unknown(regs + regno);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,899 |
php-src | e617f03066ce81d26f56c06d6bd7787c7de08703 | PHP_FUNCTION(mb_split)
{
char *arg_pattern;
size_t arg_pattern_len;
php_mb_regex_t *re;
OnigRegion *regs = NULL;
char *string;
OnigUChar *pos, *chunk_pos;
size_t string_len;
int err;
size_t n;
zend_long count = -1;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|l", &arg_pattern, &arg_pattern_len, &string, &string_len, &count) == FAILURE) {
RETURN_FALSE;
}
if (count > 0) {
count--;
}
/* create regex pattern buffer */
if ((re = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, MBREX(regex_default_options), MBREX(current_mbctype), MBREX(regex_default_syntax))) == NULL) {
RETURN_FALSE;
}
array_init(return_value);
chunk_pos = pos = (OnigUChar *)string;
err = 0;
regs = onig_region_new();
/* churn through str, generating array entries as we go */
while (count != 0 && (size_t)(pos - (OnigUChar *)string) < string_len) {
size_t beg, end;
err = onig_search(re, (OnigUChar *)string, (OnigUChar *)(string + string_len), pos, (OnigUChar *)(string + string_len), regs, 0);
if (err < 0) {
break;
}
beg = regs->beg[0], end = regs->end[0];
/* add it to the array */
if ((size_t)(pos - (OnigUChar *)string) < end) {
if (beg < string_len && beg >= (size_t)(chunk_pos - (OnigUChar *)string)) {
add_next_index_stringl(return_value, (char *)chunk_pos, ((OnigUChar *)(string + beg) - chunk_pos));
--count;
} else {
err = -2;
break;
}
/* point at our new starting point */
chunk_pos = pos = (OnigUChar *)string + end;
} else {
pos++;
}
onig_region_free(regs, 0);
}
onig_region_free(regs, 1);
/* see if we encountered an error */
if (err <= -2) {
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
onig_error_code_to_str(err_str, err);
php_error_docref(NULL, E_WARNING, "mbregex search failure in mbsplit(): %s", err_str);
zend_array_destroy(Z_ARR_P(return_value));
RETURN_FALSE;
}
/* otherwise we just have one last element to add to the array */
n = ((OnigUChar *)(string + string_len) - chunk_pos);
if (n > 0) {
add_next_index_stringl(return_value, (char *)chunk_pos, n);
} else {
add_next_index_stringl(return_value, "", 0);
}
} | 1 | CVE-2019-9025 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 5,811 |
tensorflow | e6a7c7cc18c3aaad1ae0872cb0a959f5c923d2bd | explicit CSRSparseCholeskyCPUOp(OpKernelConstruction* c) : OpKernel(c) {} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,668 |
linux | 8f659a03a0ba9289b9aeb9b4470e6fb263d6f483 | static int raw_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct inet_sock *inet = inet_sk(sk);
struct net *net = sock_net(sk);
struct ipcm_cookie ipc;
struct rtable *rt = NULL;
struct flowi4 fl4;
int free = 0;
__be32 daddr;
__be32 saddr;
u8 tos;
int err;
struct ip_options_data opt_copy;
struct raw_frag_vec rfv;
err = -EMSGSIZE;
if (len > 0xFFFF)
goto out;
/*
* Check the flags.
*/
err = -EOPNOTSUPP;
if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message */
goto out; /* compatibility */
/*
* Get and verify the address.
*/
if (msg->msg_namelen) {
DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
err = -EINVAL;
if (msg->msg_namelen < sizeof(*usin))
goto out;
if (usin->sin_family != AF_INET) {
pr_info_once("%s: %s forgot to set AF_INET. Fix it!\n",
__func__, current->comm);
err = -EAFNOSUPPORT;
if (usin->sin_family)
goto out;
}
daddr = usin->sin_addr.s_addr;
/* ANK: I did not forget to get protocol from port field.
* I just do not know, who uses this weirdness.
* IP_HDRINCL is much more convenient.
*/
} else {
err = -EDESTADDRREQ;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
daddr = inet->inet_daddr;
}
ipc.sockc.tsflags = sk->sk_tsflags;
ipc.addr = inet->inet_saddr;
ipc.opt = NULL;
ipc.tx_flags = 0;
ipc.ttl = 0;
ipc.tos = -1;
ipc.oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
err = ip_cmsg_send(sk, msg, &ipc, false);
if (unlikely(err)) {
kfree(ipc.opt);
goto out;
}
if (ipc.opt)
free = 1;
}
saddr = ipc.addr;
ipc.addr = daddr;
if (!ipc.opt) {
struct ip_options_rcu *inet_opt;
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt) {
memcpy(&opt_copy, inet_opt,
sizeof(*inet_opt) + inet_opt->opt.optlen);
ipc.opt = &opt_copy.opt;
}
rcu_read_unlock();
}
if (ipc.opt) {
err = -EINVAL;
/* Linux does not mangle headers on raw sockets,
* so that IP options + IP_HDRINCL is non-sense.
*/
if (inet->hdrincl)
goto done;
if (ipc.opt->opt.srr) {
if (!daddr)
goto done;
daddr = ipc.opt->opt.faddr;
}
}
tos = get_rtconn_flags(&ipc, sk);
if (msg->msg_flags & MSG_DONTROUTE)
tos |= RTO_ONLINK;
if (ipv4_is_multicast(daddr)) {
if (!ipc.oif)
ipc.oif = inet->mc_index;
if (!saddr)
saddr = inet->mc_addr;
} else if (!ipc.oif)
ipc.oif = inet->uc_index;
flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos,
RT_SCOPE_UNIVERSE,
inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol,
inet_sk_flowi_flags(sk) |
(inet->hdrincl ? FLOWI_FLAG_KNOWN_NH : 0),
daddr, saddr, 0, 0, sk->sk_uid);
if (!inet->hdrincl) {
rfv.msg = msg;
rfv.hlen = 0;
err = raw_probe_proto_opt(&rfv, &fl4);
if (err)
goto done;
}
security_sk_classify_flow(sk, flowi4_to_flowi(&fl4));
rt = ip_route_output_flow(net, &fl4, sk);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
rt = NULL;
goto done;
}
err = -EACCES;
if (rt->rt_flags & RTCF_BROADCAST && !sock_flag(sk, SOCK_BROADCAST))
goto done;
if (msg->msg_flags & MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (inet->hdrincl)
err = raw_send_hdrinc(sk, &fl4, msg, len,
&rt, msg->msg_flags, &ipc.sockc);
else {
sock_tx_timestamp(sk, ipc.sockc.tsflags, &ipc.tx_flags);
if (!ipc.addr)
ipc.addr = fl4.daddr;
lock_sock(sk);
err = ip_append_data(sk, &fl4, raw_getfrag,
&rfv, len, 0,
&ipc, &rt, msg->msg_flags);
if (err)
ip_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE)) {
err = ip_push_pending_frames(sk, &fl4);
if (err == -ENOBUFS && !inet->recverr)
err = 0;
}
release_sock(sk);
}
done:
if (free)
kfree(ipc.opt);
ip_rt_put(rt);
out:
if (err < 0)
return err;
return len;
do_confirm:
if (msg->msg_flags & MSG_PROBE)
dst_confirm_neigh(&rt->dst, &fl4.daddr);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
| 1 | CVE-2017-17712 | 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,019 |
gpac | 71460d72ec07df766dab0a4d52687529f3efcf0a | static const char *isoffin_probe_data(const u8 *data, u32 size, GF_FilterProbeScore *score)
{
if (gf_isom_probe_data(data, size)) {
*score = GF_FPROBE_SUPPORTED;
return "video/mp4";
}
return NULL;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,035 |
php-src | 0da8b8b801f9276359262f1ef8274c7812d3dfda?w=1 | PHPAPI char *php_escape_html_entities_ex(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset, zend_bool double_encode TSRMLS_DC)
{
size_t cursor, maxlen, len;
char *replaced;
enum entity_charset charset = determine_charset(hint_charset TSRMLS_CC);
int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
entity_table_opt entity_table;
const enc_to_uni *to_uni_table = NULL;
const entity_ht *inv_map = NULL; /* used for !double_encode */
/* only used if flags includes ENT_HTML_IGNORE_ERRORS or ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS */
const unsigned char *replacement = NULL;
size_t replacement_len = 0;
if (all) { /* replace with all named entities */
if (CHARSET_PARTIAL_SUPPORT(charset)) {
php_error_docref0(NULL TSRMLS_CC, E_STRICT, "Only basic entities "
"substitution is supported for multi-byte encodings other than UTF-8; "
"functionality is equivalent to htmlspecialchars");
}
LIMIT_ALL(all, doctype, charset);
}
entity_table = determine_entity_table(all, doctype);
if (all && !CHARSET_UNICODE_COMPAT(charset)) {
to_uni_table = enc_to_uni_index[charset];
}
if (!double_encode) {
/* first arg is 1 because we want to identify valid named entities
* even if we are only encoding the basic ones */
inv_map = unescape_inverse_map(1, flags);
}
if (flags & (ENT_HTML_SUBSTITUTE_ERRORS | ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS)) {
if (charset == cs_utf_8) {
replacement = (const unsigned char*)"\xEF\xBF\xBD";
replacement_len = sizeof("\xEF\xBF\xBD") - 1;
} else {
replacement = (const unsigned char*)"�";
replacement_len = sizeof("�") - 1;
}
}
/* initial estimate */
if (oldlen < 64) {
maxlen = 128;
} else {
maxlen = 2 * oldlen;
if (maxlen < oldlen) {
zend_error_noreturn(E_ERROR, "Input string is too long");
return NULL;
}
}
replaced = emalloc(maxlen + 1); /* adding 1 is safe: maxlen is even */
len = 0;
cursor = 0;
while (cursor < oldlen) {
const unsigned char *mbsequence = NULL;
size_t mbseqlen = 0,
cursor_before = cursor;
int status = SUCCESS;
unsigned int this_char = get_next_char(charset, old, oldlen, &cursor, &status);
/* guarantee we have at least 40 bytes to write.
* In HTML5, entities may take up to 33 bytes */
if (len > maxlen - 40) { /* maxlen can never be smaller than 128 */
replaced = safe_erealloc(replaced, maxlen , 1, 128 + 1);
maxlen += 128;
}
if (status == FAILURE) {
/* invalid MB sequence */
if (flags & ENT_HTML_IGNORE_ERRORS) {
continue;
} else if (flags & ENT_HTML_SUBSTITUTE_ERRORS) {
memcpy(&replaced[len], replacement, replacement_len);
len += replacement_len;
continue;
} else {
efree(replaced);
*newlen = 0;
return STR_EMPTY_ALLOC();
}
} else { /* SUCCESS */
mbsequence = &old[cursor_before];
mbseqlen = cursor - cursor_before;
}
if (this_char != '&') { /* no entity on this position */
const unsigned char *rep = NULL;
size_t rep_len = 0;
if (((this_char == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(this_char == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
goto pass_char_through;
if (all) { /* false that CHARSET_PARTIAL_SUPPORT(charset) */
if (to_uni_table != NULL) {
/* !CHARSET_UNICODE_COMPAT therefore not UTF-8; since UTF-8
* is the only multibyte encoding with !CHARSET_PARTIAL_SUPPORT,
* we're using a single byte encoding */
map_to_unicode(this_char, to_uni_table, &this_char);
if (this_char == 0xFFFF) /* no mapping; pass through */
goto pass_char_through;
}
/* the cursor may advance */
find_entity_for_char(this_char, charset, entity_table.ms_table, &rep,
&rep_len, old, oldlen, &cursor);
} else {
find_entity_for_char_basic(this_char, entity_table.table, &rep, &rep_len);
}
if (rep != NULL) {
replaced[len++] = '&';
memcpy(&replaced[len], rep, rep_len);
len += rep_len;
replaced[len++] = ';';
} else {
/* we did not find an entity for this char.
* check for its validity, if its valid pass it unchanged */
if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
if (CHARSET_UNICODE_COMPAT(charset)) {
if (!unicode_cp_is_allowed(this_char, doctype)) {
mbsequence = replacement;
mbseqlen = replacement_len;
}
} else if (to_uni_table) {
if (!all) /* otherwise we already did this */
map_to_unicode(this_char, to_uni_table, &this_char);
if (!unicode_cp_is_allowed(this_char, doctype)) {
mbsequence = replacement;
mbseqlen = replacement_len;
}
} else {
/* not a unicode code point, unless, coincidentally, it's in
* the 0x20..0x7D range (except 0x5C in sjis). We know nothing
* about other code points, because we have no tables. Since
* Unicode code points in that range are not disallowed in any
* document type, we could do nothing. However, conversion
* tables frequently map 0x00-0x1F to the respective C0 code
* points. Let's play it safe and admit that's the case */
if (this_char <= 0x7D &&
!unicode_cp_is_allowed(this_char, doctype)) {
mbsequence = replacement;
mbseqlen = replacement_len;
}
}
}
pass_char_through:
if (mbseqlen > 1) {
memcpy(replaced + len, mbsequence, mbseqlen);
len += mbseqlen;
} else {
replaced[len++] = mbsequence[0];
}
}
} else { /* this_char == '&' */
if (double_encode) {
encode_amp:
memcpy(&replaced[len], "&", sizeof("&") - 1);
len += sizeof("&") - 1;
} else { /* no double encode */
/* check if entity is valid */
size_t ent_len; /* not counting & or ; */
/* peek at next char */
if (old[cursor] == '#') { /* numeric entity */
unsigned code_point;
int valid;
char *pos = (char*)&old[cursor+1];
valid = process_numeric_entity((const char **)&pos, &code_point);
if (valid == FAILURE)
goto encode_amp;
if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
if (!numeric_entity_is_allowed(code_point, doctype))
goto encode_amp;
}
ent_len = pos - (char*)&old[cursor];
} else { /* named entity */
/* check for vality of named entity */
const char *start = &old[cursor],
*next = start;
unsigned dummy1, dummy2;
if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
goto encode_amp;
if (resolve_named_entity_html(start, ent_len, inv_map, &dummy1, &dummy2) == FAILURE) {
if (!(doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
&& start[1] == 'p' && start[2] == 'o' && start[3] == 's')) {
/* uses html4 inv_map, which doesn't include apos;. This is a
* hack to support it */
goto encode_amp;
}
}
}
/* checks passed; copy entity to result */
/* entity size is unbounded, we may need more memory */
/* at this point maxlen - len >= 40 */
if (maxlen - len < ent_len + 2 /* & and ; */) {
/* ent_len < oldlen, which is certainly <= SIZE_MAX/2 */
replaced = safe_erealloc(replaced, maxlen, 1, ent_len + 128 + 1);
maxlen += ent_len + 128;
}
replaced[len++] = '&';
memcpy(&replaced[len], &old[cursor], ent_len);
len += ent_len;
replaced[len++] = ';';
cursor += ent_len + 1;
}
}
}
replaced[len] = '\0';
*newlen = len;
return replaced;
}
| 1 | CVE-2016-5094 | 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. | 7,422 |
php-src | b2af4e8868726a040234de113436c6e4f6372d17 | PHP_FUNCTION(serialize)
{
zval *struc;
php_serialize_data_t var_hash;
smart_str buf = {0};
if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &struc) == FAILURE) {
return;
}
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, struc, &var_hash);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
if (EG(exception)) {
smart_str_free(&buf);
RETURN_FALSE;
}
if (buf.s) {
RETURN_NEW_STR(buf.s);
} else {
RETURN_NULL();
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,166 |
linux | 6402939ec86eaf226c8b8ae00ed983936b164908 | static int ca8210_reset_init(struct spi_device *spi)
{
int ret;
struct ca8210_platform_data *pdata = spi->dev.platform_data;
pdata->gpio_reset = of_get_named_gpio(
spi->dev.of_node,
"reset-gpio",
0
);
ret = gpio_direction_output(pdata->gpio_reset, 1);
if (ret < 0) {
dev_crit(
&spi->dev,
"Reset GPIO %d did not set to output mode\n",
pdata->gpio_reset
);
}
return ret;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,099 |
linux | 9955ac47f4ba1c95ecb6092aeaefb40a22e99268 | void __init trap_init(void)
{
return;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,144 |
Chrome | 5d0e9f824e05523e03dabc0e341b9f8f17a72bb0 | bool CSPSourceList::matches(const KURL& url, ContentSecurityPolicy::RedirectStatus redirectStatus) const
{
if (m_allowStar)
return true;
KURL effectiveURL = m_policy->selfMatchesInnerURL() && SecurityOrigin::shouldUseInnerURL(url) ? SecurityOrigin::extractInnerURL(url) : url;
if (m_allowSelf && m_policy->urlMatchesSelf(effectiveURL))
return true;
for (size_t i = 0; i < m_list.size(); ++i) {
if (m_list[i].matches(effectiveURL, redirectStatus))
return true;
}
return false;
}
| 1 | CVE-2015-6786 | 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 | 586 |
libheif | 995a4283d8ed2d0d2c1ceb1a577b993df2f0e014 | Error HeifContext::interpret_heif_file()
{
m_all_images.clear();
m_top_level_images.clear();
m_primary_image.reset();
// --- reference all non-hidden images
std::vector<heif_item_id> image_IDs = m_heif_file->get_item_IDs();
bool primary_is_grid = false;
for (heif_item_id id : image_IDs) {
auto infe_box = m_heif_file->get_infe_box(id);
if (!infe_box) {
// TODO(farindk): Should we return an error instead of skipping the invalid id?
continue;
}
if (item_type_is_image(infe_box->get_item_type())) {
auto image = std::make_shared<Image>(this, id);
m_all_images.insert(std::make_pair(id, image));
if (!infe_box->is_hidden_item()) {
if (id==m_heif_file->get_primary_image_ID()) {
image->set_primary(true);
m_primary_image = image;
primary_is_grid = infe_box->get_item_type() == "grid";
}
m_top_level_images.push_back(image);
}
}
}
if (!m_primary_image) {
return Error(heif_error_Invalid_input,
heif_suberror_Nonexisting_item_referenced,
"'pitm' box references a non-existing image");
}
// --- remove thumbnails from top-level images and assign to their respective image
auto iref_box = m_heif_file->get_iref_box();
if (iref_box) {
// m_top_level_images.clear();
for (auto& pair : m_all_images) {
auto& image = pair.second;
std::vector<Box_iref::Reference> references = iref_box->get_references_from(image->get_id());
for (const Box_iref::Reference& ref : references) {
uint32_t type = ref.header.get_short_type();
if (type==fourcc("thmb")) {
// --- this is a thumbnail image, attach to the main image
std::vector<heif_item_id> refs = ref.to_item_ID;
if (refs.size() != 1) {
return Error(heif_error_Invalid_input,
heif_suberror_Unspecified,
"Too many thumbnail references");
}
image->set_is_thumbnail_of(refs[0]);
auto master_iter = m_all_images.find(refs[0]);
if (master_iter == m_all_images.end()) {
return Error(heif_error_Invalid_input,
heif_suberror_Nonexisting_item_referenced,
"Thumbnail references a non-existing image");
}
if (master_iter->second->is_thumbnail()) {
return Error(heif_error_Invalid_input,
heif_suberror_Nonexisting_item_referenced,
"Thumbnail references another thumbnail");
}
if (image.get() == master_iter->second.get()) {
return Error(heif_error_Invalid_input,
heif_suberror_Nonexisting_item_referenced,
"Recursive thumbnail image detected");
}
master_iter->second->add_thumbnail(image);
remove_top_level_image(image);
}
else if (type==fourcc("auxl")) {
// --- this is an auxiliary image
// check whether it is an alpha channel and attach to the main image if yes
std::vector<Box_ipco::Property> properties;
Error err = m_heif_file->get_properties(image->get_id(), properties);
if (err) {
return err;
}
std::shared_ptr<Box_auxC> auxC_property;
for (const auto& property : properties) {
auto auxC = std::dynamic_pointer_cast<Box_auxC>(property.property);
if (auxC) {
auxC_property = auxC;
}
}
if (!auxC_property) {
std::stringstream sstr;
sstr << "No auxC property for image " << image->get_id();
return Error(heif_error_Invalid_input,
heif_suberror_Auxiliary_image_type_unspecified,
sstr.str());
}
std::vector<heif_item_id> refs = ref.to_item_ID;
if (refs.size() != 1) {
return Error(heif_error_Invalid_input,
heif_suberror_Unspecified,
"Too many auxiliary image references");
}
// alpha channel
if (auxC_property->get_aux_type() == "urn:mpeg:avc:2015:auxid:1" ||
auxC_property->get_aux_type() == "urn:mpeg:hevc:2015:auxid:1") {
image->set_is_alpha_channel_of(refs[0]);
auto master_iter = m_all_images.find(refs[0]);
if (image.get() == master_iter->second.get()) {
return Error(heif_error_Invalid_input,
heif_suberror_Nonexisting_item_referenced,
"Recursive alpha image detected");
}
master_iter->second->set_alpha_channel(image);
}
// depth channel
if (auxC_property->get_aux_type() == "urn:mpeg:hevc:2015:auxid:2") {
image->set_is_depth_channel_of(refs[0]);
auto master_iter = m_all_images.find(refs[0]);
if (image.get() == master_iter->second.get()) {
return Error(heif_error_Invalid_input,
heif_suberror_Nonexisting_item_referenced,
"Recursive depth image detected");
}
master_iter->second->set_depth_channel(image);
auto subtypes = auxC_property->get_subtypes();
std::vector<std::shared_ptr<SEIMessage>> sei_messages;
Error err = decode_hevc_aux_sei_messages(subtypes, sei_messages);
for (auto& msg : sei_messages) {
auto depth_msg = std::dynamic_pointer_cast<SEIMessage_depth_representation_info>(msg);
if (depth_msg) {
image->set_depth_representation_info(*depth_msg);
}
}
}
remove_top_level_image(image);
}
else {
// 'image' is a normal image, keep it as a top-level image
}
}
}
}
// --- check that HEVC images have an hvcC property
for (auto& pair : m_all_images) {
auto& image = pair.second;
std::shared_ptr<Box_infe> infe = m_heif_file->get_infe_box(image->get_id());
if (infe->get_item_type() == "hvc1") {
auto ipma = m_heif_file->get_ipma_box();
auto ipco = m_heif_file->get_ipco_box();
if (!ipco->get_property_for_item_ID(image->get_id(), ipma, fourcc("hvcC"))) {
return Error(heif_error_Invalid_input,
heif_suberror_No_hvcC_box,
"No hvcC property in hvc1 type image");
}
}
}
// --- read through properties for each image and extract image resolutions
for (auto& pair : m_all_images) {
auto& image = pair.second;
std::vector<Box_ipco::Property> properties;
Error err = m_heif_file->get_properties(pair.first, properties);
if (err) {
return err;
}
bool ispe_read = false;
bool primary_colr_set = false;
for (const auto& prop : properties) {
auto ispe = std::dynamic_pointer_cast<Box_ispe>(prop.property);
if (ispe) {
uint32_t width = ispe->get_width();
uint32_t height = ispe->get_height();
// --- check whether the image size is "too large"
if (width >= static_cast<uint32_t>(MAX_IMAGE_WIDTH) ||
height >= static_cast<uint32_t>(MAX_IMAGE_HEIGHT)) {
std::stringstream sstr;
sstr << "Image size " << width << "x" << height << " exceeds the maximum image size "
<< MAX_IMAGE_WIDTH << "x" << MAX_IMAGE_HEIGHT << "\n";
return Error(heif_error_Memory_allocation_error,
heif_suberror_Security_limit_exceeded,
sstr.str());
}
image->set_resolution(width, height);
image->set_ispe_resolution(width, height);
ispe_read = true;
}
if (ispe_read) {
auto clap = std::dynamic_pointer_cast<Box_clap>(prop.property);
if (clap) {
image->set_resolution( clap->get_width_rounded(),
clap->get_height_rounded() );
}
auto irot = std::dynamic_pointer_cast<Box_irot>(prop.property);
if (irot) {
if (irot->get_rotation()==90 ||
irot->get_rotation()==270) {
// swap width and height
image->set_resolution( image->get_height(),
image->get_width() );
}
}
}
auto colr = std::dynamic_pointer_cast<Box_colr>(prop.property);
if (colr) {
auto profile = colr->get_color_profile();
image->set_color_profile(profile);
// if this is a grid item we assign the first one's color profile
// to the main image which is supposed to be a grid
// TODO: this condition is not correct. It would also classify a secondary image as a 'grid item'.
// We have to set the grid-image color profile in another way...
const bool is_grid_item = !image->is_primary() && !image->is_alpha_channel() && !image->is_depth_channel();
if (primary_is_grid &&
!primary_colr_set &&
is_grid_item) {
m_primary_image->set_color_profile(profile);
primary_colr_set = true;
}
}
}
}
// --- read metadata and assign to image
for (heif_item_id id : image_IDs) {
std::string item_type = m_heif_file->get_item_type(id);
std::string content_type = m_heif_file->get_content_type(id);
if (item_type == "Exif" ||
(item_type=="mime" && content_type=="application/rdf+xml")) {
std::shared_ptr<ImageMetadata> metadata = std::make_shared<ImageMetadata>();
metadata->item_id = id;
metadata->item_type = item_type;
metadata->content_type = content_type;
Error err = m_heif_file->get_compressed_image_data(id, &(metadata->m_data));
if (err) {
return err;
}
//std::cerr.write((const char*)data.data(), data.size());
// --- assign metadata to the image
if (iref_box) {
std::vector<Box_iref::Reference> references = iref_box->get_references_from(id);
for (const auto& ref : references) {
if (ref.header.get_short_type() == fourcc("cdsc")) {
std::vector<uint32_t> refs = ref.to_item_ID;
if (refs.size() != 1) {
return Error(heif_error_Invalid_input,
heif_suberror_Unspecified,
"Exif data not correctly assigned to image");
}
uint32_t exif_image_id = refs[0];
auto img_iter = m_all_images.find(exif_image_id);
if (img_iter == m_all_images.end()) {
return Error(heif_error_Invalid_input,
heif_suberror_Nonexisting_item_referenced,
"Exif data assigned to non-existing image");
}
img_iter->second->add_metadata(metadata);
}
}
}
}
}
return Error::Ok;
} | 1 | CVE-2019-11471 | 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. | 9,425 |
libxml2 | 0f3b843b3534784ef57a4f9b874238aa1fda5a73 | */
double
xmlXPathStringEvalNumber(const xmlChar *str) {
const xmlChar *cur = str;
double ret;
int ok = 0;
int isneg = 0;
int exponent = 0;
int is_exponent_negative = 0;
#ifdef __GNUC__
unsigned long tmp = 0;
double temp;
#endif
if (cur == NULL) return(0);
while (IS_BLANK_CH(*cur)) cur++;
if ((*cur != '.') && ((*cur < '0') || (*cur > '9')) && (*cur != '-')) {
return(xmlXPathNAN);
}
if (*cur == '-') {
isneg = 1;
cur++;
}
#ifdef __GNUC__
/*
* tmp/temp is a workaround against a gcc compiler bug
* http://veillard.com/gcc.bug
*/
ret = 0;
while ((*cur >= '0') && (*cur <= '9')) {
ret = ret * 10;
tmp = (*cur - '0');
ok = 1;
cur++;
temp = (double) tmp;
ret = ret + temp;
}
#else
ret = 0;
while ((*cur >= '0') && (*cur <= '9')) {
ret = ret * 10 + (*cur - '0');
ok = 1;
cur++;
}
#endif
if (*cur == '.') {
int v, frac = 0, max;
double fraction = 0;
cur++;
if (((*cur < '0') || (*cur > '9')) && (!ok)) {
return(xmlXPathNAN);
}
while (*cur == '0') {
frac = frac + 1;
cur++;
}
max = frac + MAX_FRAC;
while (((*cur >= '0') && (*cur <= '9')) && (frac < max)) {
v = (*cur - '0');
fraction = fraction * 10 + v;
frac = frac + 1;
cur++;
}
fraction /= pow(10.0, frac);
ret = ret + fraction;
while ((*cur >= '0') && (*cur <= '9'))
cur++;
}
if ((*cur == 'e') || (*cur == 'E')) {
cur++;
if (*cur == '-') {
is_exponent_negative = 1;
cur++;
} else if (*cur == '+') {
cur++;
}
while ((*cur >= '0') && (*cur <= '9')) {
if (exponent < 1000000)
exponent = exponent * 10 + (*cur - '0');
cur++;
}
}
while (IS_BLANK_CH(*cur)) cur++;
if (*cur != 0) return(xmlXPathNAN);
if (isneg) ret = -ret;
if (is_exponent_negative) exponent = -exponent;
ret *= pow(10.0, (double)exponent); | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,384 |
mysql-server | 4797ea0b772d5f4c5889bc552424132806f46e93 | */
static void mysql_prune_stmt_list(MYSQL *mysql)
{
LIST *element= mysql->stmts;
LIST *pruned_list= 0;
for (; element; element= element->next)
{
MYSQL_STMT *stmt= (MYSQL_STMT *) element->data;
if (stmt->state != MYSQL_STMT_INIT_DONE)
{
stmt->mysql= 0;
stmt->last_errno= CR_SERVER_LOST;
strmov(stmt->last_error, ER(CR_SERVER_LOST));
strmov(stmt->sqlstate, unknown_sqlstate);
}
else
{
pruned_list= list_add(pruned_list, element);
}
}
mysql->stmts= pruned_list; | 1 | CVE-2017-3302 | 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. | 9,871 |
freeradius-server | 78e5aed56c36a9231bc91ea5f55b3edf88a9d2a4 | static int cbtls_verify(int ok, X509_STORE_CTX *ctx)
{
char subject[1024]; /* Used for the subject name */
char issuer[1024]; /* Used for the issuer name */
char common_name[1024];
char cn_str[1024];
char buf[64];
EAP_HANDLER *handler = NULL;
X509 *client_cert;
X509 *issuer_cert;
SSL *ssl;
int err, depth, lookup, loc;
EAP_TLS_CONF *conf;
int my_ok = ok;
REQUEST *request;
ASN1_INTEGER *sn = NULL;
ASN1_TIME *asn_time = NULL;
#ifdef HAVE_OPENSSL_OCSP_H
X509_STORE *ocsp_store = NULL;
#endif
client_cert = X509_STORE_CTX_get_current_cert(ctx);
err = X509_STORE_CTX_get_error(ctx);
depth = X509_STORE_CTX_get_error_depth(ctx);
lookup = depth;
/*
* Log client/issuing cert. If there's an error, log
* issuing cert.
*/
if ((lookup > 1) && !my_ok) lookup = 1;
/*
* Retrieve the pointer to the SSL of the connection currently treated
* and the application specific data stored into the SSL object.
*/
ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
handler = (EAP_HANDLER *)SSL_get_ex_data(ssl, 0);
request = handler->request;
conf = (EAP_TLS_CONF *)SSL_get_ex_data(ssl, 1);
#ifdef HAVE_OPENSSL_OCSP_H
ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, 2);
#endif
/*
* Get the Serial Number
*/
buf[0] = '\0';
sn = X509_get_serialNumber(client_cert);
/*
* For this next bit, we create the attributes *only* if
* we're at the client or issuing certificate.
*/
if ((lookup <= 1) && sn && (sn->length < (sizeof(buf) / 2))) {
char *p = buf;
int i;
for (i = 0; i < sn->length; i++) {
sprintf(p, "%02x", (unsigned int)sn->data[i]);
p += 2;
}
pairadd(&handler->certs,
pairmake(cert_attr_names[EAPTLS_SERIAL][lookup], buf, T_OP_SET));
}
/*
* Get the Expiration Date
*/
buf[0] = '\0';
asn_time = X509_get_notAfter(client_cert);
if ((lookup <= 1) && asn_time && (asn_time->length < MAX_STRING_LEN)) {
memcpy(buf, (char*) asn_time->data, asn_time->length);
buf[asn_time->length] = '\0';
pairadd(&handler->certs,
pairmake(cert_attr_names[EAPTLS_EXPIRATION][lookup], buf, T_OP_SET));
}
/*
* Get the Subject & Issuer
*/
subject[0] = issuer[0] = '\0';
X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
sizeof(subject));
subject[sizeof(subject) - 1] = '\0';
if ((lookup <= 1) && subject[0] && (strlen(subject) < MAX_STRING_LEN)) {
pairadd(&handler->certs,
pairmake(cert_attr_names[EAPTLS_SUBJECT][lookup], subject, T_OP_SET));
}
X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
sizeof(issuer));
issuer[sizeof(issuer) - 1] = '\0';
if ((lookup <= 1) && issuer[0] && (strlen(issuer) < MAX_STRING_LEN)) {
pairadd(&handler->certs,
pairmake(cert_attr_names[EAPTLS_ISSUER][lookup], issuer, T_OP_SET));
}
/*
* Get the Common Name, if there is a subject.
*/
X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
NID_commonName, common_name, sizeof(common_name));
common_name[sizeof(common_name) - 1] = '\0';
if ((lookup <= 1) && common_name[0] && subject[0] && (strlen(common_name) < MAX_STRING_LEN)) {
pairadd(&handler->certs,
pairmake(cert_attr_names[EAPTLS_CN][lookup], common_name, T_OP_SET));
}
#ifdef GEN_EMAIL
/*
* Get the RFC822 Subject Alternative Name
*/
loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
if (lookup <= 1 && loc >= 0) {
X509_EXTENSION *ext = NULL;
GENERAL_NAMES *names = NULL;
int i;
if ((ext = X509_get_ext(client_cert, loc)) &&
(names = X509V3_EXT_d2i(ext))) {
for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
switch (name->type) {
case GEN_EMAIL:
if (ASN1_STRING_length(name->d.rfc822Name) >= MAX_STRING_LEN)
break;
pairadd(&handler->certs,
pairmake(cert_attr_names[EAPTLS_SAN_EMAIL][lookup],
ASN1_STRING_data(name->d.rfc822Name), T_OP_SET));
break;
default:
/* XXX TODO handle other SAN types */
break;
}
}
}
if (names != NULL)
sk_GENERAL_NAME_free(names);
}
#endif /* GEN_EMAIL */
/*
* If the CRL has expired, that might still be OK.
*/
if (!my_ok &&
(conf->allow_expired_crl) &&
(err == X509_V_ERR_CRL_HAS_EXPIRED)) {
my_ok = 1;
X509_STORE_CTX_set_error( ctx, 0 );
}
if (!my_ok) {
const char *p = X509_verify_cert_error_string(err);
radlog(L_ERR,"--> verify error:num=%d:%s\n",err, p);
radius_pairmake(request, &request->packet->vps,
"Module-Failure-Message", p, T_OP_SET);
return my_ok;
}
switch (ctx->error) {
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
radlog(L_ERR, "issuer= %s\n", issuer);
break;
case X509_V_ERR_CERT_NOT_YET_VALID:
case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
radlog(L_ERR, "notBefore=");
#if 0
ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
#endif
break;
case X509_V_ERR_CERT_HAS_EXPIRED:
case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
radlog(L_ERR, "notAfter=");
#if 0
ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
#endif
break;
}
/*
* If we're at the actual client cert, apply additional
* checks.
*/
if (depth == 0) {
/*
* If the conf tells us to, check cert issuer
* against the specified value and fail
* verification if they don't match.
*/
if (conf->check_cert_issuer &&
(strcmp(issuer, conf->check_cert_issuer) != 0)) {
radlog(L_AUTH, "rlm_eap_tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
my_ok = 0;
}
/*
* If the conf tells us to, check the CN in the
* cert against xlat'ed value, but only if the
* previous checks passed.
*/
if (my_ok && conf->check_cert_cn) {
if (!radius_xlat(cn_str, sizeof(cn_str), conf->check_cert_cn, handler->request, NULL)) {
radlog(L_ERR, "rlm_eap_tls (%s): xlat failed.",
conf->check_cert_cn);
/* if this fails, fail the verification */
my_ok = 0;
} else {
RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
if (strcmp(cn_str, common_name) != 0) {
radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
my_ok = 0;
}
}
} /* check_cert_cn */
#ifdef HAVE_OPENSSL_OCSP_H
if (my_ok && conf->ocsp_enable){
RDEBUG2("--> Starting OCSP Request");
if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
radlog(L_ERR, "Error: Couldn't get issuer_cert for %s", common_name);
}
my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
}
#endif
while (conf->verify_client_cert_cmd) {
char filename[256];
int fd;
FILE *fp;
snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
conf->verify_tmp_dir, progname);
fd = mkstemp(filename);
if (fd < 0) {
RDEBUG("Failed creating file in %s: %s",
conf->verify_tmp_dir, strerror(errno));
break;
}
fp = fdopen(fd, "w");
if (!fp) {
RDEBUG("Failed opening file %s: %s",
filename, strerror(errno));
break;
}
if (!PEM_write_X509(fp, client_cert)) {
fclose(fp);
RDEBUG("Failed writing certificate to file");
goto do_unlink;
}
fclose(fp);
if (!radius_pairmake(request, &request->packet->vps,
"TLS-Client-Cert-Filename",
filename, T_OP_SET)) {
RDEBUG("Failed creating TLS-Client-Cert-Filename");
goto do_unlink;
}
RDEBUG("Verifying client certificate: %s",
conf->verify_client_cert_cmd);
if (radius_exec_program(conf->verify_client_cert_cmd,
request, 1, NULL, 0,
request->packet->vps,
NULL, 1) != 0) {
radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) fails external verification!", common_name);
my_ok = 0;
} else {
RDEBUG("Client certificate CN %s passed external validation", common_name);
}
do_unlink:
unlink(filename);
break;
}
} /* depth == 0 */
if (debug_flag > 0) {
RDEBUG2("chain-depth=%d, ", depth);
RDEBUG2("error=%d", err);
RDEBUG2("--> User-Name = %s", handler->identity);
RDEBUG2("--> BUF-Name = %s", common_name);
RDEBUG2("--> subject = %s", subject);
RDEBUG2("--> issuer = %s", issuer);
RDEBUG2("--> verify return:%d", my_ok);
}
return my_ok;
} | 1 | CVE-2012-3547 | 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,381 |
Chrome | a64c3cf0ab6da24a9a010a45ebe4794422d40c71 | static std::string FixupHomedir(const std::string& text) {
DCHECK(text.length() > 0 && text[0] == '~');
if (text.length() == 1 || text[1] == '/') {
const char* home = getenv(base::env_vars::kHome);
if (URLFixerUpper::home_directory_override)
home = URLFixerUpper::home_directory_override;
if (!home)
return text;
return home + text.substr(1);
}
#if defined(OS_MACOSX)
static const char kHome[] = "/Users/";
#else
static const char kHome[] = "/home/";
#endif
return kHome + text.substr(1);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,886 |
jasper | 243749e5a6384acdb9f0a59515c0b85dfd62bd5b | jas_image_t *jas_image_create0()
{
jas_image_t *image;
if (!(image = jas_malloc(sizeof(jas_image_t)))) {
return 0;
}
image->tlx_ = 0;
image->tly_ = 0;
image->brx_ = 0;
image->bry_ = 0;
image->clrspc_ = JAS_CLRSPC_UNKNOWN;
image->numcmpts_ = 0;
image->maxcmpts_ = 0;
image->cmpts_ = 0;
// image->inmem_ = true;
image->cmprof_ = 0;
return image;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,135 |
node | 78b0e30954111cfaba0edbeee85450d8cbc6fdf6 | void Utf8DecoderBase::WriteUtf16Slow(const uint8_t* stream,
uint16_t* data,
unsigned data_length) {
while (data_length != 0) {
unsigned cursor = 0;
uint32_t character = Utf8::ValueOf(stream, Utf8::kMaxEncodedSize, &cursor);
// There's a total lack of bounds checking for stream
// as it was already done in Reset.
stream += cursor;
if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) {
*data++ = Utf16::LeadSurrogate(character);
*data++ = Utf16::TrailSurrogate(character);
DCHECK(data_length > 1);
data_length -= 2;
} else {
*data++ = character;
data_length -= 1;
}
}
} | 1 | CVE-2015-5380 | 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,793 |
flatpak | a9107feeb4b8275b78965b36bf21b92d5724699e | flatpak_run_add_dconf_args (FlatpakBwrap *bwrap,
const char *app_id,
GKeyFile *metakey,
GError **error)
{
g_auto(GStrv) paths = NULL;
g_autofree char *migrate_path = NULL;
g_autofree char *defaults = NULL;
g_autofree char *values = NULL;
g_autofree char *locks = NULL;
gsize defaults_size;
gsize values_size;
gsize locks_size;
if (metakey)
{
paths = g_key_file_get_string_list (metakey,
FLATPAK_METADATA_GROUP_DCONF,
FLATPAK_METADATA_KEY_DCONF_PATHS,
NULL, NULL);
migrate_path = g_key_file_get_string (metakey,
FLATPAK_METADATA_GROUP_DCONF,
FLATPAK_METADATA_KEY_DCONF_MIGRATE_PATH,
NULL);
}
get_dconf_data (app_id,
(const char **) paths,
migrate_path,
&defaults, &defaults_size,
&values, &values_size,
&locks, &locks_size);
if (defaults_size != 0 &&
!flatpak_bwrap_add_args_data (bwrap,
"dconf-defaults",
defaults, defaults_size,
"/etc/glib-2.0/settings/defaults",
error))
return FALSE;
if (locks_size != 0 &&
!flatpak_bwrap_add_args_data (bwrap,
"dconf-locks",
locks, locks_size,
"/etc/glib-2.0/settings/locks",
error))
return FALSE;
/* We do a one-time conversion of existing dconf settings to a keyfile.
* Only do that once the app stops requesting dconf access.
*/
if (migrate_path)
{
g_autofree char *filename = NULL;
filename = g_build_filename (g_get_home_dir (),
".var/app", app_id,
"config/glib-2.0/settings/keyfile",
NULL);
if (values_size != 0 && !g_file_test (filename, G_FILE_TEST_EXISTS))
{
g_autofree char *dir = g_path_get_dirname (filename);
if (g_mkdir_with_parents (dir, 0700) == -1)
return FALSE;
if (!g_file_set_contents (filename, values, values_size, error))
return FALSE;
}
}
return TRUE;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,033 |
xorg-xserver | c06e27b2f6fd9f7b9f827623a48876a225264132 | XkbWriteGeomOverlay(char *wire,XkbOverlayPtr ol,Bool swap)
{
register int r;
XkbOverlayRowPtr row;
xkbOverlayWireDesc * olWire;
olWire= (xkbOverlayWireDesc *)wire;
olWire->name= ol->name;
olWire->nRows= ol->num_rows;
if (swap) {
register int n;
swapl(&olWire->name,n);
}
wire= (char *)&olWire[1];
for (r=0,row=ol->rows;r<ol->num_rows;r++,row++) {
unsigned int k;
XkbOverlayKeyPtr key;
xkbOverlayRowWireDesc * rowWire;
rowWire= (xkbOverlayRowWireDesc *)wire;
rowWire->rowUnder= row->row_under;
rowWire->nKeys= row->num_keys;
wire= (char *)&rowWire[1];
for (k=0,key=row->keys;k<row->num_keys;k++,key++) {
xkbOverlayKeyWireDesc * keyWire;
keyWire= (xkbOverlayKeyWireDesc *)wire;
memcpy(keyWire->over,key->over.name,XkbKeyNameLength);
memcpy(keyWire->under,key->under.name,XkbKeyNameLength);
wire= (char *)&keyWire[1];
}
}
return wire;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,177 |
Chrome | 45d901b56f578a74b19ba0d10fa5c4c467f19303 | void GM2TabStyle::PaintBackgroundStroke(gfx::Canvas* canvas,
bool active,
SkColor stroke_color) const {
SkPath outer_path =
GetPath(TabStyle::PathType::kBorder, canvas->image_scale(), active);
gfx::ScopedCanvas scoped_canvas(canvas);
float scale = canvas->UndoDeviceScaleFactor();
cc::PaintFlags flags;
flags.setAntiAlias(true);
flags.setColor(stroke_color);
flags.setStyle(cc::PaintFlags::kStroke_Style);
flags.setStrokeWidth(GetStrokeThickness(active) * scale);
canvas->DrawPath(outer_path, flags);
}
| 1 | CVE-2016-5218 | 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,299 |
lldpd | a8d3c90feca548fc0656d95b5d278713db86ff61 | static int _lldp_send(struct lldpd *global,
struct lldpd_hardware *hardware,
u_int8_t c_id_subtype,
char *c_id,
int c_id_len,
u_int8_t p_id_subtype,
char *p_id,
int p_id_len,
int shutdown)
{
struct lldpd_port *port;
struct lldpd_chassis *chassis;
struct lldpd_frame *frame;
int length;
u_int8_t *packet, *pos, *tlv;
struct lldpd_mgmt *mgmt;
int proto;
u_int8_t mcastaddr_regular[] = LLDP_ADDR_NEAREST_BRIDGE;
u_int8_t mcastaddr_nontpmr[] = LLDP_ADDR_NEAREST_NONTPMR_BRIDGE;
u_int8_t mcastaddr_customer[] = LLDP_ADDR_NEAREST_CUSTOMER_BRIDGE;
u_int8_t *mcastaddr;
#ifdef ENABLE_DOT1
const u_int8_t dot1[] = LLDP_TLV_ORG_DOT1;
struct lldpd_vlan *vlan;
struct lldpd_ppvid *ppvid;
struct lldpd_pi *pi;
#endif
#ifdef ENABLE_DOT3
const u_int8_t dot3[] = LLDP_TLV_ORG_DOT3;
#endif
#ifdef ENABLE_LLDPMED
int i;
const u_int8_t med[] = LLDP_TLV_ORG_MED;
#endif
#ifdef ENABLE_CUSTOM
struct lldpd_custom *custom;
#endif
port = &hardware->h_lport;
chassis = port->p_chassis;
length = hardware->h_mtu;
if ((packet = (u_int8_t*)calloc(1, length)) == NULL)
return ENOMEM;
pos = packet;
/* Ethernet header */
switch (global->g_config.c_lldp_agent_type) {
case LLDP_AGENT_TYPE_NEAREST_NONTPMR_BRIDGE: mcastaddr = mcastaddr_nontpmr; break;
case LLDP_AGENT_TYPE_NEAREST_CUSTOMER_BRIDGE: mcastaddr = mcastaddr_customer; break;
case LLDP_AGENT_TYPE_NEAREST_BRIDGE:
default: mcastaddr = mcastaddr_regular; break;
}
if (!(
/* LLDP multicast address */
POKE_BYTES(mcastaddr, ETHER_ADDR_LEN) &&
/* Source MAC address */
POKE_BYTES(&hardware->h_lladdr, ETHER_ADDR_LEN)))
goto toobig;
/* Insert VLAN tag if needed */
if (port->p_vlan_tx_enabled) {
if (!(
/* VLAN ethertype */
POKE_UINT16(ETHERTYPE_VLAN) &&
/* VLAN Tag Control Information (TCI) */
/* Priority(3bits) | DEI(1bit) | VID(12bit) */
POKE_UINT16(port->p_vlan_tx_tag)))
goto toobig;
}
if (!(
/* LLDP frame */
POKE_UINT16(ETHERTYPE_LLDP)))
goto toobig;
/* Chassis ID */
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_CHASSIS_ID) &&
POKE_UINT8(c_id_subtype) &&
POKE_BYTES(c_id, c_id_len) &&
POKE_END_LLDP_TLV))
goto toobig;
/* Port ID */
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_PORT_ID) &&
POKE_UINT8(p_id_subtype) &&
POKE_BYTES(p_id, p_id_len) &&
POKE_END_LLDP_TLV))
goto toobig;
/* Time to live */
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_TTL) &&
POKE_UINT16(shutdown?0:(global?global->g_config.c_ttl:180)) &&
POKE_END_LLDP_TLV))
goto toobig;
if (shutdown)
goto end;
/* System name */
if (chassis->c_name && *chassis->c_name != '\0') {
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_SYSTEM_NAME) &&
POKE_BYTES(chassis->c_name, strlen(chassis->c_name)) &&
POKE_END_LLDP_TLV))
goto toobig;
}
/* System description (skip it if empty) */
if (chassis->c_descr && *chassis->c_descr != '\0') {
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_SYSTEM_DESCR) &&
POKE_BYTES(chassis->c_descr, strlen(chassis->c_descr)) &&
POKE_END_LLDP_TLV))
goto toobig;
}
/* System capabilities */
if (global->g_config.c_cap_advertise && chassis->c_cap_available) {
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_SYSTEM_CAP) &&
POKE_UINT16(chassis->c_cap_available) &&
POKE_UINT16(chassis->c_cap_enabled) &&
POKE_END_LLDP_TLV))
goto toobig;
}
/* Management addresses */
TAILQ_FOREACH(mgmt, &chassis->c_mgmt, m_entries) {
proto = lldpd_af_to_lldp_proto(mgmt->m_family);
if (proto == LLDP_MGMT_ADDR_NONE) continue;
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_MGMT_ADDR) &&
/* Size of the address, including its type */
POKE_UINT8(mgmt->m_addrsize + 1) &&
POKE_UINT8(proto) &&
POKE_BYTES(&mgmt->m_addr, mgmt->m_addrsize)))
goto toobig;
/* Interface port type, OID */
if (mgmt->m_iface == 0) {
if (!(
/* We don't know the management interface */
POKE_UINT8(LLDP_MGMT_IFACE_UNKNOWN) &&
POKE_UINT32(0)))
goto toobig;
} else {
if (!(
/* We have the index of the management interface */
POKE_UINT8(LLDP_MGMT_IFACE_IFINDEX) &&
POKE_UINT32(mgmt->m_iface)))
goto toobig;
}
if (!(
/* We don't provide an OID for management */
POKE_UINT8(0) &&
POKE_END_LLDP_TLV))
goto toobig;
}
/* Port description */
if (port->p_descr && *port->p_descr != '\0') {
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_PORT_DESCR) &&
POKE_BYTES(port->p_descr, strlen(port->p_descr)) &&
POKE_END_LLDP_TLV))
goto toobig;
}
#ifdef ENABLE_DOT1
/* Port VLAN ID */
if(port->p_pvid != 0) {
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_ORG) &&
POKE_BYTES(dot1, sizeof(dot1)) &&
POKE_UINT8(LLDP_TLV_DOT1_PVID) &&
POKE_UINT16(port->p_pvid) &&
POKE_END_LLDP_TLV)) {
goto toobig;
}
}
/* Port and Protocol VLAN IDs */
TAILQ_FOREACH(ppvid, &port->p_ppvids, p_entries) {
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_ORG) &&
POKE_BYTES(dot1, sizeof(dot1)) &&
POKE_UINT8(LLDP_TLV_DOT1_PPVID) &&
POKE_UINT8(ppvid->p_cap_status) &&
POKE_UINT16(ppvid->p_ppvid) &&
POKE_END_LLDP_TLV)) {
goto toobig;
}
}
/* VLANs */
TAILQ_FOREACH(vlan, &port->p_vlans, v_entries) {
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_ORG) &&
POKE_BYTES(dot1, sizeof(dot1)) &&
POKE_UINT8(LLDP_TLV_DOT1_VLANNAME) &&
POKE_UINT16(vlan->v_vid) &&
POKE_UINT8(strlen(vlan->v_name)) &&
POKE_BYTES(vlan->v_name, strlen(vlan->v_name)) &&
POKE_END_LLDP_TLV))
goto toobig;
}
/* Protocol Identities */
TAILQ_FOREACH(pi, &port->p_pids, p_entries) {
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_ORG) &&
POKE_BYTES(dot1, sizeof(dot1)) &&
POKE_UINT8(LLDP_TLV_DOT1_PI) &&
POKE_UINT8(pi->p_pi_len) &&
POKE_BYTES(pi->p_pi, pi->p_pi_len) &&
POKE_END_LLDP_TLV))
goto toobig;
}
#endif
#ifdef ENABLE_DOT3
/* Aggregation status */
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_ORG) &&
POKE_BYTES(dot3, sizeof(dot3)) &&
POKE_UINT8(LLDP_TLV_DOT3_LA) &&
/* Bit 0 = capability ; Bit 1 = status */
POKE_UINT8((port->p_aggregid) ? 3:1) &&
POKE_UINT32(port->p_aggregid) &&
POKE_END_LLDP_TLV))
goto toobig;
/* MAC/PHY */
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_ORG) &&
POKE_BYTES(dot3, sizeof(dot3)) &&
POKE_UINT8(LLDP_TLV_DOT3_MAC) &&
POKE_UINT8(port->p_macphy.autoneg_support |
(port->p_macphy.autoneg_enabled << 1)) &&
POKE_UINT16(port->p_macphy.autoneg_advertised) &&
POKE_UINT16(port->p_macphy.mau_type) &&
POKE_END_LLDP_TLV))
goto toobig;
/* MFS */
if (port->p_mfs) {
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_ORG) &&
POKE_BYTES(dot3, sizeof(dot3)) &&
POKE_UINT8(LLDP_TLV_DOT3_MFS) &&
POKE_UINT16(port->p_mfs) &&
POKE_END_LLDP_TLV))
goto toobig;
}
/* Power */
if (port->p_power.devicetype) {
if (!(
(port->p_power.type_ext != LLDP_DOT3_POWER_8023BT_OFF ?
(tlv = pos, POKE_UINT16((LLDP_TLV_ORG << 9) | (0x1d))):
POKE_START_LLDP_TLV(LLDP_TLV_ORG)) &&
POKE_BYTES(dot3, sizeof(dot3)) &&
POKE_UINT8(LLDP_TLV_DOT3_POWER) &&
POKE_UINT8((
(((2 - port->p_power.devicetype) %(1<< 1))<<0) |
(( port->p_power.supported %(1<< 1))<<1) |
(( port->p_power.enabled %(1<< 1))<<2) |
(( port->p_power.paircontrol %(1<< 1))<<3))) &&
POKE_UINT8(port->p_power.pairs) &&
POKE_UINT8(port->p_power.class)))
goto toobig;
/* 802.3at */
if (port->p_power.powertype != LLDP_DOT3_POWER_8023AT_OFF) {
if (!(
POKE_UINT8(((((port->p_power.powertype ==
LLDP_DOT3_POWER_8023AT_TYPE1)?1:0) << 7) |
(((port->p_power.devicetype ==
LLDP_DOT3_POWER_PSE)?0:1) << 6) |
((port->p_power.source %(1<< 2))<<4) |
((port->p_power.pd_4pid %(1 << 1))<<2) |
((port->p_power.priority %(1<< 2))<<0))) &&
POKE_UINT16(port->p_power.requested) &&
POKE_UINT16(port->p_power.allocated)))
goto toobig;
}
if (port->p_power.type_ext != LLDP_DOT3_POWER_8023BT_OFF) {
if (!(
POKE_UINT16(port->p_power.requested_a) &&
POKE_UINT16(port->p_power.requested_b) &&
POKE_UINT16(port->p_power.allocated_a) &&
POKE_UINT16(port->p_power.allocated_b) &&
POKE_UINT16((
(port->p_power.pse_status << 14) |
(port->p_power.pd_status << 12) |
(port->p_power.pse_pairs_ext << 10) |
(port->p_power.class_a << 7) |
(port->p_power.class_b << 4) |
(port->p_power.class_ext << 0))) &&
POKE_UINT8(
/* Adjust by -1 to enable 0 to mean no 802.3bt support */
((port->p_power.type_ext -1) << 1) |
(port->p_power.pd_load << 0)) &&
POKE_UINT16(port->p_power.pse_max) &&
/* Send 0 for autoclass and power down requests */
POKE_UINT8(0) &&
POKE_UINT16(0) &&
POKE_UINT8(0)))
goto toobig;
}
if (!(POKE_END_LLDP_TLV))
goto toobig;
}
#endif
#ifdef ENABLE_LLDPMED
if (port->p_med_cap_enabled) {
/* LLDP-MED cap */
if (port->p_med_cap_enabled & LLDP_MED_CAP_CAP) {
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_ORG) &&
POKE_BYTES(med, sizeof(med)) &&
POKE_UINT8(LLDP_TLV_MED_CAP) &&
POKE_UINT16(chassis->c_med_cap_available) &&
POKE_UINT8(chassis->c_med_type) &&
POKE_END_LLDP_TLV))
goto toobig;
}
/* LLDP-MED inventory */
#define LLDP_INVENTORY(value, subtype) \
if (value) { \
if (!( \
POKE_START_LLDP_TLV(LLDP_TLV_ORG) && \
POKE_BYTES(med, sizeof(med)) && \
POKE_UINT8(subtype) && \
POKE_BYTES(value, \
(strlen(value)>32)?32:strlen(value)) && \
POKE_END_LLDP_TLV)) \
goto toobig; \
}
if (port->p_med_cap_enabled & LLDP_MED_CAP_IV) {
LLDP_INVENTORY(chassis->c_med_hw,
LLDP_TLV_MED_IV_HW);
LLDP_INVENTORY(chassis->c_med_fw,
LLDP_TLV_MED_IV_FW);
LLDP_INVENTORY(chassis->c_med_sw,
LLDP_TLV_MED_IV_SW);
LLDP_INVENTORY(chassis->c_med_sn,
LLDP_TLV_MED_IV_SN);
LLDP_INVENTORY(chassis->c_med_manuf,
LLDP_TLV_MED_IV_MANUF);
LLDP_INVENTORY(chassis->c_med_model,
LLDP_TLV_MED_IV_MODEL);
LLDP_INVENTORY(chassis->c_med_asset,
LLDP_TLV_MED_IV_ASSET);
}
/* LLDP-MED location */
for (i = 0; i < LLDP_MED_LOCFORMAT_LAST; i++) {
if (port->p_med_location[i].format == i + 1) {
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_ORG) &&
POKE_BYTES(med, sizeof(med)) &&
POKE_UINT8(LLDP_TLV_MED_LOCATION) &&
POKE_UINT8(port->p_med_location[i].format) &&
POKE_BYTES(port->p_med_location[i].data,
port->p_med_location[i].data_len) &&
POKE_END_LLDP_TLV))
goto toobig;
}
}
/* LLDP-MED network policy */
for (i = 0; i < LLDP_MED_APPTYPE_LAST; i++) {
if (port->p_med_policy[i].type == i + 1) {
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_ORG) &&
POKE_BYTES(med, sizeof(med)) &&
POKE_UINT8(LLDP_TLV_MED_POLICY) &&
POKE_UINT32((
((port->p_med_policy[i].type %(1<< 8))<<24) |
((port->p_med_policy[i].unknown %(1<< 1))<<23) |
((port->p_med_policy[i].tagged %(1<< 1))<<22) |
/*((0 %(1<< 1))<<21) |*/
((port->p_med_policy[i].vid %(1<<12))<< 9) |
((port->p_med_policy[i].priority %(1<< 3))<< 6) |
((port->p_med_policy[i].dscp %(1<< 6))<< 0) )) &&
POKE_END_LLDP_TLV))
goto toobig;
}
}
/* LLDP-MED POE-MDI */
if ((port->p_med_power.devicetype == LLDP_MED_POW_TYPE_PSE) ||
(port->p_med_power.devicetype == LLDP_MED_POW_TYPE_PD)) {
int devicetype = 0, source = 0;
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_ORG) &&
POKE_BYTES(med, sizeof(med)) &&
POKE_UINT8(LLDP_TLV_MED_MDI)))
goto toobig;
switch (port->p_med_power.devicetype) {
case LLDP_MED_POW_TYPE_PSE:
devicetype = 0;
switch (port->p_med_power.source) {
case LLDP_MED_POW_SOURCE_PRIMARY: source = 1; break;
case LLDP_MED_POW_SOURCE_BACKUP: source = 2; break;
case LLDP_MED_POW_SOURCE_RESERVED: source = 3; break;
default: source = 0; break;
}
break;
case LLDP_MED_POW_TYPE_PD:
devicetype = 1;
switch (port->p_med_power.source) {
case LLDP_MED_POW_SOURCE_PSE: source = 1; break;
case LLDP_MED_POW_SOURCE_LOCAL: source = 2; break;
case LLDP_MED_POW_SOURCE_BOTH: source = 3; break;
default: source = 0; break;
}
break;
}
if (!(
POKE_UINT8((
((devicetype %(1<< 2))<<6) |
((source %(1<< 2))<<4) |
((port->p_med_power.priority %(1<< 4))<<0) )) &&
POKE_UINT16(port->p_med_power.val) &&
POKE_END_LLDP_TLV))
goto toobig;
}
}
#endif
#ifdef ENABLE_CUSTOM
TAILQ_FOREACH(custom, &port->p_custom_list, next) {
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_ORG) &&
POKE_BYTES(custom->oui, sizeof(custom->oui)) &&
POKE_UINT8(custom->subtype) &&
POKE_BYTES(custom->oui_info, custom->oui_info_len) &&
POKE_END_LLDP_TLV))
goto toobig;
}
#endif
end:
/* END */
if (!(
POKE_START_LLDP_TLV(LLDP_TLV_END) &&
POKE_END_LLDP_TLV))
goto toobig;
if (interfaces_send_helper(global, hardware,
(char *)packet, pos - packet) == -1) {
log_warn("lldp", "unable to send packet on real device for %s",
hardware->h_ifname);
free(packet);
return ENETDOWN;
}
hardware->h_tx_cnt++;
/* We assume that LLDP frame is the reference */
if (!shutdown && (frame = (struct lldpd_frame*)malloc(
sizeof(int) + pos - packet)) != NULL) {
frame->size = pos - packet;
memcpy(&frame->frame, packet, frame->size);
if ((hardware->h_lport.p_lastframe == NULL) ||
(hardware->h_lport.p_lastframe->size != frame->size) ||
(memcmp(hardware->h_lport.p_lastframe->frame, frame->frame,
frame->size) != 0)) {
free(hardware->h_lport.p_lastframe);
hardware->h_lport.p_lastframe = frame;
hardware->h_lport.p_lastchange = time(NULL);
} else free(frame);
}
free(packet);
return 0;
toobig:
log_info("lldp", "Cannot send LLDP packet for %s, Too big message", p_id);
free(packet);
return E2BIG;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,996 |
postgres | 31400a673325147e1205326008e32135a78b4d8a | hstore_from_record(PG_FUNCTION_ARGS)
{
HeapTupleHeader rec;
int32 buflen;
HStore *out;
Pairs *pairs;
Oid tupType;
int32 tupTypmod;
TupleDesc tupdesc;
HeapTupleData tuple;
RecordIOData *my_extra;
int ncolumns;
int i,
j;
Datum *values;
bool *nulls;
if (PG_ARGISNULL(0))
{
Oid argtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
/*
* have no tuple to look at, so the only source of type info is the
* argtype. The lookup_rowtype_tupdesc call below will error out if we
* don't have a known composite type oid here.
*/
tupType = argtype;
tupTypmod = -1;
rec = NULL;
}
else
{
rec = PG_GETARG_HEAPTUPLEHEADER(0);
/* Extract type info from the tuple itself */
tupType = HeapTupleHeaderGetTypeId(rec);
tupTypmod = HeapTupleHeaderGetTypMod(rec);
}
tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
ncolumns = tupdesc->natts;
/*
* We arrange to look up the needed I/O info just once per series of
* calls, assuming the record type doesn't change underneath us.
*/
my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
if (my_extra == NULL ||
my_extra->ncolumns != ncolumns)
{
fcinfo->flinfo->fn_extra =
MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
sizeof(RecordIOData) - sizeof(ColumnIOData)
+ ncolumns * sizeof(ColumnIOData));
my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
my_extra->record_type = InvalidOid;
my_extra->record_typmod = 0;
}
if (my_extra->record_type != tupType ||
my_extra->record_typmod != tupTypmod)
{
MemSet(my_extra, 0,
sizeof(RecordIOData) - sizeof(ColumnIOData)
+ ncolumns * sizeof(ColumnIOData));
my_extra->record_type = tupType;
my_extra->record_typmod = tupTypmod;
my_extra->ncolumns = ncolumns;
}
pairs = palloc(ncolumns * sizeof(Pairs));
if (rec)
{
/* Build a temporary HeapTuple control structure */
tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
ItemPointerSetInvalid(&(tuple.t_self));
tuple.t_tableOid = InvalidOid;
tuple.t_data = rec;
values = (Datum *) palloc(ncolumns * sizeof(Datum));
nulls = (bool *) palloc(ncolumns * sizeof(bool));
/* Break down the tuple into fields */
heap_deform_tuple(&tuple, tupdesc, values, nulls);
}
else
{
values = NULL;
nulls = NULL;
}
for (i = 0, j = 0; i < ncolumns; ++i)
{
ColumnIOData *column_info = &my_extra->columns[i];
Oid column_type = tupdesc->attrs[i]->atttypid;
char *value;
/* Ignore dropped columns in datatype */
if (tupdesc->attrs[i]->attisdropped)
continue;
pairs[j].key = NameStr(tupdesc->attrs[i]->attname);
pairs[j].keylen = hstoreCheckKeyLen(strlen(NameStr(tupdesc->attrs[i]->attname)));
if (!nulls || nulls[i])
{
pairs[j].val = NULL;
pairs[j].vallen = 4;
pairs[j].isnull = true;
pairs[j].needfree = false;
++j;
continue;
}
/*
* Convert the column value to text
*/
if (column_info->column_type != column_type)
{
bool typIsVarlena;
getTypeOutputInfo(column_type,
&column_info->typiofunc,
&typIsVarlena);
fmgr_info_cxt(column_info->typiofunc, &column_info->proc,
fcinfo->flinfo->fn_mcxt);
column_info->column_type = column_type;
}
value = OutputFunctionCall(&column_info->proc, values[i]);
pairs[j].val = value;
pairs[j].vallen = hstoreCheckValLen(strlen(value));
pairs[j].isnull = false;
pairs[j].needfree = false;
++j;
}
ncolumns = hstoreUniquePairs(pairs, j, &buflen);
out = hstorePairs(pairs, ncolumns, buflen);
ReleaseTupleDesc(tupdesc);
PG_RETURN_POINTER(out);
}
| 1 | CVE-2014-2669 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 2,650 |
Android | d4271b792bdad85a80e2b83ab34c4b30b74f53ec | void SoftMPEG4::onReset() {
SoftVideoDecoderOMXComponent::onReset();
mPvToOmxTimeMap.clear();
mSignalledError = false;
mFramesConfigured = false;
if (mInitialized) {
PVCleanUpVideoDecoder(mHandle);
mInitialized = false;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,600 |
mruby | 55edae0226409de25e59922807cb09acb45731a2 | obj_respond_to(mrb_state *mrb, mrb_value self)
{
mrb_value mid;
mrb_sym id, rtm_id;
mrb_bool priv = FALSE, respond_to_p = TRUE;
mrb_get_args(mrb, "o|b", &mid, &priv);
if (mrb_symbol_p(mid)) {
id = mrb_symbol(mid);
}
else {
mrb_value tmp;
if (mrb_string_p(mid)) {
tmp = mrb_check_intern_str(mrb, mid);
}
else {
tmp = mrb_check_string_type(mrb, mid);
if (mrb_nil_p(tmp)) {
tmp = mrb_inspect(mrb, mid);
mrb_raisef(mrb, E_TYPE_ERROR, "%S is not a symbol", tmp);
}
tmp = mrb_check_intern_str(mrb, tmp);
}
if (mrb_nil_p(tmp)) {
respond_to_p = FALSE;
}
else {
id = mrb_symbol(tmp);
}
}
if (respond_to_p) {
respond_to_p = basic_obj_respond_to(mrb, self, id, !priv);
}
if (!respond_to_p) {
rtm_id = mrb_intern_lit(mrb, "respond_to_missing?");
if (basic_obj_respond_to(mrb, self, rtm_id, !priv)) {
mrb_value args[2], v;
args[0] = mid;
args[1] = mrb_bool_value(priv);
v = mrb_funcall_argv(mrb, self, rtm_id, 2, args);
return mrb_bool_value(mrb_bool(v));
}
}
return mrb_bool_value(respond_to_p);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,358 |
Chrome | 5bb223676defeba9c44a5ce42460c86e24561e73 | ExtensionsGuestViewMessageFilter::ExtensionsGuestViewMessageFilter(
int render_process_id,
BrowserContext* context)
: GuestViewMessageFilter(kFilteredMessageClasses,
base::size(kFilteredMessageClasses),
render_process_id,
context),
content::BrowserAssociatedInterface<mojom::GuestView>(this, this) {
GetProcessIdToFilterMap()->insert_or_assign(render_process_id_, this);
}
| 1 | CVE-2019-5796 | 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 | 5,648 |
linux | e6a21a14106d9718aa4f8e115b1e474888eeba44 | static void vidtv_s302m_compute_pts_from_video(struct vidtv_encoder *e)
{
struct vidtv_access_unit *au = e->access_units;
struct vidtv_access_unit *sync_au = e->sync->access_units;
/* use the same pts from the video access unit*/
while (au && sync_au) {
au->pts = sync_au->pts;
au = au->next;
sync_au = sync_au->next;
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,498 |
Chrome | 297ae873b471a46929ea39697b121c0b411434ee | void CustomButton::OnGestureEvent(ui::GestureEvent* event) {
if (state_ == STATE_DISABLED) {
Button::OnGestureEvent(event);
return;
}
if (event->type() == ui::ET_GESTURE_TAP && IsTriggerableEvent(*event)) {
SetState(STATE_HOVERED);
hover_animation_->Reset(1.0);
NotifyClick(*event);
event->StopPropagation();
} else if (event->type() == ui::ET_GESTURE_TAP_DOWN &&
ShouldEnterPushedState(*event)) {
SetState(STATE_PRESSED);
if (request_focus_on_press_)
RequestFocus();
event->StopPropagation();
} else if (event->type() == ui::ET_GESTURE_TAP_CANCEL ||
event->type() == ui::ET_GESTURE_END) {
SetState(STATE_NORMAL);
}
if (!event->handled())
Button::OnGestureEvent(event);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,407 |
linux | f43bfaeddc79effbf3d0fcb53ca477cca66f3db8 | static irqreturn_t atl2_intr(int irq, void *data)
{
struct atl2_adapter *adapter = netdev_priv(data);
struct atl2_hw *hw = &adapter->hw;
u32 status;
status = ATL2_READ_REG(hw, REG_ISR);
if (0 == status)
return IRQ_NONE;
/* link event */
if (status & ISR_PHY)
atl2_clear_phy_int(adapter);
/* clear ISR status, and Enable CMB DMA/Disable Interrupt */
ATL2_WRITE_REG(hw, REG_ISR, status | ISR_DIS_INT);
/* check if PCIE PHY Link down */
if (status & ISR_PHY_LINKDOWN) {
if (netif_running(adapter->netdev)) { /* reset MAC */
ATL2_WRITE_REG(hw, REG_ISR, 0);
ATL2_WRITE_REG(hw, REG_IMR, 0);
ATL2_WRITE_FLUSH(hw);
schedule_work(&adapter->reset_task);
return IRQ_HANDLED;
}
}
/* check if DMA read/write error? */
if (status & (ISR_DMAR_TO_RST | ISR_DMAW_TO_RST)) {
ATL2_WRITE_REG(hw, REG_ISR, 0);
ATL2_WRITE_REG(hw, REG_IMR, 0);
ATL2_WRITE_FLUSH(hw);
schedule_work(&adapter->reset_task);
return IRQ_HANDLED;
}
/* link event */
if (status & (ISR_PHY | ISR_MANUAL)) {
adapter->netdev->stats.tx_carrier_errors++;
atl2_check_for_link(adapter);
}
/* transmit event */
if (status & ISR_TX_EVENT)
atl2_intr_tx(adapter);
/* rx exception */
if (status & ISR_RX_EVENT)
atl2_intr_rx(adapter);
/* re-enable Interrupt */
ATL2_WRITE_REG(&adapter->hw, REG_ISR, 0);
return IRQ_HANDLED;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,605 |
linux | f9dbdf97a5bd92b1a49cee3d591b55b11fd7a6d5 |
static struct bus_type iscsi_flashnode_bus;
int iscsi_flashnode_bus_match(struct device *dev,
struct device_driver *drv)
{
if (dev->bus == &iscsi_flashnode_bus) | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,714 |
pdns | f9c57c98da1b1007a51680629b667d57d9b702b8 | void emitFlightTimes()
{
uint64_t totals = countLessThan(flightTimes.size());
unsigned int limits[]={1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 100, 200, 500, 1000, (unsigned int) flightTimes.size()};
uint64_t sofar=0;
cout.setf(std::ios::fixed);
cout.precision(2);
for(unsigned int i =0 ; i < sizeof(limits)/sizeof(limits[0]); ++i) {
if(limits[i]!=flightTimes.size())
cout<<"Within "<<limits[i]<<" msec: ";
else
cout<<"Beyond "<<limits[i]-2<<" msec: ";
uint64_t here = countLessThan(limits[i]);
cout<<100.0*here/totals<<"% ("<<100.0*(here-sofar)/totals<<"%)"<<endl;
sofar=here;
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,179 |
openssl | 3612ff6fcec0e3d1f2a598135fe12177c0419582 | char *BN_bn2dec(const BIGNUM *a)
{
int i = 0, num, ok = 0;
char *buf = NULL;
char *p;
BIGNUM *t = NULL;
BN_ULONG *bn_data = NULL, *lp;
int bn_data_num;
/*-
* get an upper bound for the length of the decimal integer
* num <= (BN_num_bits(a) + 1) * log(2)
* <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1 (rounding error)
* <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1
*/
i = BN_num_bits(a) * 3;
num = (i / 10 + i / 1000 + 1) + 1;
bn_data_num = num / BN_DEC_NUM + 1;
bn_data = OPENSSL_malloc(bn_data_num * sizeof(BN_ULONG));
buf = OPENSSL_malloc(num + 3);
if ((buf == NULL) || (bn_data == NULL)) {
BNerr(BN_F_BN_BN2DEC, ERR_R_MALLOC_FAILURE);
goto err;
}
if ((t = BN_dup(a)) == NULL)
goto err;
#define BUF_REMAIN (num+3 - (size_t)(p - buf))
p = buf;
lp = bn_data;
if (BN_is_zero(t)) {
*(p++) = '0';
*(p++) = '\0';
} else {
if (BN_is_negative(t))
*p++ = '-';
while (!BN_is_zero(t)) {
if (lp - bn_data >= bn_data_num)
goto err;
*lp = BN_div_word(t, BN_DEC_CONV);
if (*lp == (BN_ULONG)-1)
goto err;
lp++;
}
lp--;
/*
* We now have a series of blocks, BN_DEC_NUM chars in length, where
* the last one needs truncation. The blocks need to be reversed in
* order.
*/
BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT1, *lp);
while (*p)
p++;
while (lp != bn_data) {
lp--;
BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp);
while (*p)
p++;
}
}
ok = 1;
err:
if (bn_data != NULL)
OPENSSL_free(bn_data);
if (t != NULL)
BN_free(t);
if (!ok && buf) {
OPENSSL_free(buf);
buf = NULL;
}
return (buf);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,196 |
FreeRDP | 09b9d4f1994a674c4ec85b4947aa656eda1aed8a | static BOOL gdi_Glyph_EndDraw(rdpContext* context, INT32 x, INT32 y,
INT32 width, INT32 height, UINT32 bgcolor, UINT32 fgcolor)
{
rdpGdi* gdi;
if (!context || !context->gdi)
return FALSE;
gdi = context->gdi;
if (!gdi->drawing || !gdi->drawing->hdc)
return FALSE;
gdi_SetNullClipRgn(gdi->drawing->hdc);
return TRUE;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,151 |
proxygen | 52cf331743ebd74194d6343a6c2ec52bb917c982 | bool HTTP2Codec::onIngressUpgradeMessage(const HTTPMessage& msg) {
if (!HTTPParallelCodec::onIngressUpgradeMessage(msg)) {
return false;
}
if (msg.getHeaders().getNumberOfValues(http2::kProtocolSettingsHeader) != 1) {
VLOG(4) << __func__ << " with no HTTP2-Settings";
return false;
}
const auto& settingsHeader = msg.getHeaders().getSingleOrEmpty(
http2::kProtocolSettingsHeader);
if (settingsHeader.empty()) {
return true;
}
auto decoded = base64url_decode(settingsHeader);
// Must be well formed Base64Url and not too large
if (decoded.empty() || decoded.length() > http2::kMaxFramePayloadLength) {
VLOG(4) << __func__ << " failed to decode HTTP2-Settings";
return false;
}
std::unique_ptr<IOBuf> decodedBuf = IOBuf::wrapBuffer(decoded.data(),
decoded.length());
IOBufQueue settingsQueue{IOBufQueue::cacheChainLength()};
settingsQueue.append(std::move(decodedBuf));
Cursor c(settingsQueue.front());
std::deque<SettingPair> settings;
// downcast is ok because of above length check
http2::FrameHeader frameHeader{
(uint32_t)settingsQueue.chainLength(), 0, http2::FrameType::SETTINGS, 0, 0};
auto err = http2::parseSettings(c, frameHeader, settings);
if (err != ErrorCode::NO_ERROR) {
VLOG(4) << __func__ << " bad settings frame";
return false;
}
if (handleSettings(settings) != ErrorCode::NO_ERROR) {
VLOG(4) << __func__ << " handleSettings failed";
return false;
}
return true;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,816 |
ImageMagick | 361ed689cc8e56fd125f9d0d6508e9eb303bdca6 | static MagickBooleanType WriteWEBPImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
const char
*value;
int
webp_status;
MagickBooleanType
status;
MemoryInfo
*pixel_info;
register uint32_t
*magick_restrict q;
ssize_t
y;
WebPAuxStats
statistics;
WebPConfig
configure;
#if defined(MAGICKCORE_WEBPMUX_DELEGATE)
WebPMemoryWriter
writer_info;
#endif
WebPPicture
picture;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns > 16383UL) || (image->rows > 16383UL))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
if ((WebPPictureInit(&picture) == 0) || (WebPConfigInit(&configure) == 0))
ThrowWriterException(ResourceLimitError,"UnableToEncodeImageFile");
#if !defined(MAGICKCORE_WEBPMUX_DELEGATE)
picture.writer=WebPEncodeWriter;
picture.custom_ptr=(void *) image;
#else
WebPMemoryWriterInit(&writer_info);
picture.writer=WebPMemoryWrite;
picture.custom_ptr=(&writer_info);
#endif
#if WEBP_DECODER_ABI_VERSION >= 0x0100
picture.progress_hook=WebPEncodeProgress;
picture.user_data=(void *) image;
#endif
picture.stats=(&statistics);
picture.width=(int) image->columns;
picture.height=(int) image->rows;
picture.argb_stride=(int) image->columns;
picture.use_argb=1;
if (image->quality != UndefinedCompressionQuality)
configure.quality=(float) image->quality;
if (image->quality >= 100)
configure.lossless=1;
value=GetImageOption(image_info,"webp:lossless");
if (value != (char *) NULL)
configure.lossless=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:method");
if (value != (char *) NULL)
configure.method=StringToInteger(value);
value=GetImageOption(image_info,"webp:image-hint");
if (value != (char *) NULL)
{
if (LocaleCompare(value,"default") == 0)
configure.image_hint=WEBP_HINT_DEFAULT;
if (LocaleCompare(value,"photo") == 0)
configure.image_hint=WEBP_HINT_PHOTO;
if (LocaleCompare(value,"picture") == 0)
configure.image_hint=WEBP_HINT_PICTURE;
#if WEBP_DECODER_ABI_VERSION >= 0x0200
if (LocaleCompare(value,"graph") == 0)
configure.image_hint=WEBP_HINT_GRAPH;
#endif
}
value=GetImageOption(image_info,"webp:target-size");
if (value != (char *) NULL)
configure.target_size=StringToInteger(value);
value=GetImageOption(image_info,"webp:target-psnr");
if (value != (char *) NULL)
configure.target_PSNR=(float) StringToDouble(value,(char **) NULL);
value=GetImageOption(image_info,"webp:segments");
if (value != (char *) NULL)
configure.segments=StringToInteger(value);
value=GetImageOption(image_info,"webp:sns-strength");
if (value != (char *) NULL)
configure.sns_strength=StringToInteger(value);
value=GetImageOption(image_info,"webp:filter-strength");
if (value != (char *) NULL)
configure.filter_strength=StringToInteger(value);
value=GetImageOption(image_info,"webp:filter-sharpness");
if (value != (char *) NULL)
configure.filter_sharpness=StringToInteger(value);
value=GetImageOption(image_info,"webp:filter-type");
if (value != (char *) NULL)
configure.filter_type=StringToInteger(value);
value=GetImageOption(image_info,"webp:auto-filter");
if (value != (char *) NULL)
configure.autofilter=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:alpha-compression");
if (value != (char *) NULL)
configure.alpha_compression=StringToInteger(value);
value=GetImageOption(image_info,"webp:alpha-filtering");
if (value != (char *) NULL)
configure.alpha_filtering=StringToInteger(value);
value=GetImageOption(image_info,"webp:alpha-quality");
if (value != (char *) NULL)
configure.alpha_quality=StringToInteger(value);
value=GetImageOption(image_info,"webp:pass");
if (value != (char *) NULL)
configure.pass=StringToInteger(value);
value=GetImageOption(image_info,"webp:show-compressed");
if (value != (char *) NULL)
configure.show_compressed=StringToInteger(value);
value=GetImageOption(image_info,"webp:preprocessing");
if (value != (char *) NULL)
configure.preprocessing=StringToInteger(value);
value=GetImageOption(image_info,"webp:partitions");
if (value != (char *) NULL)
configure.partitions=StringToInteger(value);
value=GetImageOption(image_info,"webp:partition-limit");
if (value != (char *) NULL)
configure.partition_limit=StringToInteger(value);
#if WEBP_DECODER_ABI_VERSION >= 0x0201
value=GetImageOption(image_info,"webp:emulate-jpeg-size");
if (value != (char *) NULL)
configure.emulate_jpeg_size=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:low-memory");
if (value != (char *) NULL)
configure.low_memory=(int) ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
value=GetImageOption(image_info,"webp:thread-level");
if (value != (char *) NULL)
configure.thread_level=StringToInteger(value);
#endif
if (WebPValidateConfig(&configure) == 0)
ThrowWriterException(ResourceLimitError,"UnableToEncodeImageFile");
/*
Allocate memory for pixels.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
sizeof(*picture.argb));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
picture.argb=(uint32_t *) GetVirtualMemoryBlob(pixel_info);
/*
Convert image to WebP raster pixels.
*/
q=picture.argb;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(uint32_t) (image->alpha_trait != UndefinedPixelTrait ?
ScaleQuantumToChar(GetPixelAlpha(image,p)) << 24 : 0xff000000) |
(ScaleQuantumToChar(GetPixelRed(image,p)) << 16) |
(ScaleQuantumToChar(GetPixelGreen(image,p)) << 8) |
(ScaleQuantumToChar(GetPixelBlue(image,p)));
p+=GetPixelChannels(image);
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
webp_status=WebPEncode(&configure,&picture);
if (webp_status == 0)
{
const char
*message;
switch (picture.error_code)
{
case VP8_ENC_ERROR_OUT_OF_MEMORY:
{
message="out of memory";
break;
}
case VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY:
{
message="bitstream out of memory";
break;
}
case VP8_ENC_ERROR_NULL_PARAMETER:
{
message="NULL parameter";
break;
}
case VP8_ENC_ERROR_INVALID_CONFIGURATION:
{
message="invalid configuration";
break;
}
case VP8_ENC_ERROR_BAD_DIMENSION:
{
message="bad dimension";
break;
}
case VP8_ENC_ERROR_PARTITION0_OVERFLOW:
{
message="partition 0 overflow (> 512K)";
break;
}
case VP8_ENC_ERROR_PARTITION_OVERFLOW:
{
message="partition overflow (> 16M)";
break;
}
case VP8_ENC_ERROR_BAD_WRITE:
{
message="bad write";
break;
}
case VP8_ENC_ERROR_FILE_TOO_BIG:
{
message="file too big (> 4GB)";
break;
}
#if WEBP_DECODER_ABI_VERSION >= 0x0100
case VP8_ENC_ERROR_USER_ABORT:
{
message="user abort";
break;
}
#endif
default:
{
message="unknown exception";
break;
}
}
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
(char *) message,"`%s'",image->filename);
}
#if defined(MAGICKCORE_WEBPMUX_DELEGATE)
{
const StringInfo
*profile;
WebPData
chunk,
image_chunk = { writer_info.mem, writer_info.size };
WebPMux
*mux;
WebPMuxError
mux_error;
/*
Set image profiles (if any).
*/
mux_error=WEBP_MUX_OK;
chunk.size=0;
mux=WebPMuxNew();
profile=GetImageProfile(image,"ICC");
if ((profile != (StringInfo *) NULL) && (mux_error == WEBP_MUX_OK))
{
chunk.bytes=GetStringInfoDatum(profile);
chunk.size=GetStringInfoLength(profile);
mux_error=WebPMuxSetChunk(mux,"ICCP",&chunk,0);
}
profile=GetImageProfile(image,"EXIF");
if ((profile != (StringInfo *) NULL) && (mux_error == WEBP_MUX_OK))
{
chunk.bytes=GetStringInfoDatum(profile);
chunk.size=GetStringInfoLength(profile);
mux_error=WebPMuxSetChunk(mux,"EXIF",&chunk,0);
}
profile=GetImageProfile(image,"XMP");
if ((profile != (StringInfo *) NULL) && (mux_error == WEBP_MUX_OK))
{
chunk.bytes=GetStringInfoDatum(profile);
chunk.size=GetStringInfoLength(profile);
mux_error=WebPMuxSetChunk(mux,"XMP",&chunk,0);
}
if (mux_error != WEBP_MUX_OK)
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"UnableToEncodeImageFile","`%s'",image->filename);
if (chunk.size != 0)
{
WebPData
picture_profiles = { writer_info.mem, writer_info.size };
/*
Replace original container with image profile (if any).
*/
WebPMuxSetImage(mux,&image_chunk,1);
mux_error=WebPMuxAssemble(mux,&picture_profiles);
WebPMemoryWriterClear(&writer_info);
writer_info.size=picture_profiles.size;
writer_info.mem=(unsigned char *) picture_profiles.bytes;
}
WebPMuxDelete(mux);
}
(void) WriteBlob(image,writer_info.size,writer_info.mem);
#endif
picture.argb=(uint32_t *) NULL;
WebPPictureFree(&picture);
#if defined(MAGICKCORE_WEBPMUX_DELEGATE)
WebPMemoryWriterClear(&writer_info);
#endif
pixel_info=RelinquishVirtualMemory(pixel_info);
(void) CloseBlob(image);
return(webp_status == 0 ? MagickFalse : MagickTrue);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,676 |
Chrome | 3f38b2253b19f9f9595f79fb92bfb5077e7b1959 | SubprocessMetricsProviderTest()
: thread_bundle_(content::TestBrowserThreadBundle::DEFAULT) {
base::PersistentHistogramAllocator::GetCreateHistogramResultHistogram();
provider_.MergeHistogramDeltas();
test_recorder_ = base::StatisticsRecorder::CreateTemporaryForTesting();
base::GlobalHistogramAllocator::CreateWithLocalMemory(TEST_MEMORY_SIZE,
0, "");
}
| 1 | CVE-2016-1632 | 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,553 |
platform_bionic | 7f5aa4f35e23fd37425b3a5041737cdf58f87385 | void* leak_memalign(size_t alignment, size_t bytes)
{
// we can just use malloc
if (alignment <= MALLOC_ALIGNMENT)
return leak_malloc(bytes);
// need to make sure it's a power of two
if (alignment & (alignment-1))
alignment = 1L << (31 - __builtin_clz(alignment));
// here, aligment is at least MALLOC_ALIGNMENT<<1 bytes
// we will align by at least MALLOC_ALIGNMENT bytes
// and at most alignment-MALLOC_ALIGNMENT bytes
size_t size = (alignment-MALLOC_ALIGNMENT) + bytes;
void* base = leak_malloc(size);
if (base != NULL) {
intptr_t ptr = (intptr_t)base;
if ((ptr % alignment) == 0)
return base;
// align the pointer
ptr += ((-ptr) % alignment);
// there is always enough space for the base pointer and the guard
((void**)ptr)[-1] = MEMALIGN_GUARD;
((void**)ptr)[-2] = base;
return (void*)ptr;
}
return base;
} | 1 | CVE-2012-2674 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 2,211 |
systemd | bf65b7e0c9fc215897b676ab9a7c9d1c688143ba | static int hashmap_complete_move(Hashmap **s, Hashmap **other) {
assert(s);
assert(other);
if (!*other)
return 0;
if (*s)
return hashmap_move(*s, *other);
else
*s = TAKE_PTR(*other);
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,085 |
Chrome | 52dac009556881941c60d378e34867cdb2fd00a0 | FilePath ExtensionPrefs::GetExtensionPath(const std::string& extension_id) {
const DictionaryValue* dict = GetExtensionPref(extension_id);
std::string path;
if (!dict->GetString(kPrefPath, &path))
return FilePath();
return install_directory_.Append(FilePath::FromWStringHack(UTF8ToWide(path)));
}
| 1 | CVE-2011-3234 | 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,831 |
linux | fa3a5a1880c91bb92594ad42dfe9eedad7996b86 | static void ml_play_effects(struct ml_device *ml)
{
struct ff_effect effect;
DECLARE_BITMAP(handled_bm, FF_MEMLESS_EFFECTS);
memset(handled_bm, 0, sizeof(handled_bm));
while (ml_get_combo_effect(ml, handled_bm, &effect))
ml->play_effect(ml->dev, ml->private, &effect);
ml_schedule_timer(ml);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,970 |
Chrome | 16dcd30c215801941d9890859fd79a234128fc3e | void DownloadItemImpl::UpdateProgress(int64 bytes_so_far,
const std::string& hash_state) {
hash_state_ = hash_state;
received_bytes_ = bytes_so_far;
if (received_bytes_ > total_bytes_)
total_bytes_ = 0;
if (bound_net_log_.IsLoggingAllEvents()) {
bound_net_log_.AddEvent(
net::NetLog::TYPE_DOWNLOAD_ITEM_UPDATED,
net::NetLog::Int64Callback("bytes_so_far", received_bytes_));
}
}
| 1 | CVE-2012-2895 | 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,738 |
linux | 84d73cd3fb142bf1298a8c13fd4ca50fd2432372 | int rtnl_is_locked(void)
{
return mutex_is_locked(&rtnl_mutex);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,301 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.