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
|
---|---|---|---|---|---|---|---|---|---|
linux | 7ed47b7d142ec99ad6880bbbec51e9f12b3af74c | static int ghash_final(struct shash_desc *desc, u8 *dst)
{
struct ghash_desc_ctx *dctx = shash_desc_ctx(desc);
struct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm);
u8 *buf = dctx->buffer;
ghash_flush(ctx, dctx);
memcpy(dst, buf, GHASH_BLOCK_SIZE);
return 0;
}
| 1 | CVE-2011-4081 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 3,526 |
spice | a4a16ac42d2f19a17e36556546aa94d5cd83745f | int memslot_validate_virt(RedMemSlotInfo *info, unsigned long virt, int slot_id,
uint32_t add_size, uint32_t group_id)
{
MemSlot *slot;
slot = &info->mem_slots[group_id][slot_id];
if ((virt + add_size) < virt) {
spice_critical("virtual address overlap");
return 0;
}
if (virt < slot->virt_start_addr || (virt + add_size) > slot->virt_end_addr) {
print_memslots(info);
spice_warning("virtual address out of range"
" virt=0x%lx+0x%x slot_id=%d group_id=%d\n"
" slot=0x%lx-0x%lx delta=0x%lx",
virt, add_size, slot_id, group_id,
slot->virt_start_addr, slot->virt_end_addr, slot->address_delta);
return 0;
}
return 1;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,293 |
bwa | 20d0a13092aa4cb73230492b05f9697d5ef0b88e | int64_t bns_fasta2bntseq(gzFile fp_fa, const char *prefix, int for_only)
{
extern void seq_reverse(int len, ubyte_t *seq, int is_comp); // in bwaseqio.c
kseq_t *seq;
char name[1024];
bntseq_t *bns;
uint8_t *pac = 0;
int32_t m_seqs, m_holes;
int64_t ret = -1, m_pac, l;
bntamb1_t *q;
FILE *fp;
// initialization
seq = kseq_init(fp_fa);
bns = (bntseq_t*)calloc(1, sizeof(bntseq_t));
bns->seed = 11; // fixed seed for random generator
srand48(bns->seed);
m_seqs = m_holes = 8; m_pac = 0x10000;
bns->anns = (bntann1_t*)calloc(m_seqs, sizeof(bntann1_t));
bns->ambs = (bntamb1_t*)calloc(m_holes, sizeof(bntamb1_t));
pac = calloc(m_pac/4, 1);
q = bns->ambs;
strcpy(name, prefix); strcat(name, ".pac");
fp = xopen(name, "wb");
// read sequences
while (kseq_read(seq) >= 0) pac = add1(seq, bns, pac, &m_pac, &m_seqs, &m_holes, &q);
if (!for_only) { // add the reverse complemented sequence
int64_t ll_pac = (bns->l_pac * 2 + 3) / 4 * 4;
if (ll_pac > m_pac) pac = realloc(pac, ll_pac/4);
memset(pac + (bns->l_pac+3)/4, 0, (ll_pac - (bns->l_pac+3)/4*4) / 4);
for (l = bns->l_pac - 1; l >= 0; --l, ++bns->l_pac)
_set_pac(pac, bns->l_pac, 3-_get_pac(pac, l));
}
ret = bns->l_pac;
{ // finalize .pac file
ubyte_t ct;
err_fwrite(pac, 1, (bns->l_pac>>2) + ((bns->l_pac&3) == 0? 0 : 1), fp);
// the following codes make the pac file size always (l_pac/4+1+1)
if (bns->l_pac % 4 == 0) {
ct = 0;
err_fwrite(&ct, 1, 1, fp);
}
ct = bns->l_pac % 4;
err_fwrite(&ct, 1, 1, fp);
// close .pac file
err_fflush(fp);
err_fclose(fp);
}
bns_dump(bns, prefix);
bns_destroy(bns);
kseq_destroy(seq);
free(pac);
return ret;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,107 |
linux | 307f2fb95e9b96b3577916e73d92e104f8f26494 | int fib6_add(struct fib6_node *root, struct rt6_info *rt, struct nl_info *info)
{
struct fib6_node *fn, *pn = NULL;
int err = -ENOMEM;
int allow_create = 1;
int replace_required = 0;
if (info->nlh) {
if (!(info->nlh->nlmsg_flags & NLM_F_CREATE))
allow_create = 0;
if (info->nlh->nlmsg_flags & NLM_F_REPLACE)
replace_required = 1;
}
if (!allow_create && !replace_required)
pr_warn("RTM_NEWROUTE with no NLM_F_CREATE or NLM_F_REPLACE\n");
fn = fib6_add_1(root, &rt->rt6i_dst.addr, sizeof(struct in6_addr),
rt->rt6i_dst.plen, offsetof(struct rt6_info, rt6i_dst),
allow_create, replace_required);
if (IS_ERR(fn)) {
err = PTR_ERR(fn);
goto out;
}
pn = fn;
#ifdef CONFIG_IPV6_SUBTREES
if (rt->rt6i_src.plen) {
struct fib6_node *sn;
if (!fn->subtree) {
struct fib6_node *sfn;
/*
* Create subtree.
*
* fn[main tree]
* |
* sfn[subtree root]
* \
* sn[new leaf node]
*/
/* Create subtree root node */
sfn = node_alloc();
if (!sfn)
goto st_failure;
sfn->leaf = info->nl_net->ipv6.ip6_null_entry;
atomic_inc(&info->nl_net->ipv6.ip6_null_entry->rt6i_ref);
sfn->fn_flags = RTN_ROOT;
sfn->fn_sernum = fib6_new_sernum();
/* Now add the first leaf node to new subtree */
sn = fib6_add_1(sfn, &rt->rt6i_src.addr,
sizeof(struct in6_addr), rt->rt6i_src.plen,
offsetof(struct rt6_info, rt6i_src),
allow_create, replace_required);
if (IS_ERR(sn)) {
/* If it is failed, discard just allocated
root, and then (in st_failure) stale node
in main tree.
*/
node_free(sfn);
err = PTR_ERR(sn);
goto st_failure;
}
/* Now link new subtree to main tree */
sfn->parent = fn;
fn->subtree = sfn;
} else {
sn = fib6_add_1(fn->subtree, &rt->rt6i_src.addr,
sizeof(struct in6_addr), rt->rt6i_src.plen,
offsetof(struct rt6_info, rt6i_src),
allow_create, replace_required);
if (IS_ERR(sn)) {
err = PTR_ERR(sn);
goto st_failure;
}
}
if (!fn->leaf) {
fn->leaf = rt;
atomic_inc(&rt->rt6i_ref);
}
fn = sn;
}
#endif
err = fib6_add_rt2node(fn, rt, info);
if (!err) {
fib6_start_gc(info->nl_net, rt);
if (!(rt->rt6i_flags & RTF_CACHE))
fib6_prune_clones(info->nl_net, pn, rt);
}
out:
if (err) {
#ifdef CONFIG_IPV6_SUBTREES
/*
* If fib6_add_1 has cleared the old leaf pointer in the
* super-tree leaf node we have to find a new one for it.
*/
if (pn != fn && pn->leaf == rt) {
pn->leaf = NULL;
atomic_dec(&rt->rt6i_ref);
}
if (pn != fn && !pn->leaf && !(pn->fn_flags & RTN_RTINFO)) {
pn->leaf = fib6_find_prefix(info->nl_net, pn);
#if RT6_DEBUG >= 2
if (!pn->leaf) {
WARN_ON(pn->leaf == NULL);
pn->leaf = info->nl_net->ipv6.ip6_null_entry;
}
#endif
atomic_inc(&pn->leaf->rt6i_ref);
}
#endif
dst_free(&rt->dst);
}
return err;
#ifdef CONFIG_IPV6_SUBTREES
/* Subtree creation failed, probably main tree node
is orphan. If it is, shoot it.
*/
st_failure:
if (fn && !(fn->fn_flags & (RTN_RTINFO|RTN_ROOT)))
fib6_repair_tree(info->nl_net, fn);
dst_free(&rt->dst);
return err;
#endif
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,984 |
Android | 3cb1b6944e776863aea316e25fdc16d7f9962902 | void OMXNodeInstance::invalidateBufferID(OMX::buffer_id buffer __unused) {
}
| 1 | CVE-2015-3835 | 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,527 |
opencv | 5691d998ead1d9b0542bcfced36c2dceb3a59023 | bool parse( char* ptr )
{
bool first = true;
bool ok = true;
FileNode root_collection(fs->getFS(), 0, 0);
for(;;)
{
// 0. skip leading comments and directives and ...
// 1. reach the first item
for(;;)
{
ptr = skipSpaces( ptr, 0, INT_MAX );
if( !ptr || *ptr == '\0' )
{
ok = !first;
break;
}
if( *ptr == '%' )
{
if( memcmp( ptr, "%YAML", 5 ) == 0 &&
memcmp( ptr, "%YAML:1.", 8 ) != 0 &&
memcmp( ptr, "%YAML 1.", 8 ) != 0)
CV_PARSE_ERROR_CPP( "Unsupported YAML version (it must be 1.x)" );
*ptr = '\0';
}
else if( *ptr == '-' )
{
if( memcmp(ptr, "---", 3) == 0 )
{
ptr += 3;
break;
}
else if( first )
break;
}
else if( cv_isalnum(*ptr) || *ptr=='_')
{
if( !first )
CV_PARSE_ERROR_CPP( "The YAML streams must start with '---', except the first one" );
break;
}
else if( fs->eof() )
break;
else
CV_PARSE_ERROR_CPP( "Invalid or unsupported syntax" );
}
if( ptr )
ptr = skipSpaces( ptr, 0, INT_MAX );
if( !ptr || !ptr[0] )
break;
if( memcmp( ptr, "...", 3 ) != 0 )
{
// 2. parse the collection
FileNode root_node = fs->addNode(root_collection, std::string(), FileNode::NONE);
ptr = parseValue( ptr, root_node, 0, false );
if( !root_node.isMap() && !root_node.isSeq() )
CV_PARSE_ERROR_CPP( "Only collections as YAML streams are supported by this parser" );
// 3. parse until the end of file or next collection
ptr = skipSpaces( ptr, 0, INT_MAX );
if( !ptr )
break;
}
if( fs->eof() )
break;
ptr += 3;
first = false;
}
return ok;
} | 1 | CVE-2019-14493 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 5,577 |
Chrome | 73edae623529f04c668268de49d00324b96166a2 | void HTMLElement::collectStyleForAttribute(const Attribute& attribute, StylePropertySet* style)
{
if (attribute.name() == alignAttr) {
if (equalIgnoringCase(attribute.value(), "middle"))
addPropertyToAttributeStyle(style, CSSPropertyTextAlign, CSSValueCenter);
else
addPropertyToAttributeStyle(style, CSSPropertyTextAlign, attribute.value());
} else if (attribute.name() == contenteditableAttr) {
if (attribute.isEmpty() || equalIgnoringCase(attribute.value(), "true")) {
addPropertyToAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadWrite);
addPropertyToAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
addPropertyToAttributeStyle(style, CSSPropertyWebkitNbspMode, CSSValueSpace);
addPropertyToAttributeStyle(style, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
} else if (equalIgnoringCase(attribute.value(), "plaintext-only")) {
addPropertyToAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadWritePlaintextOnly);
addPropertyToAttributeStyle(style, CSSPropertyWordWrap, CSSValueBreakWord);
addPropertyToAttributeStyle(style, CSSPropertyWebkitNbspMode, CSSValueSpace);
addPropertyToAttributeStyle(style, CSSPropertyWebkitLineBreak, CSSValueAfterWhiteSpace);
} else if (equalIgnoringCase(attribute.value(), "false"))
addPropertyToAttributeStyle(style, CSSPropertyWebkitUserModify, CSSValueReadOnly);
} else if (attribute.name() == hiddenAttr) {
addPropertyToAttributeStyle(style, CSSPropertyDisplay, CSSValueNone);
} else if (attribute.name() == draggableAttr) {
if (equalIgnoringCase(attribute.value(), "true")) {
addPropertyToAttributeStyle(style, CSSPropertyWebkitUserDrag, CSSValueElement);
addPropertyToAttributeStyle(style, CSSPropertyWebkitUserSelect, CSSValueNone);
} else if (equalIgnoringCase(attribute.value(), "false"))
addPropertyToAttributeStyle(style, CSSPropertyWebkitUserDrag, CSSValueNone);
} else if (attribute.name() == dirAttr) {
if (equalIgnoringCase(attribute.value(), "auto"))
addPropertyToAttributeStyle(style, CSSPropertyUnicodeBidi, unicodeBidiAttributeForDirAuto(this));
else {
addPropertyToAttributeStyle(style, CSSPropertyDirection, attribute.value());
if (!hasTagName(bdiTag) && !hasTagName(bdoTag) && !hasTagName(outputTag))
addPropertyToAttributeStyle(style, CSSPropertyUnicodeBidi, CSSValueEmbed);
}
} else if (attribute.name().matches(XMLNames::langAttr)) {
mapLanguageAttributeToLocale(attribute, style);
} else if (attribute.name() == langAttr) {
if (!fastHasAttribute(XMLNames::langAttr))
mapLanguageAttributeToLocale(attribute, style);
} else
StyledElement::collectStyleForAttribute(attribute, style);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,445 |
linux | f2fcfcd670257236ebf2088bbdf26f6a8ef459fe | static void l2cap_do_start(struct sock *sk)
{
struct l2cap_conn *conn = l2cap_pi(sk)->conn;
if (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT) {
if (!(conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE))
return;
if (l2cap_check_security(sk)) {
struct l2cap_conn_req req;
req.scid = cpu_to_le16(l2cap_pi(sk)->scid);
req.psm = l2cap_pi(sk)->psm;
l2cap_pi(sk)->ident = l2cap_get_ident(conn);
l2cap_send_cmd(conn, l2cap_pi(sk)->ident,
L2CAP_CONN_REQ, sizeof(req), &req);
}
} else {
struct l2cap_info_req req;
req.type = cpu_to_le16(L2CAP_IT_FEAT_MASK);
conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_SENT;
conn->info_ident = l2cap_get_ident(conn);
mod_timer(&conn->info_timer, jiffies +
msecs_to_jiffies(L2CAP_INFO_TIMEOUT));
l2cap_send_cmd(conn, conn->info_ident,
L2CAP_INFO_REQ, sizeof(req), &req);
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,488 |
tor | 43414eb98821d3b5c6c65181d7545ce938f82c8e | addr_policy_permits_tor_addr(const tor_addr_t *addr, uint16_t port,
smartlist_t *policy)
{
addr_policy_result_t p;
p = compare_tor_addr_to_addr_policy(addr, port, policy);
switch (p) {
case ADDR_POLICY_PROBABLY_ACCEPTED:
case ADDR_POLICY_ACCEPTED:
return 1;
case ADDR_POLICY_PROBABLY_REJECTED:
case ADDR_POLICY_REJECTED:
return 0;
default:
log_warn(LD_BUG, "Unexpected result: %d", (int)p);
return 0;
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,591 |
samba | ec504dbf69636a554add1f3d5703dd6c3ad450b8 | static int ldb_match_equality(struct ldb_context *ldb,
const struct ldb_message *msg,
const struct ldb_parse_tree *tree,
enum ldb_scope scope,
bool *matched)
{
unsigned int i;
struct ldb_message_element *el;
const struct ldb_schema_attribute *a;
struct ldb_dn *valuedn;
int ret;
if (ldb_attr_dn(tree->u.equality.attr) == 0) {
valuedn = ldb_dn_from_ldb_val(ldb, ldb, &tree->u.equality.value);
if (valuedn == NULL) {
return LDB_ERR_INVALID_DN_SYNTAX;
}
ret = ldb_dn_compare(msg->dn, valuedn);
talloc_free(valuedn);
*matched = (ret == 0);
return LDB_SUCCESS;
}
/* TODO: handle the "*" case derived from an extended search
operation without the attibute type defined */
el = ldb_msg_find_element(msg, tree->u.equality.attr);
if (el == NULL) {
*matched = false;
return LDB_SUCCESS;
}
a = ldb_schema_attribute_by_name(ldb, el->name);
if (a == NULL) {
return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
}
for (i=0;i<el->num_values;i++) {
if (a->syntax->operator_fn) {
ret = a->syntax->operator_fn(ldb, LDB_OP_EQUALITY, a,
&tree->u.equality.value, &el->values[i], matched);
if (ret != LDB_SUCCESS) return ret;
if (*matched) return LDB_SUCCESS;
} else {
if (a->syntax->comparison_fn(ldb, ldb, &tree->u.equality.value,
&el->values[i]) == 0) {
*matched = true;
return LDB_SUCCESS;
}
}
}
*matched = false;
return LDB_SUCCESS;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,719 |
Android | 04839626ed859623901ebd3a5fd483982186b59d | long Track::GetType() const
{
return m_info.type;
}
| 1 | CVE-2016-1621 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 7,227 |
linux | 2ca39528c01a933f6689cd6505ce65bd6d68a530 | static int do_tkill(pid_t tgid, pid_t pid, int sig)
{
struct siginfo info;
info.si_signo = sig;
info.si_errno = 0;
info.si_code = SI_TKILL;
info.si_pid = task_tgid_vnr(current);
info.si_uid = from_kuid_munged(current_user_ns(), current_uid());
return do_send_specific(tgid, pid, sig, &info);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,608 |
qemu | a7278b36fcab9af469563bd7b9dadebe2ae25e48 | static inline void vmxnet3_ring_write_curr_cell(Vmxnet3Ring *ring, void *buff)
{
vmw_shmem_write(vmxnet3_ring_curr_cell_pa(ring), buff, ring->cell_size);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,421 |
linux | b71812168571fa55e44cdd0254471331b9c4c4c6 | unsigned int ebt_do_table(struct sk_buff *skb,
const struct nf_hook_state *state,
struct ebt_table *table)
{
unsigned int hook = state->hook;
int i, nentries;
struct ebt_entry *point;
struct ebt_counter *counter_base, *cb_base;
const struct ebt_entry_target *t;
int verdict, sp = 0;
struct ebt_chainstack *cs;
struct ebt_entries *chaininfo;
const char *base;
const struct ebt_table_info *private;
struct xt_action_param acpar;
acpar.state = state;
acpar.hotdrop = false;
read_lock_bh(&table->lock);
private = table->private;
cb_base = COUNTER_BASE(private->counters, private->nentries,
smp_processor_id());
if (private->chainstack)
cs = private->chainstack[smp_processor_id()];
else
cs = NULL;
chaininfo = private->hook_entry[hook];
nentries = private->hook_entry[hook]->nentries;
point = (struct ebt_entry *)(private->hook_entry[hook]->data);
counter_base = cb_base + private->hook_entry[hook]->counter_offset;
/* base for chain jumps */
base = private->entries;
i = 0;
while (i < nentries) {
if (ebt_basic_match(point, skb, state->in, state->out))
goto letscontinue;
if (EBT_MATCH_ITERATE(point, ebt_do_match, skb, &acpar) != 0)
goto letscontinue;
if (acpar.hotdrop) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
/* increase counter */
(*(counter_base + i)).pcnt++;
(*(counter_base + i)).bcnt += skb->len;
/* these should only watch: not modify, nor tell us
* what to do with the packet
*/
EBT_WATCHER_ITERATE(point, ebt_do_watcher, skb, &acpar);
t = (struct ebt_entry_target *)
(((char *)point) + point->target_offset);
/* standard target */
if (!t->u.target->target)
verdict = ((struct ebt_standard_target *)t)->verdict;
else {
acpar.target = t->u.target;
acpar.targinfo = t->data;
verdict = t->u.target->target(skb, &acpar);
}
if (verdict == EBT_ACCEPT) {
read_unlock_bh(&table->lock);
return NF_ACCEPT;
}
if (verdict == EBT_DROP) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
if (verdict == EBT_RETURN) {
letsreturn:
if (WARN(sp == 0, "RETURN on base chain")) {
/* act like this is EBT_CONTINUE */
goto letscontinue;
}
sp--;
/* put all the local variables right */
i = cs[sp].n;
chaininfo = cs[sp].chaininfo;
nentries = chaininfo->nentries;
point = cs[sp].e;
counter_base = cb_base +
chaininfo->counter_offset;
continue;
}
if (verdict == EBT_CONTINUE)
goto letscontinue;
if (WARN(verdict < 0, "bogus standard verdict\n")) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
/* jump to a udc */
cs[sp].n = i + 1;
cs[sp].chaininfo = chaininfo;
cs[sp].e = ebt_next_entry(point);
i = 0;
chaininfo = (struct ebt_entries *) (base + verdict);
if (WARN(chaininfo->distinguisher, "jump to non-chain\n")) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
nentries = chaininfo->nentries;
point = (struct ebt_entry *)chaininfo->data;
counter_base = cb_base + chaininfo->counter_offset;
sp++;
continue;
letscontinue:
point = ebt_next_entry(point);
i++;
}
/* I actually like this :) */
if (chaininfo->policy == EBT_RETURN)
goto letsreturn;
if (chaininfo->policy == EBT_ACCEPT) {
read_unlock_bh(&table->lock);
return NF_ACCEPT;
}
read_unlock_bh(&table->lock);
return NF_DROP;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,890 |
Android | 1f24c730ab6ca5aff1e3137b340b8aeaeda4bdbc | status_t StreamingProcessor::processRecordingFrame() {
ATRACE_CALL();
status_t res;
sp<Camera2Heap> recordingHeap;
size_t heapIdx = 0;
nsecs_t timestamp;
sp<Camera2Client> client = mClient.promote();
if (client == 0) {
BufferItem imgBuffer;
res = mRecordingConsumer->acquireBuffer(&imgBuffer, 0);
if (res != OK) {
if (res != BufferItemConsumer::NO_BUFFER_AVAILABLE) {
ALOGE("%s: Camera %d: Can't acquire recording buffer: %s (%d)",
__FUNCTION__, mId, strerror(-res), res);
}
return res;
}
mRecordingConsumer->releaseBuffer(imgBuffer);
return OK;
}
{
/* acquire SharedParameters before mMutex so we don't dead lock
with Camera2Client code calling into StreamingProcessor */
SharedParameters::Lock l(client->getParameters());
Mutex::Autolock m(mMutex);
BufferItem imgBuffer;
res = mRecordingConsumer->acquireBuffer(&imgBuffer, 0);
if (res != OK) {
if (res != BufferItemConsumer::NO_BUFFER_AVAILABLE) {
ALOGE("%s: Camera %d: Can't acquire recording buffer: %s (%d)",
__FUNCTION__, mId, strerror(-res), res);
}
return res;
}
timestamp = imgBuffer.mTimestamp;
mRecordingFrameCount++;
ALOGVV("OnRecordingFrame: Frame %d", mRecordingFrameCount);
if (l.mParameters.state != Parameters::RECORD &&
l.mParameters.state != Parameters::VIDEO_SNAPSHOT) {
ALOGV("%s: Camera %d: Discarding recording image buffers "
"received after recording done", __FUNCTION__,
mId);
mRecordingConsumer->releaseBuffer(imgBuffer);
return INVALID_OPERATION;
}
if (mRecordingHeap == 0) {
size_t payloadSize = sizeof(VideoNativeMetadata);
ALOGV("%s: Camera %d: Creating recording heap with %zu buffers of "
"size %zu bytes", __FUNCTION__, mId,
mRecordingHeapCount, payloadSize);
mRecordingHeap = new Camera2Heap(payloadSize, mRecordingHeapCount,
"Camera2Client::RecordingHeap");
if (mRecordingHeap->mHeap->getSize() == 0) {
ALOGE("%s: Camera %d: Unable to allocate memory for recording",
__FUNCTION__, mId);
mRecordingConsumer->releaseBuffer(imgBuffer);
return NO_MEMORY;
}
for (size_t i = 0; i < mRecordingBuffers.size(); i++) {
if (mRecordingBuffers[i].mBuf !=
BufferItemConsumer::INVALID_BUFFER_SLOT) {
ALOGE("%s: Camera %d: Non-empty recording buffers list!",
__FUNCTION__, mId);
}
}
mRecordingBuffers.clear();
mRecordingBuffers.setCapacity(mRecordingHeapCount);
mRecordingBuffers.insertAt(0, mRecordingHeapCount);
mRecordingHeapHead = 0;
mRecordingHeapFree = mRecordingHeapCount;
}
if (mRecordingHeapFree == 0) {
ALOGE("%s: Camera %d: No free recording buffers, dropping frame",
__FUNCTION__, mId);
mRecordingConsumer->releaseBuffer(imgBuffer);
return NO_MEMORY;
}
heapIdx = mRecordingHeapHead;
mRecordingHeapHead = (mRecordingHeapHead + 1) % mRecordingHeapCount;
mRecordingHeapFree--;
ALOGVV("%s: Camera %d: Timestamp %lld",
__FUNCTION__, mId, timestamp);
ssize_t offset;
size_t size;
sp<IMemoryHeap> heap =
mRecordingHeap->mBuffers[heapIdx]->getMemory(&offset,
&size);
VideoNativeMetadata *payload = reinterpret_cast<VideoNativeMetadata*>(
(uint8_t*)heap->getBase() + offset);
payload->eType = kMetadataBufferTypeANWBuffer;
payload->pBuffer = imgBuffer.mGraphicBuffer->getNativeBuffer();
payload->nFenceFd = -1;
ALOGVV("%s: Camera %d: Sending out ANWBuffer %p",
__FUNCTION__, mId, payload->pBuffer);
mRecordingBuffers.replaceAt(imgBuffer, heapIdx);
recordingHeap = mRecordingHeap;
}
Camera2Client::SharedCameraCallbacks::Lock l(client->mSharedCameraCallbacks);
if (l.mRemoteCallback != 0) {
l.mRemoteCallback->dataCallbackTimestamp(timestamp,
CAMERA_MSG_VIDEO_FRAME,
recordingHeap->mBuffers[heapIdx]);
} else {
ALOGW("%s: Camera %d: Remote callback gone", __FUNCTION__, mId);
}
return OK;
}
| 1 | CVE-2016-3834 | 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. | 3,722 |
vim | 78d52883e10d71f23ab72a3d8b9733b00da8c9ad | paragraph_start(linenr_T lnum)
{
char_u *p;
int leader_len = 0; // leader len of current line
char_u *leader_flags = NULL; // flags for leader of current line
int next_leader_len; // leader len of next line
char_u *next_leader_flags; // flags for leader of next line
int do_comments; // format comments
if (lnum <= 1)
return TRUE; // start of the file
p = ml_get(lnum - 1);
if (*p == NUL)
return TRUE; // after empty line
do_comments = has_format_option(FO_Q_COMS);
if (fmt_check_par(lnum - 1, &leader_len, &leader_flags, do_comments))
return TRUE; // after non-paragraph line
if (fmt_check_par(lnum, &next_leader_len, &next_leader_flags, do_comments))
return TRUE; // "lnum" is not a paragraph line
if (has_format_option(FO_WHITE_PAR) && !ends_in_white(lnum - 1))
return TRUE; // missing trailing space in previous line.
if (has_format_option(FO_Q_NUMBER) && (get_number_indent(lnum) > 0))
return TRUE; // numbered item starts in "lnum".
if (!same_leader(lnum - 1, leader_len, leader_flags,
next_leader_len, next_leader_flags))
return TRUE; // change of comment leader.
return FALSE;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,759 |
linux | 9c895160d25a76c21b65bad141b08e8d4f99afef | static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
{
return kvm_x86_ops->get_segment_base(vcpu, seg);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,927 |
php | 6dedeb40db13971af45276f80b5375030aa7e76f | int phar_detect_phar_fname_ext(const char *filename, int filename_len, const char **ext_str, int *ext_len, int executable, int for_create, int is_complete TSRMLS_DC) /* {{{ */
{
const char *pos, *slash;
*ext_str = NULL;
*ext_len = 0;
if (!filename_len || filename_len == 1) {
return FAILURE;
}
phar_request_initialize(TSRMLS_C);
/* first check for alias in first segment */
pos = memchr(filename, '/', filename_len);
if (pos && pos != filename) {
/* check for url like http:// or phar:// */
if (*(pos - 1) == ':' && (pos - filename) < filename_len - 1 && *(pos + 1) == '/') {
*ext_len = -2;
*ext_str = NULL;
return FAILURE;
}
if (zend_hash_exists(&(PHAR_GLOBALS->phar_alias_map), (char *) filename, pos - filename)) {
*ext_str = pos;
*ext_len = -1;
return FAILURE;
}
if (PHAR_G(manifest_cached) && zend_hash_exists(&cached_alias, (char *) filename, pos - filename)) {
*ext_str = pos;
*ext_len = -1;
return FAILURE;
}
}
if (zend_hash_num_elements(&(PHAR_GLOBALS->phar_fname_map)) || PHAR_G(manifest_cached)) {
phar_archive_data **pphar;
if (is_complete) {
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), (char *) filename, filename_len, (void **)&pphar)) {
*ext_str = filename + (filename_len - (*pphar)->ext_len);
woohoo:
*ext_len = (*pphar)->ext_len;
if (executable == 2) {
return SUCCESS;
}
if (executable == 1 && !(*pphar)->is_data) {
return SUCCESS;
}
if (!executable && (*pphar)->is_data) {
return SUCCESS;
}
return FAILURE;
}
if (PHAR_G(manifest_cached) && SUCCESS == zend_hash_find(&cached_phars, (char *) filename, filename_len, (void **)&pphar)) {
*ext_str = filename + (filename_len - (*pphar)->ext_len);
goto woohoo;
}
} else {
phar_zstr key;
char *str_key;
uint keylen;
ulong unused;
zend_hash_internal_pointer_reset(&(PHAR_GLOBALS->phar_fname_map));
while (FAILURE != zend_hash_has_more_elements(&(PHAR_GLOBALS->phar_fname_map))) {
if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&(PHAR_GLOBALS->phar_fname_map), &key, &keylen, &unused, 0, NULL)) {
break;
}
PHAR_STR(key, str_key);
if (keylen > (uint) filename_len) {
zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map));
PHAR_STR_FREE(str_key);
continue;
}
if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen
|| filename[keylen] == '/' || filename[keylen] == '\0')) {
PHAR_STR_FREE(str_key);
if (FAILURE == zend_hash_get_current_data(&(PHAR_GLOBALS->phar_fname_map), (void **) &pphar)) {
break;
}
*ext_str = filename + (keylen - (*pphar)->ext_len);
goto woohoo;
}
PHAR_STR_FREE(str_key);
zend_hash_move_forward(&(PHAR_GLOBALS->phar_fname_map));
}
if (PHAR_G(manifest_cached)) {
zend_hash_internal_pointer_reset(&cached_phars);
while (FAILURE != zend_hash_has_more_elements(&cached_phars)) {
if (HASH_KEY_NON_EXISTANT == zend_hash_get_current_key_ex(&cached_phars, &key, &keylen, &unused, 0, NULL)) {
break;
}
PHAR_STR(key, str_key);
if (keylen > (uint) filename_len) {
zend_hash_move_forward(&cached_phars);
PHAR_STR_FREE(str_key);
continue;
}
if (!memcmp(filename, str_key, keylen) && ((uint)filename_len == keylen
|| filename[keylen] == '/' || filename[keylen] == '\0')) {
PHAR_STR_FREE(str_key);
if (FAILURE == zend_hash_get_current_data(&cached_phars, (void **) &pphar)) {
break;
}
*ext_str = filename + (keylen - (*pphar)->ext_len);
goto woohoo;
}
PHAR_STR_FREE(str_key);
zend_hash_move_forward(&cached_phars);
}
}
}
}
pos = memchr(filename + 1, '.', filename_len);
next_extension:
if (!pos) {
return FAILURE;
}
while (pos != filename && (*(pos - 1) == '/' || *(pos - 1) == '\0')) {
pos = memchr(pos + 1, '.', filename_len - (pos - filename) + 1);
if (!pos) {
return FAILURE;
}
}
slash = memchr(pos, '/', filename_len - (pos - filename));
if (!slash) {
/* this is a url like "phar://blah.phar" with no directory */
*ext_str = pos;
*ext_len = strlen(pos);
/* file extension must contain "phar" */
switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) {
case SUCCESS:
return SUCCESS;
case FAILURE:
/* we are at the end of the string, so we fail */
return FAILURE;
}
}
/* we've found an extension that ends at a directory separator */
*ext_str = pos;
*ext_len = slash - pos;
switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create TSRMLS_CC)) {
case SUCCESS:
return SUCCESS;
case FAILURE:
/* look for more extensions */
pos = strchr(pos + 1, '.');
if (pos) {
*ext_str = NULL;
*ext_len = 0;
}
goto next_extension;
}
return FAILURE;
}
/* }}} */
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,572 |
Chrome | 1777aa6484af15014b8691082a8c3075418786f5 | void LayerTreeHostQt::setRootCompositingLayer(WebCore::GraphicsLayer* graphicsLayer)
{
m_nonCompositedContentLayer->removeAllChildren();
if (graphicsLayer)
m_nonCompositedContentLayer->addChild(graphicsLayer);
}
| 1 | CVE-2011-1800 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 2,386 |
FFmpeg | 9807d3976be0e92e4ece3b4b1701be894cd7c2e1 | static int64_t pva_read_timestamp(struct AVFormatContext *s, int stream_index,
int64_t *pos, int64_t pos_limit) {
AVIOContext *pb = s->pb;
PVAContext *pvactx = s->priv_data;
int length, streamid;
int64_t res = AV_NOPTS_VALUE;
pos_limit = FFMIN(*pos+PVA_MAX_PAYLOAD_LENGTH*8, (uint64_t)*pos+pos_limit);
while (*pos < pos_limit) {
res = AV_NOPTS_VALUE;
avio_seek(pb, *pos, SEEK_SET);
pvactx->continue_pes = 0;
if (read_part_of_packet(s, &res, &length, &streamid, 0)) {
(*pos)++;
continue;
}
if (streamid - 1 != stream_index || res == AV_NOPTS_VALUE) {
*pos = avio_tell(pb) + length;
continue;
}
break;
}
pvactx->continue_pes = 0;
return res;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,116 |
server | b3c3291f0b7c1623cb20663f7cf31b7f749768bc | bool open_table(THD *thd, TABLE_LIST *table_list, Open_table_context *ot_ctx)
{
TABLE *table;
const char *key;
uint key_length;
const char *alias= table_list->alias.str;
uint flags= ot_ctx->get_flags();
MDL_ticket *mdl_ticket;
TABLE_SHARE *share;
uint gts_flags;
bool from_share= false;
#ifdef WITH_PARTITION_STORAGE_ENGINE
int part_names_error=0;
#endif
DBUG_ENTER("open_table");
/*
The table must not be opened already. The table can be pre-opened for
some statements if it is a temporary table.
open_temporary_table() must be used to open temporary tables.
*/
DBUG_ASSERT(!table_list->table);
/* an open table operation needs a lot of the stack space */
if (check_stack_overrun(thd, STACK_MIN_SIZE_FOR_OPEN, (uchar *)&alias))
DBUG_RETURN(TRUE);
if (!(flags & MYSQL_OPEN_IGNORE_KILLED) && thd->killed)
{
thd->send_kill_message();
DBUG_RETURN(TRUE);
}
/*
Check if we're trying to take a write lock in a read only transaction.
Note that we allow write locks on log tables as otherwise logging
to general/slow log would be disabled in read only transactions.
*/
if (table_list->mdl_request.is_write_lock_request() &&
thd->tx_read_only &&
!(flags & (MYSQL_LOCK_LOG_TABLE | MYSQL_OPEN_HAS_MDL_LOCK)))
{
my_error(ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION, MYF(0));
DBUG_RETURN(true);
}
if (!table_list->db.str)
{
my_error(ER_NO_DB_ERROR, MYF(0));
DBUG_RETURN(true);
}
key_length= get_table_def_key(table_list, &key);
/*
If we're in pre-locked or LOCK TABLES mode, let's try to find the
requested table in the list of pre-opened and locked tables. If the
table is not there, return an error - we can't open not pre-opened
tables in pre-locked/LOCK TABLES mode.
TODO: move this block into a separate function.
*/
if (thd->locked_tables_mode &&
! (flags & MYSQL_OPEN_GET_NEW_TABLE))
{ // Using table locks
TABLE *best_table= 0;
int best_distance= INT_MIN;
for (table=thd->open_tables; table ; table=table->next)
{
if (table->s->table_cache_key.length == key_length &&
!memcmp(table->s->table_cache_key.str, key, key_length))
{
if (!my_strcasecmp(system_charset_info, table->alias.c_ptr(), alias) &&
table->query_id != thd->query_id && /* skip tables already used */
(thd->locked_tables_mode == LTM_LOCK_TABLES ||
table->query_id == 0))
{
int distance= ((int) table->reginfo.lock_type -
(int) table_list->lock_type);
/*
Find a table that either has the exact lock type requested,
or has the best suitable lock. In case there is no locked
table that has an equal or higher lock than requested,
we us the closest matching lock to be able to produce an error
message about wrong lock mode on the table. The best_table
is changed if bd < 0 <= d or bd < d < 0 or 0 <= d < bd.
distance < 0 - No suitable lock found
distance > 0 - we have lock mode higher then we require
distance == 0 - we have lock mode exactly which we need
*/
if ((best_distance < 0 && distance > best_distance) ||
(distance >= 0 && distance < best_distance))
{
best_distance= distance;
best_table= table;
if (best_distance == 0)
{
/*
We have found a perfect match and can finish iterating
through open tables list. Check for table use conflict
between calling statement and SP/trigger is done in
lock_tables().
*/
break;
}
}
}
}
}
if (best_table)
{
table= best_table;
table->query_id= thd->query_id;
table->init(thd, table_list);
DBUG_PRINT("info",("Using locked table"));
#ifdef WITH_PARTITION_STORAGE_ENGINE
part_names_error= set_partitions_as_used(table_list, table);
#endif
goto reset;
}
if (is_locked_view(thd, table_list))
{
if (table_list->sequence)
{
my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str, table_list->alias.str);
DBUG_RETURN(true);
}
DBUG_RETURN(FALSE); // VIEW
}
/*
No table in the locked tables list. In case of explicit LOCK TABLES
this can happen if a user did not include the table into the list.
In case of pre-locked mode locked tables list is generated automatically,
so we may only end up here if the table did not exist when
locked tables list was created.
*/
if (thd->locked_tables_mode == LTM_PRELOCKED)
my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db.str, table_list->alias.str);
else
my_error(ER_TABLE_NOT_LOCKED, MYF(0), alias);
DBUG_RETURN(TRUE);
}
/*
Non pre-locked/LOCK TABLES mode, and the table is not temporary.
This is the normal use case.
*/
if (! (flags & MYSQL_OPEN_HAS_MDL_LOCK))
{
/*
We are not under LOCK TABLES and going to acquire write-lock/
modify the base table. We need to acquire protection against
global read lock until end of this statement in order to have
this statement blocked by active FLUSH TABLES WITH READ LOCK.
We don't need to acquire this protection under LOCK TABLES as
such protection already acquired at LOCK TABLES time and
not released until UNLOCK TABLES.
We don't block statements which modify only temporary tables
as these tables are not preserved by any form of
backup which uses FLUSH TABLES WITH READ LOCK.
TODO: The fact that we sometimes acquire protection against
GRL only when we encounter table to be write-locked
slightly increases probability of deadlock.
This problem will be solved once Alik pushes his
temporary table refactoring patch and we can start
pre-acquiring metadata locks at the beggining of
open_tables() call.
*/
if (table_list->mdl_request.is_write_lock_request() &&
! (flags & (MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK |
MYSQL_OPEN_FORCE_SHARED_MDL |
MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL |
MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK)) &&
! ot_ctx->has_protection_against_grl())
{
MDL_request protection_request;
MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);
if (thd->global_read_lock.can_acquire_protection())
DBUG_RETURN(TRUE);
protection_request.init(MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE,
MDL_STATEMENT);
/*
Install error handler which if possible will convert deadlock error
into request to back-off and restart process of opening tables.
*/
thd->push_internal_handler(&mdl_deadlock_handler);
bool result= thd->mdl_context.acquire_lock(&protection_request,
ot_ctx->get_timeout());
thd->pop_internal_handler();
if (result)
DBUG_RETURN(TRUE);
ot_ctx->set_has_protection_against_grl();
}
if (open_table_get_mdl_lock(thd, ot_ctx, &table_list->mdl_request,
flags, &mdl_ticket) ||
mdl_ticket == NULL)
{
DEBUG_SYNC(thd, "before_open_table_wait_refresh");
DBUG_RETURN(TRUE);
}
DEBUG_SYNC(thd, "after_open_table_mdl_shared");
}
else
{
/*
Grab reference to the MDL lock ticket that was acquired
by the caller.
*/
mdl_ticket= table_list->mdl_request.ticket;
}
if (table_list->open_strategy == TABLE_LIST::OPEN_IF_EXISTS)
{
if (!ha_table_exists(thd, &table_list->db, &table_list->table_name))
DBUG_RETURN(FALSE);
}
else if (table_list->open_strategy == TABLE_LIST::OPEN_STUB)
DBUG_RETURN(FALSE);
/* Table exists. Let us try to open it. */
if (table_list->i_s_requested_object & OPEN_TABLE_ONLY)
gts_flags= GTS_TABLE;
else if (table_list->i_s_requested_object & OPEN_VIEW_ONLY)
gts_flags= GTS_VIEW;
else
gts_flags= GTS_TABLE | GTS_VIEW;
retry_share:
share= tdc_acquire_share(thd, table_list, gts_flags, &table);
if (unlikely(!share))
{
/*
Hide "Table doesn't exist" errors if the table belongs to a view.
The check for thd->is_error() is necessary to not push an
unwanted error in case the error was already silenced.
@todo Rework the alternative ways to deal with ER_NO_SUCH TABLE.
*/
if (thd->is_error())
{
if (table_list->parent_l)
{
thd->clear_error();
my_error(ER_WRONG_MRG_TABLE, MYF(0));
}
else if (table_list->belong_to_view)
{
TABLE_LIST *view= table_list->belong_to_view;
thd->clear_error();
my_error(ER_VIEW_INVALID, MYF(0),
view->view_db.str, view->view_name.str);
}
}
DBUG_RETURN(TRUE);
}
/*
Check if this TABLE_SHARE-object corresponds to a view. Note, that there is
no need to check TABLE_SHARE::tdc.flushed as we do for regular tables,
because view shares are always up to date.
*/
if (share->is_view)
{
/*
If parent_l of the table_list is non null then a merge table
has this view as child table, which is not supported.
*/
if (table_list->parent_l)
{
my_error(ER_WRONG_MRG_TABLE, MYF(0));
goto err_lock;
}
if (table_list->sequence)
{
my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str,
table_list->alias.str);
goto err_lock;
}
/*
This table is a view. Validate its metadata version: in particular,
that it was a view when the statement was prepared.
*/
if (check_and_update_table_version(thd, table_list, share))
goto err_lock;
/* Open view */
if (mysql_make_view(thd, share, table_list, false))
goto err_lock;
/* TODO: Don't free this */
tdc_release_share(share);
DBUG_ASSERT(table_list->view);
DBUG_RETURN(FALSE);
}
#ifdef WITH_WSREP
if (!((flags & MYSQL_OPEN_IGNORE_FLUSH) ||
(thd->wsrep_applier)))
#else
if (!(flags & MYSQL_OPEN_IGNORE_FLUSH))
#endif
{
if (share->tdc->flushed)
{
DBUG_PRINT("info", ("Found old share version: %lld current: %lld",
share->tdc->version, tdc_refresh_version()));
/*
We already have an MDL lock. But we have encountered an old
version of table in the table definition cache which is possible
when someone changes the table version directly in the cache
without acquiring a metadata lock (e.g. this can happen during
"rolling" FLUSH TABLE(S)).
Release our reference to share, wait until old version of
share goes away and then try to get new version of table share.
*/
if (table)
tc_release_table(table);
else
tdc_release_share(share);
MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);
bool wait_result;
thd->push_internal_handler(&mdl_deadlock_handler);
wait_result= tdc_wait_for_old_version(thd, table_list->db.str,
table_list->table_name.str,
ot_ctx->get_timeout(),
mdl_ticket->get_deadlock_weight());
thd->pop_internal_handler();
if (wait_result)
DBUG_RETURN(TRUE);
goto retry_share;
}
if (thd->open_tables && thd->open_tables->s->tdc->flushed)
{
/*
If the version changes while we're opening the tables,
we have to back off, close all the tables opened-so-far,
and try to reopen them. Note: refresh_version is currently
changed only during FLUSH TABLES.
*/
if (table)
tc_release_table(table);
else
tdc_release_share(share);
(void)ot_ctx->request_backoff_action(Open_table_context::OT_REOPEN_TABLES,
NULL);
DBUG_RETURN(TRUE);
}
}
if (table)
{
DBUG_ASSERT(table->file != NULL);
MYSQL_REBIND_TABLE(table->file);
#ifdef WITH_PARTITION_STORAGE_ENGINE
part_names_error= set_partitions_as_used(table_list, table);
#endif
}
else
{
enum open_frm_error error;
/* make a new table */
if (!(table=(TABLE*) my_malloc(sizeof(*table),MYF(MY_WME))))
goto err_lock;
error= open_table_from_share(thd, share, &table_list->alias,
HA_OPEN_KEYFILE | HA_TRY_READ_ONLY,
EXTRA_RECORD,
thd->open_options, table, FALSE,
IF_PARTITIONING(table_list->partition_names,0));
if (unlikely(error))
{
my_free(table);
if (error == OPEN_FRM_DISCOVER)
(void) ot_ctx->request_backoff_action(Open_table_context::OT_DISCOVER,
table_list);
else if (share->crashed)
{
if (!(flags & MYSQL_OPEN_IGNORE_REPAIR))
(void) ot_ctx->request_backoff_action(Open_table_context::OT_REPAIR,
table_list);
else
table_list->crashed= 1; /* Mark that table was crashed */
}
goto err_lock;
}
if (open_table_entry_fini(thd, share, table))
{
closefrm(table);
my_free(table);
goto err_lock;
}
/* Add table to the share's used tables list. */
tc_add_table(thd, table);
from_share= true;
}
table->mdl_ticket= mdl_ticket;
table->reginfo.lock_type=TL_READ; /* Assume read */
table->init(thd, table_list);
table->next= thd->open_tables; /* Link into simple list */
thd->set_open_tables(table);
reset:
/*
Check that there is no reference to a condition from an earlier query
(cf. Bug#58553).
*/
DBUG_ASSERT(table->file->pushed_cond == NULL);
table_list->updatable= 1; // It is not derived table nor non-updatable VIEW
table_list->table= table;
if (!from_share && table->vcol_fix_expr(thd))
goto err_lock;
#ifdef WITH_PARTITION_STORAGE_ENGINE
if (unlikely(table->part_info))
{
/* Partitions specified were incorrect.*/
if (part_names_error)
{
table->file->print_error(part_names_error, MYF(0));
DBUG_RETURN(true);
}
}
else if (table_list->partition_names)
{
/* Don't allow PARTITION () clause on a nonpartitioned table */
my_error(ER_PARTITION_CLAUSE_ON_NONPARTITIONED, MYF(0));
DBUG_RETURN(true);
}
#endif
if (table_list->sequence && table->s->table_type != TABLE_TYPE_SEQUENCE)
{
my_error(ER_NOT_SEQUENCE, MYF(0), table_list->db.str, table_list->alias.str);
DBUG_RETURN(true);
}
DBUG_RETURN(FALSE);
err_lock:
tdc_release_share(share);
DBUG_PRINT("exit", ("failed"));
DBUG_RETURN(TRUE);
} | 1 | CVE-2022-27376 | 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. | 7,050 |
libtiff | 5c080298d59efa53264d7248bbe3a04660db6ef7 | cpStripToTile(uint8* out, uint8* in,
uint32 rows, uint32 cols, int outskew, int64 inskew)
{
while (rows-- > 0) {
uint32 j = cols;
while (j-- > 0)
*out++ = *in++;
out += outskew;
in += inskew;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,929 |
Chrome | 31b81d4cf8b6a063391839816c82fc61c8272e53 | void ScreenLayoutObserver::CreateOrUpdateNotification(
const base::string16& message,
const base::string16& additional_message) {
message_center::MessageCenter::Get()->RemoveNotification(kNotificationId,
false /* by_user */);
if (message.empty() && additional_message.empty())
return;
if (Shell::Get()
->screen_orientation_controller()
->ignore_display_configuration_updates()) {
return;
}
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
std::unique_ptr<Notification> notification(new Notification(
message_center::NOTIFICATION_TYPE_SIMPLE, kNotificationId, message,
additional_message, bundle.GetImageNamed(IDR_AURA_NOTIFICATION_DISPLAY),
base::string16(), // display_source
GURL(),
message_center::NotifierId(message_center::NotifierId::SYSTEM_COMPONENT,
system_notifier::kNotifierDisplay),
message_center::RichNotificationData(),
new message_center::HandleNotificationClickedDelegate(
base::Bind(&OpenSettingsFromNotification))));
ShellPort::Get()->RecordUserMetricsAction(
UMA_STATUS_AREA_DISPLAY_NOTIFICATION_CREATED);
message_center::MessageCenter::Get()->AddNotification(
std::move(notification));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,406 |
savannah | 1c3ccb3e040bf13e342ee60bc23b21b97b11923f | asn1_get_bit_der (const unsigned char *der, int der_len,
int *ret_len, unsigned char *str, int str_size,
int *bit_len)
{
int len_len = 0, len_byte;
if (der_len <= 0)
return ASN1_GENERIC_ERROR;
len_byte = asn1_get_length_der (der, der_len, &len_len) - 1;
if (len_byte < 0)
return ASN1_DER_ERROR;
*ret_len = len_byte + len_len + 1;
*bit_len = len_byte * 8 - der[len_len];
if (*bit_len <= 0)
return ASN1_DER_ERROR;
if (str_size >= len_byte)
memcpy (str, der + len_len + 1, len_byte);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,475 |
LibRaw | a6937d4046a7c4742b683a04c8564605fd9be4fb | int LibRaw::ljpeg_start(struct jhead *jh, int info_only)
{
ushort c, tag, len;
int cnt = 0;
uchar data[0x10000];
const uchar *dp;
memset(jh, 0, sizeof *jh);
jh->restart = INT_MAX;
if ((fgetc(ifp), fgetc(ifp)) != 0xd8)
return 0;
do
{
if (feof(ifp))
return 0;
if (cnt++ > 1024)
return 0; // 1024 tags limit
if (!fread(data, 2, 2, ifp))
return 0;
tag = data[0] << 8 | data[1];
len = (data[2] << 8 | data[3]) - 2;
if (tag <= 0xff00)
return 0;
fread(data, 1, len, ifp);
switch (tag)
{
case 0xffc3: // start of frame; lossless, Huffman
jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
case 0xffc1:
case 0xffc0:
jh->algo = tag & 0xff;
jh->bits = data[0];
jh->high = data[1] << 8 | data[2];
jh->wide = data[3] << 8 | data[4];
jh->clrs = data[5] + jh->sraw;
if (len == 9 && !dng_version)
getc(ifp);
break;
case 0xffc4: // define Huffman tables
if (info_only)
break;
for (dp = data; dp < data + len && !((c = *dp++) & -20);)
jh->free[c] = jh->huff[c] = make_decoder_ref(&dp);
break;
case 0xffda: // start of scan
jh->psv = data[1 + data[0] * 2];
jh->bits -= data[3 + data[0] * 2] & 15;
break;
case 0xffdb:
FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2];
break;
case 0xffdd:
jh->restart = data[0] << 8 | data[1];
}
} while (tag != 0xffda);
if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide ||
!jh->clrs)
return 0;
if (info_only)
return 1;
if (!jh->huff[0])
return 0;
FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c];
if (jh->sraw)
{
FORC(4) jh->huff[2 + c] = jh->huff[1];
FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0];
}
jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4);
merror(jh->row, "ljpeg_start()");
return zero_after_ff = 1;
} | 1 | CVE-2020-35533 | 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. | 9,834 |
qemu | 8c92060d3c0248bd4d515719a35922cd2391b9b4 | static ssize_t sungem_receive(NetClientState *nc, const uint8_t *buf,
size_t size)
{
SunGEMState *s = qemu_get_nic_opaque(nc);
PCIDevice *d = PCI_DEVICE(s);
uint32_t mac_crc, done, kick, max_fsize;
uint32_t fcs_size, ints, rxdma_cfg, rxmac_cfg, csum, coff;
uint8_t smallbuf[60];
struct gem_rxd desc;
uint64_t dbase, baddr;
unsigned int rx_cond;
trace_sungem_rx_packet(size);
rxmac_cfg = s->macregs[MAC_RXCFG >> 2];
rxdma_cfg = s->rxdmaregs[RXDMA_CFG >> 2];
max_fsize = s->macregs[MAC_MAXFSZ >> 2] & 0x7fff;
/* If MAC or DMA disabled, can't receive */
if (!(rxdma_cfg & RXDMA_CFG_ENABLE) ||
!(rxmac_cfg & MAC_RXCFG_ENAB)) {
trace_sungem_rx_disabled();
return 0;
}
/* Size adjustment for FCS */
if (rxmac_cfg & MAC_RXCFG_SFCS) {
fcs_size = 0;
} else {
fcs_size = 4;
}
/* Discard frame smaller than a MAC or larger than max frame size
* (when accounting for FCS)
*/
if (size < 6 || (size + 4) > max_fsize) {
trace_sungem_rx_bad_frame_size(size);
/* XXX Increment error statistics ? */
return size;
}
/* We don't drop too small frames since we get them in qemu, we pad
* them instead. We should probably use the min frame size register
* but I don't want to use a variable size staging buffer and I
* know both MacOS and Linux use the default 64 anyway. We use 60
* here to account for the non-existent FCS.
*/
if (size < 60) {
memcpy(smallbuf, buf, size);
memset(&smallbuf[size], 0, 60 - size);
buf = smallbuf;
size = 60;
}
/* Get MAC crc */
mac_crc = net_crc32_le(buf, ETH_ALEN);
/* Packet isn't for me ? */
rx_cond = sungem_check_rx_mac(s, buf, mac_crc);
if (rx_cond == rx_no_match) {
/* Just drop it */
trace_sungem_rx_unmatched();
return size;
}
/* Get ring pointers */
kick = s->rxdmaregs[RXDMA_KICK >> 2] & s->rx_mask;
done = s->rxdmaregs[RXDMA_DONE >> 2] & s->rx_mask;
trace_sungem_rx_process(done, kick, s->rx_mask + 1);
/* Ring full ? Can't receive */
if (sungem_rx_full(s, kick, done)) {
trace_sungem_rx_ringfull();
return 0;
}
/* Note: The real GEM will fetch descriptors in blocks of 4,
* for now we handle them one at a time, I think the driver will
* cope
*/
dbase = s->rxdmaregs[RXDMA_DBHI >> 2];
dbase = (dbase << 32) | s->rxdmaregs[RXDMA_DBLOW >> 2];
/* Read the next descriptor */
pci_dma_read(d, dbase + done * sizeof(desc), &desc, sizeof(desc));
trace_sungem_rx_desc(le64_to_cpu(desc.status_word),
le64_to_cpu(desc.buffer));
/* Effective buffer address */
baddr = le64_to_cpu(desc.buffer) & ~7ull;
baddr |= (rxdma_cfg & RXDMA_CFG_FBOFF) >> 10;
/* Write buffer out */
pci_dma_write(d, baddr, buf, size);
if (fcs_size) {
/* Should we add an FCS ? Linux doesn't ask us to strip it,
* however I believe nothing checks it... For now we just
* do nothing. It's faster this way.
*/
}
/* Calculate the checksum */
coff = (rxdma_cfg & RXDMA_CFG_CSUMOFF) >> 13;
csum = net_raw_checksum((uint8_t *)buf + coff, size - coff);
/* Build the updated descriptor */
desc.status_word = (size + fcs_size) << 16;
desc.status_word |= ((uint64_t)(mac_crc >> 16)) << 44;
desc.status_word |= csum;
if (rx_cond == rx_match_mcast) {
desc.status_word |= RXDCTRL_HPASS;
}
if (rx_cond == rx_match_altmac) {
desc.status_word |= RXDCTRL_ALTMAC;
}
desc.status_word = cpu_to_le64(desc.status_word);
pci_dma_write(d, dbase + done * sizeof(desc), &desc, sizeof(desc));
done = (done + 1) & s->rx_mask;
s->rxdmaregs[RXDMA_DONE >> 2] = done;
/* XXX Unconditionally set RX interrupt for now. The interrupt
* mitigation timer might well end up adding more overhead than
* helping here...
*/
ints = GREG_STAT_RXDONE;
if (sungem_rx_full(s, kick, done)) {
ints |= GREG_STAT_RXNOBUF;
}
sungem_update_status(s, ints, true);
return size;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,667 |
keepalived | 5241e4d7b177d0b6f073cfc9ed5444bf51ec89d6 | parse_cmdline(int argc, char **argv)
{
int c;
bool reopen_log = false;
int signum;
struct utsname uname_buf;
int longindex;
int curind;
bool bad_option = false;
unsigned facility;
mode_t new_umask_val;
struct option long_options[] = {
{"use-file", required_argument, NULL, 'f'},
#if defined _WITH_VRRP_ && defined _WITH_LVS_
{"vrrp", no_argument, NULL, 'P'},
{"check", no_argument, NULL, 'C'},
#endif
#ifdef _WITH_BFD_
{"no_bfd", no_argument, NULL, 'B'},
#endif
{"all", no_argument, NULL, 3 },
{"log-console", no_argument, NULL, 'l'},
{"log-detail", no_argument, NULL, 'D'},
{"log-facility", required_argument, NULL, 'S'},
{"log-file", optional_argument, NULL, 'g'},
{"flush-log-file", no_argument, NULL, 2 },
{"no-syslog", no_argument, NULL, 'G'},
{"umask", required_argument, NULL, 'u'},
#ifdef _WITH_VRRP_
{"release-vips", no_argument, NULL, 'X'},
{"dont-release-vrrp", no_argument, NULL, 'V'},
#endif
#ifdef _WITH_LVS_
{"dont-release-ipvs", no_argument, NULL, 'I'},
#endif
{"dont-respawn", no_argument, NULL, 'R'},
{"dont-fork", no_argument, NULL, 'n'},
{"dump-conf", no_argument, NULL, 'd'},
{"pid", required_argument, NULL, 'p'},
#ifdef _WITH_VRRP_
{"vrrp_pid", required_argument, NULL, 'r'},
#endif
#ifdef _WITH_LVS_
{"checkers_pid", required_argument, NULL, 'c'},
{"address-monitoring", no_argument, NULL, 'a'},
#endif
#ifdef _WITH_BFD_
{"bfd_pid", required_argument, NULL, 'b'},
#endif
#ifdef _WITH_SNMP_
{"snmp", no_argument, NULL, 'x'},
{"snmp-agent-socket", required_argument, NULL, 'A'},
#endif
{"core-dump", no_argument, NULL, 'm'},
{"core-dump-pattern", optional_argument, NULL, 'M'},
#ifdef _MEM_CHECK_LOG_
{"mem-check-log", no_argument, NULL, 'L'},
#endif
#if HAVE_DECL_CLONE_NEWNET
{"namespace", required_argument, NULL, 's'},
#endif
{"config-id", required_argument, NULL, 'i'},
{"signum", required_argument, NULL, 4 },
{"config-test", optional_argument, NULL, 't'},
#ifdef _WITH_PERF_
{"perf", optional_argument, NULL, 5 },
#endif
#ifdef WITH_DEBUG_OPTIONS
{"debug", optional_argument, NULL, 6 },
#endif
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0 }
};
/* Unfortunately, if a short option is used, getopt_long() doesn't change the value
* of longindex, so we need to ensure that before calling getopt_long(), longindex
* is set to a known invalid value */
curind = optind;
while (longindex = -1, (c = getopt_long(argc, argv, ":vhlndu:DRS:f:p:i:mM::g::Gt::"
#if defined _WITH_VRRP_ && defined _WITH_LVS_
"PC"
#endif
#ifdef _WITH_VRRP_
"r:VX"
#endif
#ifdef _WITH_LVS_
"ac:I"
#endif
#ifdef _WITH_BFD_
"Bb:"
#endif
#ifdef _WITH_SNMP_
"xA:"
#endif
#ifdef _MEM_CHECK_LOG_
"L"
#endif
#if HAVE_DECL_CLONE_NEWNET
"s:"
#endif
, long_options, &longindex)) != -1) {
/* Check for an empty option argument. For example --use-file= returns
* a 0 length option, which we don't want */
if (longindex >= 0 && long_options[longindex].has_arg == required_argument && optarg && !optarg[0]) {
c = ':';
optarg = NULL;
}
switch (c) {
case 'v':
fprintf(stderr, "%s", version_string);
#ifdef GIT_COMMIT
fprintf(stderr, ", git commit %s", GIT_COMMIT);
#endif
fprintf(stderr, "\n\n%s\n\n", COPYRIGHT_STRING);
fprintf(stderr, "Built with kernel headers for Linux %d.%d.%d\n",
(LINUX_VERSION_CODE >> 16) & 0xff,
(LINUX_VERSION_CODE >> 8) & 0xff,
(LINUX_VERSION_CODE ) & 0xff);
uname(&uname_buf);
fprintf(stderr, "Running on %s %s %s\n\n", uname_buf.sysname, uname_buf.release, uname_buf.version);
fprintf(stderr, "configure options: %s\n\n", KEEPALIVED_CONFIGURE_OPTIONS);
fprintf(stderr, "Config options: %s\n\n", CONFIGURATION_OPTIONS);
fprintf(stderr, "System options: %s\n", SYSTEM_OPTIONS);
exit(0);
break;
case 'h':
usage(argv[0]);
exit(0);
break;
case 'l':
__set_bit(LOG_CONSOLE_BIT, &debug);
reopen_log = true;
break;
case 'n':
__set_bit(DONT_FORK_BIT, &debug);
break;
case 'd':
__set_bit(DUMP_CONF_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'V':
__set_bit(DONT_RELEASE_VRRP_BIT, &debug);
break;
#endif
#ifdef _WITH_LVS_
case 'I':
__set_bit(DONT_RELEASE_IPVS_BIT, &debug);
break;
#endif
case 'D':
if (__test_bit(LOG_DETAIL_BIT, &debug))
__set_bit(LOG_EXTRA_DETAIL_BIT, &debug);
else
__set_bit(LOG_DETAIL_BIT, &debug);
break;
case 'R':
__set_bit(DONT_RESPAWN_BIT, &debug);
break;
#ifdef _WITH_VRRP_
case 'X':
__set_bit(RELEASE_VIPS_BIT, &debug);
break;
#endif
case 'S':
if (!read_unsigned(optarg, &facility, 0, LOG_FACILITY_MAX, false))
fprintf(stderr, "Invalid log facility '%s'\n", optarg);
else {
log_facility = LOG_FACILITY[facility].facility;
reopen_log = true;
}
break;
case 'g':
if (optarg && optarg[0])
log_file_name = optarg;
else
log_file_name = "/tmp/keepalived.log";
open_log_file(log_file_name, NULL, NULL, NULL);
break;
case 'G':
__set_bit(NO_SYSLOG_BIT, &debug);
reopen_log = true;
break;
case 'u':
new_umask_val = set_umask(optarg);
if (umask_cmdline)
umask_val = new_umask_val;
break;
case 't':
__set_bit(CONFIG_TEST_BIT, &debug);
__set_bit(DONT_RESPAWN_BIT, &debug);
__set_bit(DONT_FORK_BIT, &debug);
__set_bit(NO_SYSLOG_BIT, &debug);
if (optarg && optarg[0]) {
int fd = open(optarg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1) {
fprintf(stderr, "Unable to open config-test log file %s\n", optarg);
exit(EXIT_FAILURE);
}
dup2(fd, STDERR_FILENO);
close(fd);
}
break;
case 'f':
conf_file = optarg;
break;
case 2: /* --flush-log-file */
set_flush_log_file();
break;
#if defined _WITH_VRRP_ && defined _WITH_LVS_
case 'P':
__clear_bit(DAEMON_CHECKERS, &daemon_mode);
break;
case 'C':
__clear_bit(DAEMON_VRRP, &daemon_mode);
break;
#endif
#ifdef _WITH_BFD_
case 'B':
__clear_bit(DAEMON_BFD, &daemon_mode);
break;
#endif
case 'p':
main_pidfile = optarg;
break;
#ifdef _WITH_LVS_
case 'c':
checkers_pidfile = optarg;
break;
case 'a':
__set_bit(LOG_ADDRESS_CHANGES, &debug);
break;
#endif
#ifdef _WITH_VRRP_
case 'r':
vrrp_pidfile = optarg;
break;
#endif
#ifdef _WITH_BFD_
case 'b':
bfd_pidfile = optarg;
break;
#endif
#ifdef _WITH_SNMP_
case 'x':
snmp = 1;
break;
case 'A':
snmp_socket = optarg;
break;
#endif
case 'M':
set_core_dump_pattern = true;
if (optarg && optarg[0])
core_dump_pattern = optarg;
/* ... falls through ... */
case 'm':
create_core_dump = true;
break;
#ifdef _MEM_CHECK_LOG_
case 'L':
__set_bit(MEM_CHECK_LOG_BIT, &debug);
break;
#endif
#if HAVE_DECL_CLONE_NEWNET
case 's':
override_namespace = MALLOC(strlen(optarg) + 1);
strcpy(override_namespace, optarg);
break;
#endif
case 'i':
FREE_PTR(config_id);
config_id = MALLOC(strlen(optarg) + 1);
strcpy(config_id, optarg);
break;
case 4: /* --signum */
signum = get_signum(optarg);
if (signum == -1) {
fprintf(stderr, "Unknown sigfunc %s\n", optarg);
exit(1);
}
printf("%d\n", signum);
exit(0);
break;
case 3: /* --all */
__set_bit(RUN_ALL_CHILDREN, &daemon_mode);
#ifdef _WITH_VRRP_
__set_bit(DAEMON_VRRP, &daemon_mode);
#endif
#ifdef _WITH_LVS_
__set_bit(DAEMON_CHECKERS, &daemon_mode);
#endif
#ifdef _WITH_BFD_
__set_bit(DAEMON_BFD, &daemon_mode);
#endif
break;
#ifdef _WITH_PERF_
case 5:
if (optarg && optarg[0]) {
if (!strcmp(optarg, "run"))
perf_run = PERF_RUN;
else if (!strcmp(optarg, "all"))
perf_run = PERF_ALL;
else if (!strcmp(optarg, "end"))
perf_run = PERF_END;
else
log_message(LOG_INFO, "Unknown perf start point %s", optarg);
}
else
perf_run = PERF_RUN;
break;
#endif
#ifdef WITH_DEBUG_OPTIONS
case 6:
set_debug_options(optarg && optarg[0] ? optarg : NULL);
break;
#endif
case '?':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Unknown option -%c\n", optopt);
else
fprintf(stderr, "Unknown option %s\n", argv[curind]);
bad_option = true;
break;
case ':':
if (optopt && argv[curind][1] != '-')
fprintf(stderr, "Missing parameter for option -%c\n", optopt);
else
fprintf(stderr, "Missing parameter for option --%s\n", long_options[longindex].name);
bad_option = true;
break;
default:
exit(1);
break;
}
curind = optind;
}
if (optind < argc) {
printf("Unexpected argument(s): ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
if (bad_option)
exit(1);
return reopen_log;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,876 |
ghostscript | c501a58f8d5650c8ba21d447c0d6f07eafcb0f15 | static TT_F26Dot6 Norm( TT_F26Dot6 X, TT_F26Dot6 Y )
{
Int64 T1, T2;
MUL_64( X, X, T1 );
MUL_64( Y, Y, T2 );
ADD_64( T1, T2, T1 );
return (TT_F26Dot6)SQRT_64( T1 );
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,232 |
Chrome | 7f3d85b096f66870a15b37c2f40b219b2e292693 | png_do_read_interlace(png_structp png_ptr)
{
png_row_infop row_info = &(png_ptr->row_info);
png_bytep row = png_ptr->row_buf + 1;
int pass = png_ptr->pass;
png_uint_32 transformations = png_ptr->transformations;
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Offset to next interlace block */
PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
png_debug(1, "in png_do_read_interlace");
if (row != NULL && row_info != NULL)
{
png_uint_32 final_width;
final_width = row_info->width * png_pass_inc[pass];
switch (row_info->pixel_depth)
{
case 1:
{
png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
int sshift, dshift;
int s_start, s_end, s_inc;
int jstop = png_pass_inc[pass];
png_byte v;
png_uint_32 i;
int j;
#ifdef PNG_READ_PACKSWAP_SUPPORTED
if (transformations & PNG_PACKSWAP)
{
sshift = (int)((row_info->width + 7) & 0x07);
dshift = (int)((final_width + 7) & 0x07);
s_start = 7;
s_end = 0;
s_inc = -1;
}
else
#endif
{
sshift = 7 - (int)((row_info->width + 7) & 0x07);
dshift = 7 - (int)((final_width + 7) & 0x07);
s_start = 0;
s_end = 7;
s_inc = 1;
}
for (i = 0; i < row_info->width; i++)
{
v = (png_byte)((*sp >> sshift) & 0x01);
for (j = 0; j < jstop; j++)
{
*dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
*dp |= (png_byte)(v << dshift);
if (dshift == s_end)
{
dshift = s_start;
dp--;
}
else
dshift += s_inc;
}
if (sshift == s_end)
{
sshift = s_start;
sp--;
}
else
sshift += s_inc;
}
break;
}
case 2:
{
png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
int sshift, dshift;
int s_start, s_end, s_inc;
int jstop = png_pass_inc[pass];
png_uint_32 i;
#ifdef PNG_READ_PACKSWAP_SUPPORTED
if (transformations & PNG_PACKSWAP)
{
sshift = (int)(((row_info->width + 3) & 0x03) << 1);
dshift = (int)(((final_width + 3) & 0x03) << 1);
s_start = 6;
s_end = 0;
s_inc = -2;
}
else
#endif
{
sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
s_start = 0;
s_end = 6;
s_inc = 2;
}
for (i = 0; i < row_info->width; i++)
{
png_byte v;
int j;
v = (png_byte)((*sp >> sshift) & 0x03);
for (j = 0; j < jstop; j++)
{
*dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
*dp |= (png_byte)(v << dshift);
if (dshift == s_end)
{
dshift = s_start;
dp--;
}
else
dshift += s_inc;
}
if (sshift == s_end)
{
sshift = s_start;
sp--;
}
else
sshift += s_inc;
}
break;
}
case 4:
{
png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
int sshift, dshift;
int s_start, s_end, s_inc;
png_uint_32 i;
int jstop = png_pass_inc[pass];
#ifdef PNG_READ_PACKSWAP_SUPPORTED
if (transformations & PNG_PACKSWAP)
{
sshift = (int)(((row_info->width + 1) & 0x01) << 2);
dshift = (int)(((final_width + 1) & 0x01) << 2);
s_start = 4;
s_end = 0;
s_inc = -4;
}
else
#endif
{
sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
s_start = 0;
s_end = 4;
s_inc = 4;
}
for (i = 0; i < row_info->width; i++)
{
png_byte v = (png_byte)((*sp >> sshift) & 0xf);
int j;
for (j = 0; j < jstop; j++)
{
*dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
*dp |= (png_byte)(v << dshift);
if (dshift == s_end)
{
dshift = s_start;
dp--;
}
else
dshift += s_inc;
}
if (sshift == s_end)
{
sshift = s_start;
sp--;
}
else
sshift += s_inc;
}
break;
}
default:
{
png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
png_bytep sp = row + (png_size_t)(row_info->width - 1)
* pixel_bytes;
png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
int jstop = png_pass_inc[pass];
png_uint_32 i;
for (i = 0; i < row_info->width; i++)
{
png_byte v[8];
int j;
png_memcpy(v, sp, pixel_bytes);
for (j = 0; j < jstop; j++)
{
png_memcpy(dp, v, pixel_bytes);
dp -= pixel_bytes;
}
sp -= pixel_bytes;
}
break;
}
}
row_info->width = final_width;
row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width);
}
#ifndef PNG_READ_PACKSWAP_SUPPORTED
PNG_UNUSED(transformations) /* Silence compiler warning */
#endif
}
| 1 | CVE-2015-8126 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 1,487 |
linux | 47abea041f897d64dbd5777f0cf7745148f85d75 | static bool io_cancel_cb(struct io_wq_work *work, void *data)
{
struct io_kiocb *req = container_of(work, struct io_kiocb, work);
struct io_cancel_data *cd = data;
if (req->ctx != cd->ctx)
return false;
if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
;
} else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
if (req->file != cd->file)
return false;
} else {
if (req->cqe.user_data != cd->data)
return false;
}
if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
if (cd->seq == req->work.cancel_seq)
return false;
req->work.cancel_seq = cd->seq;
}
return true;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,510 |
ImageMagick | f28e9e56e1b56d4e1f09d2a56d70892ae295d6a4 | MagickExport size_t InterpretImageFilename(const ImageInfo *image_info,
Image *image,const char *format,int value,char *filename,
ExceptionInfo *exception)
{
char
*q;
int
c;
MagickBooleanType
canonical;
register const char
*p;
ssize_t
field_width,
offset;
canonical=MagickFalse;
offset=0;
(void) CopyMagickString(filename,format,MagickPathExtent);
for (p=strchr(format,'%'); p != (char *) NULL; p=strchr(p+1,'%'))
{
q=(char *) p+1;
if (*q == '%')
{
p=q+1;
continue;
}
field_width=0;
if (*q == '0')
field_width=(ssize_t) strtol(q,&q,10);
switch (*q)
{
case 'd':
case 'o':
case 'x':
{
q++;
c=(*q);
*q='\0';
(void) FormatLocaleString(filename+(p-format-offset),(size_t)
(MagickPathExtent-(p-format-offset)),p,value);
offset+=(4-field_width);
*q=c;
(void) ConcatenateMagickString(filename,q,MagickPathExtent);
canonical=MagickTrue;
if (*(q-1) != '%')
break;
p++;
break;
}
case '[':
{
char
pattern[MagickPathExtent];
const char
*option;
register char
*r;
register ssize_t
i;
ssize_t
depth;
/*
Image option.
*/
if (strchr(p,']') == (char *) NULL)
break;
depth=1;
r=q+1;
for (i=0; (i < (MagickPathExtent-1L)) && (*r != '\0'); i++)
{
if (*r == '[')
depth++;
if (*r == ']')
depth--;
if (depth <= 0)
break;
pattern[i]=(*r++);
}
pattern[i]='\0';
if (LocaleNCompare(pattern,"filename:",9) != 0)
break;
option=(const char *) NULL;
if (image != (Image *) NULL)
option=GetImageProperty(image,pattern,exception);
if ((option == (const char *) NULL) && (image != (Image *) NULL))
option=GetImageArtifact(image,pattern);
if ((option == (const char *) NULL) &&
(image_info != (ImageInfo *) NULL))
option=GetImageOption(image_info,pattern);
if (option == (const char *) NULL)
break;
q--;
c=(*q);
*q='\0';
(void) CopyMagickString(filename+(p-format-offset),option,(size_t)
(MagickPathExtent-(p-format-offset)));
offset+=strlen(pattern)-strlen(option)+3;
*q=c;
(void) ConcatenateMagickString(filename,r+1,MagickPathExtent);
canonical=MagickTrue;
if (*(q-1) != '%')
break;
p++;
break;
}
default:
break;
}
}
if (canonical == MagickFalse)
(void) CopyMagickString(filename,format,MagickPathExtent);
else
for (q=filename; *q != '\0'; q++)
if ((*q == '%') && (*(q+1) == '%'))
(void) CopyMagickString(q,q+1,(size_t) (MagickPathExtent-(q-filename)));
return(strlen(filename));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,528 |
vim | 0c8485f0e4931463c0f7986e1ea84a7d79f10c75 | u_eval_tree(u_header_T *first_uhp, list_T *list)
{
u_header_T *uhp = first_uhp;
dict_T *dict;
while (uhp != NULL)
{
dict = dict_alloc();
if (dict == NULL)
return;
dict_add_nr_str(dict, "seq", uhp->uh_seq, NULL);
dict_add_nr_str(dict, "time", (long)uhp->uh_time, NULL);
if (uhp == curbuf->b_u_newhead)
dict_add_nr_str(dict, "newhead", 1, NULL);
if (uhp == curbuf->b_u_curhead)
dict_add_nr_str(dict, "curhead", 1, NULL);
if (uhp->uh_save_nr > 0)
dict_add_nr_str(dict, "save", uhp->uh_save_nr, NULL);
if (uhp->uh_alt_next.ptr != NULL)
{
list_T *alt_list = list_alloc();
if (alt_list != NULL)
{
/* Recursive call to add alternate undo tree. */
u_eval_tree(uhp->uh_alt_next.ptr, alt_list);
dict_add_list(dict, "alt", alt_list);
}
}
list_append_dict(list, dict);
uhp = uhp->uh_prev.ptr;
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,104 |
vim | d0b5138ba4bccff8a744c99836041ef6322ed39a | clear_termoptions(void)
{
/*
* Reset a few things before clearing the old options. This may cause
* outputting a few things that the terminal doesn't understand, but the
* screen will be cleared later, so this is OK.
*/
#ifdef FEAT_MOUSE_TTY
mch_setmouse(FALSE); /* switch mouse off */
#endif
#ifdef FEAT_TITLE
mch_restore_title(3); /* restore window titles */
#endif
#if defined(FEAT_XCLIPBOARD) && defined(FEAT_GUI)
/* When starting the GUI close the display opened for the clipboard.
* After restoring the title, because that will need the display. */
if (gui.starting)
clear_xterm_clip();
#endif
stoptermcap(); /* stop termcap mode */
free_termoptions();
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,494 |
FFmpeg | 611b35627488a8d0763e75c25ee0875c5b7987dd | static int dnxhd_find_frame_end(DNXHDParserContext *dctx,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = &dctx->pc;
uint64_t state = pc->state64;
int pic_found = pc->frame_start_found;
int i = 0;
if (!pic_found) {
for (i = 0; i < buf_size; i++) {
state = (state << 8) | buf[i];
if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {
i++;
pic_found = 1;
dctx->cur_byte = 0;
dctx->remaining = 0;
break;
}
}
}
if (pic_found && !dctx->remaining) {
if (!buf_size) /* EOF considered as end of frame */
return 0;
for (; i < buf_size; i++) {
dctx->cur_byte++;
state = (state << 8) | buf[i];
if (dctx->cur_byte == 24) {
dctx->h = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 26) {
dctx->w = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 42) {
int cid = (state >> 32) & 0xFFFFFFFF;
if (cid <= 0)
continue;
dctx->remaining = avpriv_dnxhd_get_frame_size(cid);
if (dctx->remaining <= 0) {
dctx->remaining = ff_dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);
if (dctx->remaining <= 0)
return dctx->remaining;
}
if (buf_size - i + 47 >= dctx->remaining) {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
} else {
dctx->remaining -= buf_size;
}
}
}
} else if (pic_found) {
if (dctx->remaining > buf_size) {
dctx->remaining -= buf_size;
} else {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
}
}
pc->frame_start_found = pic_found;
pc->state64 = state;
return END_NOT_FOUND;
}
| 1 | CVE-2017-9608 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 1,673 |
krb5 | 4c023ba43c16396f0d199e2df1cfa59b88b62acc | find_alternate_tgs(kdc_realm_t *kdc_active_realm, krb5_principal princ,
krb5_db_entry **server_ptr, const char **status)
{
krb5_error_code retval;
krb5_principal *plist = NULL, *pl2;
krb5_data tmp;
krb5_db_entry *server = NULL;
*server_ptr = NULL;
assert(is_cross_tgs_principal(princ));
if ((retval = krb5_walk_realm_tree(kdc_context,
krb5_princ_realm(kdc_context, princ),
krb5_princ_component(kdc_context, princ, 1),
&plist, KRB5_REALM_BRANCH_CHAR))) {
goto cleanup;
}
/* move to the end */
for (pl2 = plist; *pl2; pl2++);
/* the first entry in this array is for krbtgt/local@local, so we
ignore it */
while (--pl2 > plist) {
tmp = *krb5_princ_realm(kdc_context, *pl2);
krb5_princ_set_realm(kdc_context, *pl2,
krb5_princ_realm(kdc_context, tgs_server));
retval = db_get_svc_princ(kdc_context, *pl2, 0, &server, status);
krb5_princ_set_realm(kdc_context, *pl2, &tmp);
if (retval == KRB5_KDB_NOENTRY)
continue;
else if (retval)
goto cleanup;
log_tgs_alt_tgt(kdc_context, server->princ);
*server_ptr = server;
server = NULL;
goto cleanup;
}
cleanup:
if (retval != 0)
*status = "UNKNOWN_SERVER";
krb5_free_realm_tree(kdc_context, plist);
krb5_db_free_principal(kdc_context, server);
return retval;
}
| 1 | CVE-2013-1417 | 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,184 |
gpac | b43f9d1a4b4e33d08edaef6d313e6ce4bdf554d3 | static void naludmx_update_clli_mdcv(GF_NALUDmxCtx *ctx, Bool reset_crc)
{
if (!ctx->opid) return;
if (reset_crc)
ctx->clli_crc = 0;
if ((ctx->hevc_state && ctx->hevc_state->clli_valid)
|| (ctx->vvc_state && ctx->vvc_state->clli_valid)
) {
u8 *clli = ctx->hevc_state ? ctx->hevc_state->clli_data : ctx->vvc_state->clli_data;
gf_filter_pid_set_property(ctx->opid, GF_PROP_PID_CONTENT_LIGHT_LEVEL, &PROP_DATA(clli, 4));
ctx->clli_crc = gf_crc_32(clli, 4);
}
if (reset_crc)
ctx->mdcv_crc = 0;
if ((ctx->hevc_state && ctx->hevc_state->mdcv_valid)
|| (ctx->vvc_state && ctx->vvc_state->mdcv_valid)
) {
u8 *mdcv = ctx->hevc_state ? ctx->hevc_state->mdcv_data : ctx->vvc_state->mdcv_data;
gf_filter_pid_set_property(ctx->opid, GF_PROP_PID_MASTER_DISPLAY_COLOUR, &PROP_DATA(mdcv, 24));
ctx->mdcv_crc = gf_crc_32(mdcv, 24);
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,312 |
wireshark | 41bfc9112480c3d83331ed93470c7f675a9d5b1a | dissect_header_lens_v2(tvbuff_t *tvb, wtap_syscall_header* syscall_header, int offset, proto_tree *tree, int encoding)
{
guint32 param_count;
proto_item *ti;
proto_tree *len_tree;
ti = proto_tree_add_item(tree, hf_se_param_lens, tvb, offset, syscall_header->nparams * SYSDIG_PARAM_SIZE_V2, ENC_NA);
len_tree = proto_item_add_subtree(ti, ett_sysdig_parm_lens);
for (param_count = 0; param_count < syscall_header->nparams; param_count++) {
proto_tree_add_item(len_tree, hf_se_param_len, tvb, offset + (param_count * SYSDIG_PARAM_SIZE_V2), SYSDIG_PARAM_SIZE_V2, encoding);
}
proto_item_set_len(ti, syscall_header->nparams * SYSDIG_PARAM_SIZE_V2);
return syscall_header->nparams * SYSDIG_PARAM_SIZE_V2;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,551 |
gpac | c535bad50d5812d27ee5b22b54371bddec411514 | GF_Err BM_SceneReplace(GF_BifsDecoder *codec, GF_BitStream *bs, GF_List *com_list)
{
GF_Command *com;
GF_Node *backup_root;
GF_List *backup_routes;
GF_Err BD_DecSceneReplace(GF_BifsDecoder * codec, GF_BitStream *bs, GF_List *proto_list);
backup_routes = codec->scenegraph->Routes;
backup_root = codec->scenegraph->RootNode;
com = gf_sg_command_new(codec->current_graph, GF_SG_SCENE_REPLACE);
codec->scenegraph->Routes = gf_list_new();
codec->current_graph = codec->scenegraph;
codec->LastError = BD_DecSceneReplace(codec, bs, com->new_proto_list);
com->use_names = codec->UseName;
/*restore*/
com->node = codec->scenegraph->RootNode;
codec->scenegraph->RootNode = backup_root;
gf_list_add(com_list, com);
/*insert routes*/
while (gf_list_count(codec->scenegraph->Routes)) {
GF_Route *r = (GF_Route*)gf_list_get(codec->scenegraph->Routes, 0);
GF_Command *ri = gf_sg_command_new(codec->current_graph, GF_SG_ROUTE_INSERT);
gf_list_rem(codec->scenegraph->Routes, 0);
ri->fromFieldIndex = r->FromField.fieldIndex;
ri->fromNodeID = gf_node_get_id(r->FromNode);
ri->toFieldIndex = r->ToField.fieldIndex;
ri->toNodeID = gf_node_get_id(r->ToNode);
if (r->ID) ri->RouteID = r->ID;
ri->def_name = r->name ? gf_strdup(r->name) : NULL;
gf_list_add(com_list, ri);
gf_sg_route_del(r);
}
gf_list_del(codec->scenegraph->Routes);
codec->scenegraph->Routes = backup_routes;
return codec->LastError;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,819 |
linux | 854e8bb1aa06c578c2c9145fa6bfe3680ef63b23 | int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
{
return kvm_x86_ops->set_msr(vcpu, msr);
}
| 1 | CVE-2014-3610 | 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 | 8,147 |
opa-ff | c5759e7b76f5bf844be6c6641cc1b356bbc83869 | int main(int argc, char *argv[]) {
p_fm_config_conx_hdlt hdl;
int instance = 0;
fm_mgr_config_errno_t res;
char *rem_addr = NULL;
char *community = "public";
char Opts[256];
int arg;
char *command;
int i;
/* Get options at the command line (overide default values) */
strcpy(Opts, "i:d:h-");
while ((arg = getopt(argc, argv, Opts)) != EOF) {
switch (arg) {
case 'h':
case '-':
usage(argv[0]);
return(0);
case 'i':
instance = atol(optarg);
break;
case 'd':
rem_addr = optarg;
break;
default:
usage(argv[0]);
return(-1);
}
}
if(optind >= argc){
fprintf(stderr, "Command required\n");
usage(argv[0]);
return -1;
}
command = argv[optind++];
printf("Connecting to %s FM instance %d\n", (rem_addr==NULL) ? "LOCAL":rem_addr, instance);
if((res = fm_mgr_config_init(&hdl,instance, rem_addr, community)) != FM_CONF_OK)
{
fprintf(stderr, "Failed to initialize the client handle: %d\n", res);
goto die_clean;
}
if((res = fm_mgr_config_connect(hdl)) != FM_CONF_OK)
{
fprintf(stderr, "Failed to connect: (%d) %s\n",res,fm_mgr_get_error_str(res));
goto die_clean;
}
for(i=0;i<commandListLen;i++){
if(strcmp(command,commandList[i].name) == 0){
return commandList[i].cmdPtr(hdl, commandList[i].mgr, (argc - optind), &argv[optind]);
}
}
fprintf(stderr, "Command (%s) is not valid\n",command);
usage(argv[0]);
res = -1;
die_clean:
if (hdl) free(hdl);
return res;
}
| 1 | CVE-2015-5232 | 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,677 |
libtiff | 3ca657a8793dd011bf869695d72ad31c779c3cc1 | fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32 bps = tif->tif_dir.td_bitspersample / 8;
tmsize_t wc = cc / bps;
tmsize_t count;
uint8 *cp = (uint8 *) cp0;
uint8 *tmp = (uint8 *)_TIFFmalloc(cc);
assert((cc%(bps*stride))==0);
if (!tmp)
return;
_TIFFmemcpy(tmp, cp0, cc);
for (count = 0; count < wc; count++) {
uint32 byte;
for (byte = 0; byte < bps; byte++) {
#if WORDS_BIGENDIAN
cp[byte * wc + count] = tmp[bps * count + byte];
#else
cp[(bps - byte - 1) * wc + count] =
tmp[bps * count + byte];
#endif
}
}
_TIFFfree(tmp);
cp = (uint8 *) cp0;
cp += cc - stride - 1;
for (count = cc; count > stride; count -= stride)
REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
}
| 1 | CVE-2016-9535 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 2,938 |
linux | b9a41d21dceadf8104812626ef85dc56ee8a60ed | void dm_internal_suspend_fast(struct mapped_device *md)
{
mutex_lock(&md->suspend_lock);
if (dm_suspended_md(md) || dm_suspended_internally_md(md))
return;
set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
synchronize_srcu(&md->io_barrier);
flush_workqueue(md->wq);
dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,565 |
Chrome | f85a87ec670ad0fce9d98d90c9a705b72a288154 | static void reflectedTreatNullAsNullStringCustomURLAttrAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TestObjectV8Internal::reflectedTreatNullAsNullStringCustomURLAttrAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,405 |
savannah | 0edf0986f3be570f5bf90ff245a85c1675f5c9a4 | TT_Save_Context( TT_ExecContext exec,
TT_Size size )
{
FT_Int i;
/* XXXX: Will probably disappear soon with all the code range */
/* management, which is now rather obsolete. */
/* */
size->num_function_defs = exec->numFDefs;
size->num_instruction_defs = exec->numIDefs;
size->max_func = exec->maxFunc;
size->max_ins = exec->maxIns;
for ( i = 0; i < TT_MAX_CODE_RANGES; i++ )
size->codeRangeTable[i] = exec->codeRangeTable[i];
return TT_Err_Ok;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,042 |
libebml | 05beb69ba60acce09f73ed491bb76f332849c3a0 | EbmlElement * EbmlElement::FindNextElement(IOCallback & DataStream, const EbmlSemanticContext & Context, int & UpperLevel,
uint64 MaxDataSize, bool AllowDummyElt, unsigned int MaxLowerLevel)
{
int PossibleID_Length = 0;
binary PossibleIdNSize[16];
int PossibleSizeLength;
uint64 SizeUnknown;
int ReadIndex = 0; // trick for the algo, start index at 0
uint32 ReadSize = 0;
uint64 SizeFound;
int SizeIdx;
bool bFound;
int UpperLevel_original = UpperLevel;
do {
// read a potential ID
do {
assert(ReadIndex < 16);
// build the ID with the current Read Buffer
bFound = false;
binary IdBitMask = 1 << 7;
for (SizeIdx = 0; SizeIdx < ReadIndex && SizeIdx < 4; SizeIdx++) {
if (PossibleIdNSize[0] & (IdBitMask >> SizeIdx)) {
// ID found
PossibleID_Length = SizeIdx + 1;
IdBitMask >>= SizeIdx;
bFound = true;
break;
}
}
if (bFound) {
break;
}
if (ReadIndex >= 4) {
// ID not found
// shift left the read octets
memmove(&PossibleIdNSize[0],&PossibleIdNSize[1], --ReadIndex);
}
if (DataStream.read(&PossibleIdNSize[ReadIndex++], 1) == 0) {
return NULL; // no more data ?
}
ReadSize++;
} while (!bFound && MaxDataSize > ReadSize);
if (!bFound)
// we reached the maximum we could read without a proper ID
return NULL;
SizeIdx = ReadIndex;
ReadIndex -= PossibleID_Length;
// read the data size
uint32 _SizeLength;
PossibleSizeLength = ReadIndex;
while (1) {
_SizeLength = PossibleSizeLength;
SizeFound = ReadCodedSizeValue(&PossibleIdNSize[PossibleID_Length], _SizeLength, SizeUnknown);
if (_SizeLength != 0) {
bFound = true;
break;
}
if (PossibleSizeLength >= 8) {
bFound = false;
break;
}
if( DataStream.read( &PossibleIdNSize[SizeIdx++], 1 ) == 0 ) {
return NULL; // no more data ?
}
ReadSize++;
PossibleSizeLength++;
}
if (bFound) {
// find the element in the context and use the correct creator
EbmlId PossibleID(PossibleIdNSize, PossibleID_Length);
EbmlElement * Result = CreateElementUsingContext(PossibleID, Context, UpperLevel, false, AllowDummyElt, MaxLowerLevel);
///< \todo continue is misplaced
if (Result != NULL) {
if (AllowDummyElt || !Result->IsDummy()) {
Result->SetSizeLength(_SizeLength);
Result->Size = SizeFound;
// UpperLevel values
// -1 : global element
// 0 : child
// 1 : same level
// + : further parent
if (Result->ValidateSize() && (SizeFound == SizeUnknown || UpperLevel > 0 || MaxDataSize == 0 || MaxDataSize >= (PossibleID_Length + PossibleSizeLength + SizeFound))) {
if (SizeFound == SizeUnknown) {
Result->SetSizeInfinite();
}
Result->SizePosition = DataStream.getFilePointer() - SizeIdx + EBML_ID_LENGTH(PossibleID);
Result->ElementPosition = Result->SizePosition - EBML_ID_LENGTH(PossibleID);
// place the file at the beggining of the data
DataStream.setFilePointer(Result->SizePosition + _SizeLength);
return Result;
}
}
delete Result;
}
}
// recover all the data in the buffer minus one byte
ReadIndex = SizeIdx - 1;
memmove(&PossibleIdNSize[0], &PossibleIdNSize[1], ReadIndex);
UpperLevel = UpperLevel_original;
} while ( MaxDataSize > DataStream.getFilePointer() - SizeIdx + PossibleID_Length );
return NULL;
} | 1 | CVE-2019-13615 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 6,000 |
advancecomp | 7894a6e684ce68ddff9f4f4919ab8e3911ac8040 | void png_compress_palette_delta(data_ptr& out_ptr, unsigned& out_size, const unsigned char* pal_ptr, unsigned pal_size, const unsigned char* prev_ptr, unsigned prev_size)
{
unsigned i;
unsigned char* dst_ptr;
unsigned dst_size;
dst_ptr = data_alloc(pal_size * 2);
dst_size = 0;
dst_ptr[dst_size++] = 0; /* replacement */
i = 0;
while (i<pal_size) {
unsigned j;
while (i < pal_size && (i < prev_size && prev_ptr[i] == pal_ptr[i] && prev_ptr[i+1] == pal_ptr[i+1] && prev_ptr[i+2] == pal_ptr[i+2]))
i += 3;
if (i == pal_size)
break;
j = i + 3;
while (j < pal_size && (j >= prev_size || prev_ptr[j] != pal_ptr[j] || prev_ptr[j+1] != pal_ptr[j+1] || prev_ptr[j+2] != pal_ptr[j+2]))
j += 3;
dst_ptr[dst_size++] = i / 3; /* first index */
dst_ptr[dst_size++] = (j / 3) - 1; /* last index */
while (i < j) {
dst_ptr[dst_size++] = pal_ptr[i++];
dst_ptr[dst_size++] = pal_ptr[i++];
dst_ptr[dst_size++] = pal_ptr[i++];
}
}
if (dst_size == 1) {
out_ptr = 0;
out_size = 0;
free(dst_ptr);
} else {
out_ptr = dst_ptr;
out_size = dst_size;
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,024 |
ceph | ff72c50a2c43c57aead933eb4903ad1ca6d1748a | static int drop_privileges(CephContext *ctx)
{
uid_t uid = ctx->get_set_uid();
gid_t gid = ctx->get_set_gid();
std::string uid_string = ctx->get_set_uid_string();
std::string gid_string = ctx->get_set_gid_string();
if (gid && setgid(gid) != 0) {
int err = errno;
ldout(ctx, -1) << "unable to setgid " << gid << ": " << cpp_strerror(err) << dendl;
return -err;
}
if (uid && setuid(uid) != 0) {
int err = errno;
ldout(ctx, -1) << "unable to setuid " << uid << ": " << cpp_strerror(err) << dendl;
return -err;
}
if (uid && gid) {
ldout(ctx, 0) << "set uid:gid to " << uid << ":" << gid
<< " (" << uid_string << ":" << gid_string << ")" << dendl;
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,992 |
Chrome | 5925dff83699508b5e2735afb0297dfb310e159d | void Browser::WindowFullscreenStateChanged() {
UpdateCommandsForFullscreenMode(window_->IsFullscreen());
UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN);
MessageLoop::current()->PostTask(
FROM_HERE, method_factory_.NewRunnableMethod(
&Browser::NotifyFullscreenChange));
if (!window_->IsFullscreen())
NotifyTabOfFullscreenExitIfNecessary();
}
| 1 | CVE-2011-3896 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 1,442 |
Chrome | f335421145bb7f82c60fb9d61babcd6ce2e4b21e | GURL Extension::GetResourceURL(const GURL& extension_url,
const std::string& relative_path) {
DCHECK(extension_url.SchemeIs(extensions::kExtensionScheme));
DCHECK_EQ("/", extension_url.path());
std::string path = relative_path;
if (relative_path.size() > 0 && relative_path[0] == '/')
path = relative_path.substr(1);
GURL ret_val = GURL(extension_url.spec() + path);
DCHECK(StartsWithASCII(ret_val.spec(), extension_url.spec(), false));
return ret_val;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,677 |
Chrome | dc7b094a338c6c521f918f478e993f0f74bbea0d | void ConnectPanelServiceSignals() {
if (!ibus_) {
return;
}
IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE(
g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey));
if (!ibus_panel_service) {
LOG(ERROR) << "IBusPanelService is NOT available.";
return;
}
g_signal_connect(ibus_panel_service,
"focus-in",
G_CALLBACK(FocusInCallback),
this);
g_signal_connect(ibus_panel_service,
"register-properties",
G_CALLBACK(RegisterPropertiesCallback),
this);
g_signal_connect(ibus_panel_service,
"update-property",
G_CALLBACK(UpdatePropertyCallback),
this);
}
| 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 | 3,959 |
ImageMagick | c073a7712d82476b5fbee74856c46b88af9c3175 | static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\052",4) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\052\000",4) == 0)
return(MagickTrue);
#if defined(TIFF_VERSION_BIG)
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0)
return(MagickTrue);
#endif
return(MagickFalse);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,204 |
ImageMagick | 73fb0aac5b958521e1511e179ecc0ad49f70ebaf | static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
IndexPacket
index;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
offset,
pixel_info_length;
ssize_t
count,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->matte=flags & 0x04 ? MagickTrue : MagickFalse;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
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);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate RLE pixels.
*/
if (image->matte != MagickFalse)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
MagickMax(number_planes_filled,4)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*
MagickMax(number_planes_filled,4);
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->matte == MagickFalse)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
operand++;
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
p=pixels+offset;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,*p & mask,&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(size_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
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 colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p);
image->colormap[i].green=ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->matte == MagickFalse)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
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);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelRed(q,image->colormap[(ssize_t) index].red);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelGreen(q,image->colormap[(ssize_t) index].green);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelBlue(q,image->colormap[(ssize_t) index].blue);
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelPacket *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
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;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 1 | CVE-2016-10050 | 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,580 |
oniguruma | 0f7f61ed1b7b697e283e37bd2d731d0bd57adb55 | conv_swap2bytes(const UChar* s, const UChar* end, UChar* conv)
{
while (s < end) {
*conv++ = s[1];
*conv++ = s[0];
s += 2;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,141 |
opencv | c96850ba599ada02dad6bd1a4271ce8f4f20e246 | bool DISOpticalFlowImpl::ocl_PatchInverseSearch(UMat &src_Ux, UMat &src_Uy,
UMat &I0, UMat &I1, UMat &I0x, UMat &I0y, int num_iter, int pyr_level)
{
size_t globalSize[] = {(size_t)ws, (size_t)hs};
size_t localSize[] = {16, 16};
int idx;
int num_inner_iter = (int)floor(grad_descent_iter / (float)num_iter);
for (int iter = 0; iter < num_iter; iter++)
{
if (iter == 0)
{
ocl::Kernel k1("dis_patch_inverse_search_fwd_1", ocl::video::dis_flow_oclsrc);
size_t global_sz[] = {(size_t)hs * 8};
size_t local_sz[] = {8};
idx = 0;
idx = k1.set(idx, ocl::KernelArg::PtrReadOnly(src_Ux));
idx = k1.set(idx, ocl::KernelArg::PtrReadOnly(src_Uy));
idx = k1.set(idx, ocl::KernelArg::PtrReadOnly(I0));
idx = k1.set(idx, ocl::KernelArg::PtrReadOnly(I1));
idx = k1.set(idx, (int)border_size);
idx = k1.set(idx, (int)patch_size);
idx = k1.set(idx, (int)patch_stride);
idx = k1.set(idx, (int)w);
idx = k1.set(idx, (int)h);
idx = k1.set(idx, (int)ws);
idx = k1.set(idx, (int)hs);
idx = k1.set(idx, (int)pyr_level);
idx = k1.set(idx, ocl::KernelArg::PtrWriteOnly(u_Sx));
idx = k1.set(idx, ocl::KernelArg::PtrWriteOnly(u_Sy));
if (!k1.run(1, global_sz, local_sz, false))
return false;
ocl::Kernel k2("dis_patch_inverse_search_fwd_2", ocl::video::dis_flow_oclsrc);
idx = 0;
idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(src_Ux));
idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(src_Uy));
idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(I0));
idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(I1));
idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(I0x));
idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(I0y));
idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0xx_buf));
idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0yy_buf));
idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0xy_buf));
idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0x_buf));
idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0y_buf));
idx = k2.set(idx, (int)border_size);
idx = k2.set(idx, (int)patch_size);
idx = k2.set(idx, (int)patch_stride);
idx = k2.set(idx, (int)w);
idx = k2.set(idx, (int)h);
idx = k2.set(idx, (int)ws);
idx = k2.set(idx, (int)hs);
idx = k2.set(idx, (int)num_inner_iter);
idx = k2.set(idx, (int)pyr_level);
idx = k2.set(idx, ocl::KernelArg::PtrReadWrite(u_Sx));
idx = k2.set(idx, ocl::KernelArg::PtrReadWrite(u_Sy));
if (!k2.run(2, globalSize, localSize, false))
return false;
}
else
{
ocl::Kernel k3("dis_patch_inverse_search_bwd_1", ocl::video::dis_flow_oclsrc);
size_t global_sz[] = {(size_t)hs * 8};
size_t local_sz[] = {8};
idx = 0;
idx = k3.set(idx, ocl::KernelArg::PtrReadOnly(I0));
idx = k3.set(idx, ocl::KernelArg::PtrReadOnly(I1));
idx = k3.set(idx, (int)border_size);
idx = k3.set(idx, (int)patch_size);
idx = k3.set(idx, (int)patch_stride);
idx = k3.set(idx, (int)w);
idx = k3.set(idx, (int)h);
idx = k3.set(idx, (int)ws);
idx = k3.set(idx, (int)hs);
idx = k3.set(idx, (int)pyr_level);
idx = k3.set(idx, ocl::KernelArg::PtrReadWrite(u_Sx));
idx = k3.set(idx, ocl::KernelArg::PtrReadWrite(u_Sy));
if (!k3.run(1, global_sz, local_sz, false))
return false;
ocl::Kernel k4("dis_patch_inverse_search_bwd_2", ocl::video::dis_flow_oclsrc);
idx = 0;
idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(I0));
idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(I1));
idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(I0x));
idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(I0y));
idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0xx_buf));
idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0yy_buf));
idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0xy_buf));
idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0x_buf));
idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0y_buf));
idx = k4.set(idx, (int)border_size);
idx = k4.set(idx, (int)patch_size);
idx = k4.set(idx, (int)patch_stride);
idx = k4.set(idx, (int)w);
idx = k4.set(idx, (int)h);
idx = k4.set(idx, (int)ws);
idx = k4.set(idx, (int)hs);
idx = k4.set(idx, (int)num_inner_iter);
idx = k4.set(idx, ocl::KernelArg::PtrReadWrite(u_Sx));
idx = k4.set(idx, ocl::KernelArg::PtrReadWrite(u_Sy));
if (!k4.run(2, globalSize, localSize, false))
return false;
}
}
return true;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,830 |
libexpat | f0bec73b018caa07d3e75ec8dd967f3785d71bde | XML_GetBuffer(XML_Parser parser, int len)
{
if (len < 0) {
errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
switch (ps_parsing) {
case XML_SUSPENDED:
errorCode = XML_ERROR_SUSPENDED;
return NULL;
case XML_FINISHED:
errorCode = XML_ERROR_FINISHED;
return NULL;
default: ;
}
if (len > bufferLim - bufferEnd) {
#ifdef XML_CONTEXT_BYTES
int keep;
#endif /* defined XML_CONTEXT_BYTES */
/* Do not invoke signed arithmetic overflow: */
int neededSize = (int) ((unsigned)len + (unsigned)(bufferEnd - bufferPtr));
if (neededSize < 0) {
errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
#ifdef XML_CONTEXT_BYTES
keep = (int)(bufferPtr - buffer);
if (keep > XML_CONTEXT_BYTES)
keep = XML_CONTEXT_BYTES;
neededSize += keep;
#endif /* defined XML_CONTEXT_BYTES */
if (neededSize <= bufferLim - buffer) {
#ifdef XML_CONTEXT_BYTES
if (keep < bufferPtr - buffer) {
int offset = (int)(bufferPtr - buffer) - keep;
memmove(buffer, &buffer[offset], bufferEnd - bufferPtr + keep);
bufferEnd -= offset;
bufferPtr -= offset;
}
#else
memmove(buffer, bufferPtr, bufferEnd - bufferPtr);
bufferEnd = buffer + (bufferEnd - bufferPtr);
bufferPtr = buffer;
#endif /* not defined XML_CONTEXT_BYTES */
}
else {
char *newBuf;
int bufferSize = (int)(bufferLim - bufferPtr);
if (bufferSize == 0)
bufferSize = INIT_BUFFER_SIZE;
do {
/* Do not invoke signed arithmetic overflow: */
bufferSize = (int) (2U * (unsigned) bufferSize);
} while (bufferSize < neededSize && bufferSize > 0);
if (bufferSize <= 0) {
errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
newBuf = (char *)MALLOC(bufferSize);
if (newBuf == 0) {
errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
bufferLim = newBuf + bufferSize;
#ifdef XML_CONTEXT_BYTES
if (bufferPtr) {
int keep = (int)(bufferPtr - buffer);
if (keep > XML_CONTEXT_BYTES)
keep = XML_CONTEXT_BYTES;
memcpy(newBuf, &bufferPtr[-keep], bufferEnd - bufferPtr + keep);
FREE(buffer);
buffer = newBuf;
bufferEnd = buffer + (bufferEnd - bufferPtr) + keep;
bufferPtr = buffer + keep;
}
else {
bufferEnd = newBuf + (bufferEnd - bufferPtr);
bufferPtr = buffer = newBuf;
}
#else
if (bufferPtr) {
memcpy(newBuf, bufferPtr, bufferEnd - bufferPtr);
FREE(buffer);
}
bufferEnd = newBuf + (bufferEnd - bufferPtr);
bufferPtr = buffer = newBuf;
#endif /* not defined XML_CONTEXT_BYTES */
}
eventPtr = eventEndPtr = NULL;
positionPtr = NULL;
}
return bufferEnd;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,717 |
linux | d4122754442799187d5d537a9c039a49a67e57f1 | static int spk_ttyio_ldisc_open(struct tty_struct *tty)
{
struct spk_ldisc_data *ldisc_data;
if (!tty->ops->write)
return -EOPNOTSUPP;
speakup_tty = tty;
ldisc_data = kmalloc(sizeof(*ldisc_data), GFP_KERNEL);
if (!ldisc_data)
return -ENOMEM;
init_completion(&ldisc_data->completion);
ldisc_data->buf_free = true;
speakup_tty->disc_data = ldisc_data;
return 0;
} | 1 | CVE-2020-28941 | 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,504 |
php-src | 7245bff300d3fa8bacbef7897ff080a6f1c23eba?w=1 | SPL_METHOD(FilesystemIterator, current)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
RETURN_STRINGL(intern->file_name, intern->file_name_len, 1);
} else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) {
spl_filesystem_object_get_file_name(intern TSRMLS_CC);
spl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC);
} else {
RETURN_ZVAL(getThis(), 1, 0);
/*RETURN_STRING(intern->u.dir.entry.d_name, 1);*/
}
}
| 1 | CVE-2016-5770 | CWE-190 | Integer Overflow or Wraparound | The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number. | Phase: Requirements
Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol.
Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
If possible, choose a language or compiler that performs automatic bounds checking.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Use libraries or frameworks that make it easier to handle numbers without unexpected consequences.
Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106]
Phase: Implementation
Strategy: Input Validation
Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.
Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values.
Phase: Implementation
Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7]
Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Phase: Implementation
Strategy: Compilation or Build Hardening
Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system. | 1,440 |
Chrome | 2649de11c562aa96d336c06136a1a20c01711be0 | bool IsSensitiveURL(const GURL& url,
bool is_request_from_browser_or_webui_renderer) {
bool sensitive_chrome_url = false;
const char kGoogleCom[] = "google.com";
const char kClient[] = "clients";
url::Origin origin = url::Origin::Create(url);
if (origin.DomainIs(kGoogleCom)) {
base::StringPiece host = url.host_piece();
while (host.ends_with("."))
host.remove_suffix(1u);
if (is_request_from_browser_or_webui_renderer) {
base::StringPiece::size_type pos = host.rfind(kClient);
if (pos != base::StringPiece::npos) {
bool match = true;
if (pos > 0 && host[pos - 1] != '.') {
match = false;
} else {
for (base::StringPiece::const_iterator
i = host.begin() + pos + strlen(kClient),
end = host.end() - (strlen(kGoogleCom) + 1);
i != end; ++i) {
if (!isdigit(*i)) {
match = false;
break;
}
}
}
sensitive_chrome_url = sensitive_chrome_url || match;
}
}
sensitive_chrome_url = sensitive_chrome_url ||
(url.DomainIs("chrome.google.com") &&
base::StartsWith(url.path_piece(), "/webstore",
base::CompareCase::SENSITIVE));
}
return sensitive_chrome_url || extension_urls::IsWebstoreUpdateUrl(url) ||
extension_urls::IsBlacklistUpdateUrl(url) ||
extension_urls::IsSafeBrowsingUrl(origin, url.path_piece());
}
| 1 | CVE-2018-6035 | 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. | 751 |
Android | 04839626ed859623901ebd3a5fd483982186b59d | const Block* SimpleBlock::GetBlock() const
{
return &m_block;
}
| 1 | CVE-2016-1621 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 7,009 |
linux | d1e7fd6462ca9fc76650fbe6ca800e35b24267da | static inline int is_si_special(const struct kernel_siginfo *info)
{
return info <= SEND_SIG_PRIV;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,370 |
linux-2.6 | 89f5b7da2a6bad2e84670422ab8192382a5aeb9f | int get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
unsigned long start, int len, int write, int force,
struct page **pages, struct vm_area_struct **vmas)
{
int i;
unsigned int vm_flags;
if (len <= 0)
return 0;
/*
* Require read or write permissions.
* If 'force' is set, we only require the "MAY" flags.
*/
vm_flags = write ? (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
vm_flags &= force ? (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
i = 0;
do {
struct vm_area_struct *vma;
unsigned int foll_flags;
vma = find_extend_vma(mm, start);
if (!vma && in_gate_area(tsk, start)) {
unsigned long pg = start & PAGE_MASK;
struct vm_area_struct *gate_vma = get_gate_vma(tsk);
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
if (write) /* user gate pages are read-only */
return i ? : -EFAULT;
if (pg > TASK_SIZE)
pgd = pgd_offset_k(pg);
else
pgd = pgd_offset_gate(mm, pg);
BUG_ON(pgd_none(*pgd));
pud = pud_offset(pgd, pg);
BUG_ON(pud_none(*pud));
pmd = pmd_offset(pud, pg);
if (pmd_none(*pmd))
return i ? : -EFAULT;
pte = pte_offset_map(pmd, pg);
if (pte_none(*pte)) {
pte_unmap(pte);
return i ? : -EFAULT;
}
if (pages) {
struct page *page = vm_normal_page(gate_vma, start, *pte);
pages[i] = page;
if (page)
get_page(page);
}
pte_unmap(pte);
if (vmas)
vmas[i] = gate_vma;
i++;
start += PAGE_SIZE;
len--;
continue;
}
if (!vma || (vma->vm_flags & (VM_IO | VM_PFNMAP))
|| !(vm_flags & vma->vm_flags))
return i ? : -EFAULT;
if (is_vm_hugetlb_page(vma)) {
i = follow_hugetlb_page(mm, vma, pages, vmas,
&start, &len, i, write);
continue;
}
foll_flags = FOLL_TOUCH;
if (pages)
foll_flags |= FOLL_GET;
if (!write && !(vma->vm_flags & VM_LOCKED) &&
(!vma->vm_ops || !vma->vm_ops->fault))
foll_flags |= FOLL_ANON;
do {
struct page *page;
/*
* If tsk is ooming, cut off its access to large memory
* allocations. It has a pending SIGKILL, but it can't
* be processed until returning to user space.
*/
if (unlikely(test_tsk_thread_flag(tsk, TIF_MEMDIE)))
return -ENOMEM;
if (write)
foll_flags |= FOLL_WRITE;
cond_resched();
while (!(page = follow_page(vma, start, foll_flags))) {
int ret;
ret = handle_mm_fault(mm, vma, start,
foll_flags & FOLL_WRITE);
if (ret & VM_FAULT_ERROR) {
if (ret & VM_FAULT_OOM)
return i ? i : -ENOMEM;
else if (ret & VM_FAULT_SIGBUS)
return i ? i : -EFAULT;
BUG();
}
if (ret & VM_FAULT_MAJOR)
tsk->maj_flt++;
else
tsk->min_flt++;
/*
* The VM_FAULT_WRITE bit tells us that
* do_wp_page has broken COW when necessary,
* even if maybe_mkwrite decided not to set
* pte_write. We can thus safely do subsequent
* page lookups as if they were reads.
*/
if (ret & VM_FAULT_WRITE)
foll_flags &= ~FOLL_WRITE;
cond_resched();
}
if (pages) {
pages[i] = page;
flush_anon_page(vma, page, start);
flush_dcache_page(page);
}
if (vmas)
vmas[i] = vma;
i++;
start += PAGE_SIZE;
len--;
} while (len && start < vma->vm_end);
} while (len);
return i;
} | 1 | CVE-2008-2372 | 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,337 |
ImageMagick | e5c063a1007506ba69e97a35effcdef944421c89 | static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
{
while (len >= 4)
{
*data++ = ReadBlobFloat(image);
len -= sizeof(float);
}
if (len > 0)
(void) SeekBlob(image, len, SEEK_CUR);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,637 |
linux | a6e544b0a88b53114bfa5a57e21b7be7a8dfc9d0 | static __always_inline void __flow_hash_secret_init(void)
{
net_get_random_once(&hashrnd, sizeof(hashrnd));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,434 |
jasper | 5d66894d2313e3f3469f19066e149e08ff076698 | jas_matrix_t *jas_matrix_create(int numrows, int numcols)
{
jas_matrix_t *matrix;
int i;
if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {
return 0;
}
matrix->flags_ = 0;
matrix->numrows_ = numrows;
matrix->numcols_ = numcols;
matrix->rows_ = 0;
matrix->maxrows_ = numrows;
matrix->data_ = 0;
matrix->datasize_ = numrows * numcols;
if (matrix->maxrows_ > 0) {
if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_,
sizeof(jas_seqent_t *)))) {
jas_matrix_destroy(matrix);
return 0;
}
}
if (matrix->datasize_ > 0) {
if (!(matrix->data_ = jas_alloc2(matrix->datasize_,
sizeof(jas_seqent_t)))) {
jas_matrix_destroy(matrix);
return 0;
}
}
for (i = 0; i < numrows; ++i) {
matrix->rows_[i] = &matrix->data_[i * matrix->numcols_];
}
for (i = 0; i < matrix->datasize_; ++i) {
matrix->data_[i] = 0;
}
matrix->xstart_ = 0;
matrix->ystart_ = 0;
matrix->xend_ = matrix->numcols_;
matrix->yend_ = matrix->numrows_;
return matrix;
}
| 1 | CVE-2016-8884 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 2,200 |
openssl | f48b83b4fb7d6689584cf25f61ca63a4891f5b11 | int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
{
char *str;
ASN1_TIME atm;
long offset;
char buff1[24], buff2[24], *p;
int i, j;
p = buff1;
i = ctm->length;
str = (char *)ctm->data;
if (ctm->type == V_ASN1_UTCTIME) {
if ((i < 11) || (i > 17))
return 0;
memcpy(p, str, 10);
p += 10;
str += 10;
} else {
if (i < 13)
return 0;
memcpy(p, str, 12);
p += 12;
str += 12;
}
if ((*str == 'Z') || (*str == '-') || (*str == '+')) {
*(p++) = '0';
*(p++) = '0';
} else {
*(p++) = *(str++);
*(p++) = *(str++);
/* Skip any fractional seconds... */
if (*str == '.') {
str++;
while ((*str >= '0') && (*str <= '9'))
str++;
}
}
*(p++) = 'Z';
*(p++) = '\0';
if (*str == 'Z')
offset = 0;
else {
if ((*str != '+') && (*str != '-'))
return 0;
offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;
offset += (str[3] - '0') * 10 + (str[4] - '0');
if (*str == '-')
offset = -offset;
}
atm.type = ctm->type;
atm.flags = 0;
atm.length = sizeof(buff2);
atm.data = (unsigned char *)buff2;
if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)
return 0;
if (ctm->type == V_ASN1_UTCTIME) {
i = (buff1[0] - '0') * 10 + (buff1[1] - '0');
if (i < 50)
i += 100; /* cf. RFC 2459 */
j = (buff2[0] - '0') * 10 + (buff2[1] - '0');
if (j < 50)
j += 100;
if (i < j)
return -1;
if (i > j)
return 1;
}
i = strcmp(buff1, buff2);
if (i == 0) /* wait a second then return younger :-) */
return -1;
else
return i;
}
| 1 | CVE-2015-1789 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 1,446 |
Chrome | 673ce95d481ea9368c4d4d43ac756ba1d6d9e608 | void PdfCompositorClient::Composite(
service_manager::Connector* connector,
base::SharedMemoryHandle handle,
size_t data_size,
mojom::PdfCompositor::CompositePdfCallback callback,
scoped_refptr<base::SequencedTaskRunner> callback_task_runner) {
DCHECK(data_size);
if (!compositor_)
Connect(connector);
mojo::ScopedSharedBufferHandle buffer_handle =
mojo::WrapSharedMemoryHandle(handle, data_size, true);
compositor_->CompositePdf(
std::move(buffer_handle),
base::BindOnce(&OnCompositePdf, base::Passed(&compositor_),
std::move(callback), callback_task_runner));
}
| 1 | CVE-2018-6063 | CWE-787 | Out-of-bounds Write | The product writes data past the end, or before the beginning, of the intended buffer. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333].
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 6,717 |
mono | 4905ef1130feb26c3150b28b97e4a96752e0d399 | MonoReflectionMethod*
mono_reflection_bind_generic_method_parameters (MonoReflectionMethod *rmethod, MonoArray *types)
{
MonoClass *klass;
MonoMethod *method, *inflated;
MonoMethodInflated *imethod;
MonoGenericContext tmp_context;
MonoGenericInst *ginst;
MonoType **type_argv;
int count, i;
MONO_ARCH_SAVE_REGS;
if (!strcmp (rmethod->object.vtable->klass->name, "MethodBuilder")) {
#ifndef DISABLE_REFLECTION_EMIT
MonoReflectionMethodBuilder *mb = NULL;
MonoReflectionTypeBuilder *tb;
MonoClass *klass;
mb = (MonoReflectionMethodBuilder *) rmethod;
tb = (MonoReflectionTypeBuilder *) mb->type;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
method = methodbuilder_to_mono_method (klass, mb);
#else
g_assert_not_reached ();
method = NULL;
#endif
} else {
method = rmethod->method;
}
klass = method->klass;
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
count = mono_method_signature (method)->generic_param_count;
if (count != mono_array_length (types))
return NULL;
type_argv = g_new0 (MonoType *, count);
for (i = 0; i < count; i++) {
MonoReflectionType *garg = mono_array_get (types, gpointer, i);
type_argv [i] = mono_reflection_type_get_handle (garg);
}
ginst = mono_metadata_get_generic_inst (count, type_argv);
g_free (type_argv);
tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
tmp_context.method_inst = ginst;
inflated = mono_class_inflate_generic_method (method, &tmp_context);
imethod = (MonoMethodInflated *) inflated;
if (method->klass->image->dynamic) {
MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
/*
* This table maps metadata structures representing inflated methods/fields
* to the reflection objects representing their generic definitions.
*/
mono_loader_lock ();
mono_g_hash_table_insert (image->generic_def_objects, imethod, rmethod);
mono_loader_unlock ();
}
return mono_method_get_object (mono_object_domain (rmethod), inflated, NULL); | 1 | CVE-2010-4254 | 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,262 |
linux | 638164a2718f337ea224b747cf5977ef143166a4 | void f2fs_wait_discard_bios(struct f2fs_sb_info *sbi)
{
__issue_discard_cmd(sbi, false);
__drop_discard_cmd(sbi);
__wait_discard_cmd(sbi, false);
}
| 1 | CVE-2017-18200 | 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,437 |
Chrome | b654d718218ece17c496e74acd250038656f31c3 | String openTemporaryFile(const String&, PlatformFileHandle& handle)
{
handle = INVALID_HANDLE_VALUE;
wchar_t tempPath[MAX_PATH];
int tempPathLength = ::GetTempPathW(WTF_ARRAY_LENGTH(tempPath), tempPath);
if (tempPathLength <= 0 || tempPathLength > WTF_ARRAY_LENGTH(tempPath))
return String();
String proposedPath;
do {
wchar_t tempFile[] = L"XXXXXXXX.tmp"; // Use 8.3 style name (more characters aren't helpful due to 8.3 short file names)
const int randomPartLength = 8;
cryptographicallyRandomValues(tempFile, randomPartLength * sizeof(wchar_t));
const char validChars[] = "0123456789abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < randomPartLength; ++i)
tempFile[i] = validChars[tempFile[i] % (sizeof(validChars) - 1)];
ASSERT(wcslen(tempFile) == WTF_ARRAY_LENGTH(tempFile) - 1);
proposedPath = pathByAppendingComponent(tempPath, tempFile);
if (proposedPath.isEmpty())
break;
handle = ::CreateFileW(proposedPath.charactersWithNullTermination(), GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);
} while (!isHandleValid(handle) && GetLastError() == ERROR_ALREADY_EXISTS);
if (!isHandleValid(handle))
return String();
return proposedPath;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,563 |
libarchive | eec077f52bfa2d3f7103b4b74d52572ba8a15aca | next_line(struct archive_read *a,
const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)
{
ssize_t len;
int quit;
quit = 0;
if (*avail == 0) {
*nl = 0;
len = 0;
} else
len = get_line_size(*b, *avail, nl);
/*
* Read bytes more while it does not reach the end of line.
*/
while (*nl == 0 && len == *avail && !quit) {
ssize_t diff = *ravail - *avail;
size_t nbytes_req = (*ravail+1023) & ~1023U;
ssize_t tested;
/* Increase reading bytes if it is not enough to at least
* new two lines. */
if (nbytes_req < (size_t)*ravail + 160)
nbytes_req <<= 1;
*b = __archive_read_ahead(a, nbytes_req, avail);
if (*b == NULL) {
if (*ravail >= *avail)
return (0);
/* Reading bytes reaches the end of file. */
*b = __archive_read_ahead(a, *avail, avail);
quit = 1;
}
*ravail = *avail;
*b += diff;
*avail -= diff;
tested = len;/* Skip some bytes we already determinated. */
len = get_line_size(*b + len, *avail - len, nl);
if (len >= 0)
len += tested;
}
return (len);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,671 |
gnome-shell | 90c55e1977fde252b79bcfd9d0ef41144fb21fe2 | shell_gtk_embed_class_init (ShellGtkEmbedClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
ClutterActorClass *actor_class = CLUTTER_ACTOR_CLASS (klass);
object_class->get_property = shell_gtk_embed_get_property;
object_class->set_property = shell_gtk_embed_set_property;
object_class->dispose = shell_gtk_embed_dispose;
actor_class->get_preferred_width = shell_gtk_embed_get_preferred_width;
actor_class->get_preferred_height = shell_gtk_embed_get_preferred_height;
actor_class->allocate = shell_gtk_embed_allocate;
actor_class->map = shell_gtk_embed_map;
actor_class->unmap = shell_gtk_embed_unmap;
g_object_class_install_property (object_class,
PROP_WINDOW,
g_param_spec_object ("window",
"Window",
"ShellEmbeddedWindow to embed",
SHELL_TYPE_EMBEDDED_WINDOW,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,307 |
linux | e461fcb194172b3f709e0b478d2ac1bdac7ab9a3 | xfs_attr3_leaf_compact(
struct xfs_da_args *args,
struct xfs_attr3_icleaf_hdr *ichdr_d,
struct xfs_buf *bp)
{
xfs_attr_leafblock_t *leaf_s, *leaf_d;
struct xfs_attr3_icleaf_hdr ichdr_s;
struct xfs_trans *trans = args->trans;
struct xfs_mount *mp = trans->t_mountp;
char *tmpbuffer;
trace_xfs_attr_leaf_compact(args);
tmpbuffer = kmem_alloc(XFS_LBSIZE(mp), KM_SLEEP);
ASSERT(tmpbuffer != NULL);
memcpy(tmpbuffer, bp->b_addr, XFS_LBSIZE(mp));
memset(bp->b_addr, 0, XFS_LBSIZE(mp));
/*
* Copy basic information
*/
leaf_s = (xfs_attr_leafblock_t *)tmpbuffer;
leaf_d = bp->b_addr;
ichdr_s = *ichdr_d; /* struct copy */
ichdr_d->firstused = XFS_LBSIZE(mp);
ichdr_d->usedbytes = 0;
ichdr_d->count = 0;
ichdr_d->holes = 0;
ichdr_d->freemap[0].base = xfs_attr3_leaf_hdr_size(leaf_s);
ichdr_d->freemap[0].size = ichdr_d->firstused - ichdr_d->freemap[0].base;
/*
* Copy all entry's in the same (sorted) order,
* but allocate name/value pairs packed and in sequence.
*/
xfs_attr3_leaf_moveents(leaf_s, &ichdr_s, 0, leaf_d, ichdr_d, 0,
ichdr_s.count, mp);
/*
* this logs the entire buffer, but the caller must write the header
* back to the buffer when it is finished modifying it.
*/
xfs_trans_log_buf(trans, bp, 0, XFS_LBSIZE(mp) - 1);
kmem_free(tmpbuffer);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,218 |
linux | 208c72f4fe44fe09577e7975ba0e7fa0278f3d03 | void nl80211_send_mgmt_tx_status(struct cfg80211_registered_device *rdev,
struct net_device *netdev, u64 cookie,
const u8 *buf, size_t len, bool ack,
gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_FRAME_TX_STATUS);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_FRAME, len, buf);
NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, cookie);
if (ack)
NLA_PUT_FLAG(msg, NL80211_ATTR_ACK);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast(msg, 0, nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,407 |
Chrome | 3a353ebdb7753a3fbeb401c4c0e0f3358ccbb90b | DelayNode* BaseAudioContext::createDelay(ExceptionState& exception_state) {
DCHECK(IsMainThread());
return DelayNode::Create(*this, exception_state);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,891 |
Android | 5a9753fca56f0eeb9f61e342b2fccffc364f9426 | void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride);
}
| 1 | CVE-2016-1621 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 4,894 |
Chrome | 3514a77e7fa2e5b8bfe5d98af22964bbd69d680f | void ProcessStateChangesPlanB(WebRtcSetDescriptionObserver::States states) {
DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kPlanB);
std::vector<RTCRtpReceiver*> removed_receivers;
for (auto it = handler_->rtp_receivers_.begin();
it != handler_->rtp_receivers_.end(); ++it) {
if (ReceiverWasRemoved(*(*it), states.transceiver_states))
removed_receivers.push_back(it->get());
}
for (auto& transceiver_state : states.transceiver_states) {
if (ReceiverWasAdded(transceiver_state)) {
handler_->OnAddReceiverPlanB(transceiver_state.MoveReceiverState());
}
}
for (auto* removed_receiver : removed_receivers) {
handler_->OnRemoveReceiverPlanB(RTCRtpReceiver::getId(
removed_receiver->state().webrtc_receiver().get()));
}
}
| 1 | CVE-2019-5760 | CWE-416 | Use After Free | The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
Phase: Architecture and Design
Strategy: Language Selection
Choose a language that provides automatic memory management.
Phase: Implementation
Strategy: Attack Surface Reduction
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.
Effectiveness: Defense in Depth
Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution. | 9,579 |
Android | 45c97f878bee15cd97262fe7f57ecea71990fed7 | IHEVCD_ERROR_T ihevcd_parse_pps(codec_t *ps_codec)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 value;
WORD32 pps_id;
pps_t *ps_pps;
sps_t *ps_sps;
bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm;
if(0 == ps_codec->i4_sps_done)
return IHEVCD_INVALID_HEADER;
UEV_PARSE("pic_parameter_set_id", value, ps_bitstrm);
pps_id = value;
if((pps_id >= MAX_PPS_CNT) || (pps_id < 0))
{
if(ps_codec->i4_pps_done)
return IHEVCD_UNSUPPORTED_PPS_ID;
else
pps_id = 0;
}
ps_pps = (ps_codec->s_parse.ps_pps_base + MAX_PPS_CNT - 1);
ps_pps->i1_pps_id = pps_id;
UEV_PARSE("seq_parameter_set_id", value, ps_bitstrm);
ps_pps->i1_sps_id = value;
ps_pps->i1_sps_id = CLIP3(ps_pps->i1_sps_id, 0, MAX_SPS_CNT - 2);
ps_sps = (ps_codec->s_parse.ps_sps_base + ps_pps->i1_sps_id);
/* If the SPS that is being referred to has not been parsed,
* copy an existing SPS to the current location */
if(0 == ps_sps->i1_sps_valid)
{
return IHEVCD_INVALID_HEADER;
/*
sps_t *ps_sps_ref = ps_codec->ps_sps_base;
while(0 == ps_sps_ref->i1_sps_valid)
ps_sps_ref++;
ihevcd_copy_sps(ps_codec, ps_pps->i1_sps_id, ps_sps_ref->i1_sps_id);
*/
}
BITS_PARSE("dependent_slices_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_dependent_slice_enabled_flag = value;
BITS_PARSE("output_flag_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_output_flag_present_flag = value;
BITS_PARSE("num_extra_slice_header_bits", value, ps_bitstrm, 3);
ps_pps->i1_num_extra_slice_header_bits = value;
BITS_PARSE("sign_data_hiding_flag", value, ps_bitstrm, 1);
ps_pps->i1_sign_data_hiding_flag = value;
BITS_PARSE("cabac_init_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_cabac_init_present_flag = value;
UEV_PARSE("num_ref_idx_l0_default_active_minus1", value, ps_bitstrm);
ps_pps->i1_num_ref_idx_l0_default_active = value + 1;
UEV_PARSE("num_ref_idx_l1_default_active_minus1", value, ps_bitstrm);
ps_pps->i1_num_ref_idx_l1_default_active = value + 1;
SEV_PARSE("pic_init_qp_minus26", value, ps_bitstrm);
ps_pps->i1_pic_init_qp = value + 26;
BITS_PARSE("constrained_intra_pred_flag", value, ps_bitstrm, 1);
ps_pps->i1_constrained_intra_pred_flag = value;
BITS_PARSE("transform_skip_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_transform_skip_enabled_flag = value;
BITS_PARSE("cu_qp_delta_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_cu_qp_delta_enabled_flag = value;
if(ps_pps->i1_cu_qp_delta_enabled_flag)
{
UEV_PARSE("diff_cu_qp_delta_depth", value, ps_bitstrm);
ps_pps->i1_diff_cu_qp_delta_depth = value;
}
else
{
ps_pps->i1_diff_cu_qp_delta_depth = 0;
}
ps_pps->i1_log2_min_cu_qp_delta_size = ps_sps->i1_log2_ctb_size - ps_pps->i1_diff_cu_qp_delta_depth;
/* Print different */
SEV_PARSE("cb_qp_offset", value, ps_bitstrm);
ps_pps->i1_pic_cb_qp_offset = value;
/* Print different */
SEV_PARSE("cr_qp_offset", value, ps_bitstrm);
ps_pps->i1_pic_cr_qp_offset = value;
/* Print different */
BITS_PARSE("slicelevel_chroma_qp_flag", value, ps_bitstrm, 1);
ps_pps->i1_pic_slice_level_chroma_qp_offsets_present_flag = value;
BITS_PARSE("weighted_pred_flag", value, ps_bitstrm, 1);
ps_pps->i1_weighted_pred_flag = value;
BITS_PARSE("weighted_bipred_flag", value, ps_bitstrm, 1);
ps_pps->i1_weighted_bipred_flag = value;
BITS_PARSE("transquant_bypass_enable_flag", value, ps_bitstrm, 1);
ps_pps->i1_transquant_bypass_enable_flag = value;
BITS_PARSE("tiles_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_tiles_enabled_flag = value;
BITS_PARSE("entropy_coding_sync_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_entropy_coding_sync_enabled_flag = value;
ps_pps->i1_loop_filter_across_tiles_enabled_flag = 0;
if(ps_pps->i1_tiles_enabled_flag)
{
UEV_PARSE("num_tile_columns_minus1", value, ps_bitstrm);
ps_pps->i1_num_tile_columns = value + 1;
UEV_PARSE("num_tile_rows_minus1", value, ps_bitstrm);
ps_pps->i1_num_tile_rows = value + 1;
if((ps_pps->i1_num_tile_columns < 1) ||
(ps_pps->i1_num_tile_columns > ps_sps->i2_pic_wd_in_ctb) ||
(ps_pps->i1_num_tile_rows < 1) ||
(ps_pps->i1_num_tile_rows > ps_sps->i2_pic_ht_in_ctb))
return IHEVCD_INVALID_HEADER;
BITS_PARSE("uniform_spacing_flag", value, ps_bitstrm, 1);
ps_pps->i1_uniform_spacing_flag = value;
{
WORD32 start;
WORD32 i, j;
start = 0;
for(i = 0; i < ps_pps->i1_num_tile_columns; i++)
{
tile_t *ps_tile;
if(!ps_pps->i1_uniform_spacing_flag)
{
if(i < (ps_pps->i1_num_tile_columns - 1))
{
UEV_PARSE("column_width_minus1[ i ]", value, ps_bitstrm);
value += 1;
}
else
{
value = ps_sps->i2_pic_wd_in_ctb - start;
}
}
else
{
value = ((i + 1) * ps_sps->i2_pic_wd_in_ctb) / ps_pps->i1_num_tile_columns -
(i * ps_sps->i2_pic_wd_in_ctb) / ps_pps->i1_num_tile_columns;
}
for(j = 0; j < ps_pps->i1_num_tile_rows; j++)
{
ps_tile = ps_pps->ps_tile + j * ps_pps->i1_num_tile_columns + i;
ps_tile->u1_pos_x = start;
ps_tile->u2_wd = value;
}
start += value;
if((start > ps_sps->i2_pic_wd_in_ctb) ||
(value <= 0))
return IHEVCD_INVALID_HEADER;
}
start = 0;
for(i = 0; i < (ps_pps->i1_num_tile_rows); i++)
{
tile_t *ps_tile;
if(!ps_pps->i1_uniform_spacing_flag)
{
if(i < (ps_pps->i1_num_tile_rows - 1))
{
UEV_PARSE("row_height_minus1[ i ]", value, ps_bitstrm);
value += 1;
}
else
{
value = ps_sps->i2_pic_ht_in_ctb - start;
}
}
else
{
value = ((i + 1) * ps_sps->i2_pic_ht_in_ctb) / ps_pps->i1_num_tile_rows -
(i * ps_sps->i2_pic_ht_in_ctb) / ps_pps->i1_num_tile_rows;
}
for(j = 0; j < ps_pps->i1_num_tile_columns; j++)
{
ps_tile = ps_pps->ps_tile + i * ps_pps->i1_num_tile_columns + j;
ps_tile->u1_pos_y = start;
ps_tile->u2_ht = value;
}
start += value;
if((start > ps_sps->i2_pic_ht_in_ctb) ||
(value <= 0))
return IHEVCD_INVALID_HEADER;
}
}
BITS_PARSE("loop_filter_across_tiles_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_loop_filter_across_tiles_enabled_flag = value;
}
else
{
/* If tiles are not present, set first tile in each PPS to have tile
width and height equal to picture width and height */
ps_pps->i1_num_tile_columns = 1;
ps_pps->i1_num_tile_rows = 1;
ps_pps->i1_uniform_spacing_flag = 1;
ps_pps->ps_tile->u1_pos_x = 0;
ps_pps->ps_tile->u1_pos_y = 0;
ps_pps->ps_tile->u2_wd = ps_sps->i2_pic_wd_in_ctb;
ps_pps->ps_tile->u2_ht = ps_sps->i2_pic_ht_in_ctb;
}
BITS_PARSE("loop_filter_across_slices_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_loop_filter_across_slices_enabled_flag = value;
BITS_PARSE("deblocking_filter_control_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_deblocking_filter_control_present_flag = value;
/* Default values */
ps_pps->i1_pic_disable_deblocking_filter_flag = 0;
ps_pps->i1_deblocking_filter_override_enabled_flag = 0;
ps_pps->i1_beta_offset_div2 = 0;
ps_pps->i1_tc_offset_div2 = 0;
if(ps_pps->i1_deblocking_filter_control_present_flag)
{
BITS_PARSE("deblocking_filter_override_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_deblocking_filter_override_enabled_flag = value;
BITS_PARSE("pic_disable_deblocking_filter_flag", value, ps_bitstrm, 1);
ps_pps->i1_pic_disable_deblocking_filter_flag = value;
if(!ps_pps->i1_pic_disable_deblocking_filter_flag)
{
SEV_PARSE("pps_beta_offset_div2", value, ps_bitstrm);
ps_pps->i1_beta_offset_div2 = value;
SEV_PARSE("pps_tc_offset_div2", value, ps_bitstrm);
ps_pps->i1_tc_offset_div2 = value;
}
}
BITS_PARSE("pps_scaling_list_data_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_pps_scaling_list_data_present_flag = value;
if(ps_pps->i1_pps_scaling_list_data_present_flag)
{
COPY_DEFAULT_SCALING_LIST(ps_pps->pi2_scaling_mat);
ihevcd_scaling_list_data(ps_codec, ps_pps->pi2_scaling_mat);
}
BITS_PARSE("lists_modification_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_lists_modification_present_flag = value;
UEV_PARSE("log2_parallel_merge_level_minus2", value, ps_bitstrm);
ps_pps->i1_log2_parallel_merge_level = value + 2;
BITS_PARSE("slice_header_extension_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_slice_header_extension_present_flag = value;
/* Not present in HM */
BITS_PARSE("pps_extension_flag", value, ps_bitstrm, 1);
ps_codec->i4_pps_done = 1;
return ret;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,603 |
savannah | 40cc957f52e772f45125126439ba9333cf2d2998 | Tar::Tar(wxString &szFile, wxString &szCompressDir) :
DFile(szFile)
{
strCompressDir = szCompressDir;
bCanCompress = true;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,690 |
linux | 338f977f4eb441e69bb9a46eaa0ac715c931a67f | bool ieee80211_tx_prepare_skb(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, struct sk_buff *skb,
int band, struct ieee80211_sta **sta)
{
struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif);
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_tx_data tx;
if (ieee80211_tx_prepare(sdata, &tx, skb) == TX_DROP)
return false;
info->band = band;
info->control.vif = vif;
info->hw_queue = vif->hw_queue[skb_get_queue_mapping(skb)];
if (invoke_tx_handlers(&tx))
return false;
if (sta) {
if (tx.sta)
*sta = &tx.sta->sta;
else
*sta = NULL;
}
return true;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,027 |
php-src | a15bffd105ac28fd0dd9b596632dbf035238fda3 | static zend_bool php_auto_globals_create_cookie(zend_string *name)
{
if (PG(variables_order) && (strchr(PG(variables_order),'C') || strchr(PG(variables_order),'c'))) {
sapi_module.treat_data(PARSE_COOKIE, NULL, NULL);
} else {
zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_COOKIE]);
array_init(&PG(http_globals)[TRACK_VARS_COOKIE]);
}
zend_hash_update(&EG(symbol_table), name, &PG(http_globals)[TRACK_VARS_COOKIE]);
Z_ADDREF(PG(http_globals)[TRACK_VARS_COOKIE]);
return 0; /* don't rearm */
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,699 |
linux | a2d859e3fc97e79d907761550dbc03ff1b36479c | struct sctp_association *sctp_make_temp_asoc(const struct sctp_endpoint *ep,
struct sctp_chunk *chunk,
gfp_t gfp)
{
struct sctp_association *asoc;
enum sctp_scope scope;
struct sk_buff *skb;
/* Create the bare association. */
scope = sctp_scope(sctp_source(chunk));
asoc = sctp_association_new(ep, ep->base.sk, scope, gfp);
if (!asoc)
goto nodata;
asoc->temp = 1;
skb = chunk->skb;
/* Create an entry for the source address of the packet. */
SCTP_INPUT_CB(skb)->af->from_skb(&asoc->c.peer_addr, skb, 1);
nodata:
return asoc;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,867 |
qemu | 5193be3be35f29a35bc465036cd64ad60d43385f | static void tsc2102_data_register_write(
TSC210xState *s, int reg, uint16_t value)
{
switch (reg) {
case 0x00: /* X */
case 0x01: /* Y */
case 0x02: /* Z1 */
case 0x03: /* Z2 */
case 0x05: /* BAT1 */
case 0x06: /* BAT2 */
case 0x07: /* AUX1 */
case 0x08: /* AUX2 */
case 0x09: /* TEMP1 */
case 0x0a: /* TEMP2 */
return;
default:
#ifdef TSC_VERBOSE
fprintf(stderr, "tsc2102_data_register_write: "
"no such register: 0x%02x\n", reg);
#endif
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,050 |
linux | d7a6be58edc01b1c66ecd8fcc91236bfbce0a420 | static int available_error_type_open(struct inode *inode, struct file *file)
{
return single_open(file, available_error_type_show, NULL);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,525 |
git | fd55a19eb1d49ae54008d932a65f79cd6fda45c9 | void diff_change(struct diff_options *options,
unsigned old_mode, unsigned new_mode,
const unsigned char *old_sha1,
const unsigned char *new_sha1,
const char *base, const char *path)
{
char concatpath[PATH_MAX];
struct diff_filespec *one, *two;
if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
&& S_ISGITLINK(new_mode))
return;
if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
unsigned tmp;
const unsigned char *tmp_c;
tmp = old_mode; old_mode = new_mode; new_mode = tmp;
tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
}
if (!path) path = "";
sprintf(concatpath, "%s%s", base, path);
if (options->prefix &&
strncmp(concatpath, options->prefix, options->prefix_length))
return;
one = alloc_filespec(concatpath);
two = alloc_filespec(concatpath);
fill_filespec(one, old_sha1, old_mode);
fill_filespec(two, new_sha1, new_mode);
diff_queue(&diff_queued_diff, one, two);
DIFF_OPT_SET(options, HAS_CHANGES);
} | 1 | CVE-2008-3546 | 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,505 |
gpac | ec64c7b8966d7e4642d12debb888be5acf18efb9 | GF_Err infe_box_read(GF_Box *s, GF_BitStream *bs)
{
char *buf;
u32 buf_len, i, string_len, string_start;
GF_ItemInfoEntryBox *ptr = (GF_ItemInfoEntryBox *)s;
ISOM_DECREASE_SIZE(ptr, 4);
ptr->item_ID = gf_bs_read_u16(bs);
ptr->item_protection_index = gf_bs_read_u16(bs);
if (ptr->version == 2) {
ISOM_DECREASE_SIZE(ptr, 4);
ptr->item_type = gf_bs_read_u32(bs);
}
buf_len = (u32) (ptr->size);
buf = (char*)gf_malloc(buf_len);
if (!buf) return GF_OUT_OF_MEM;
if (buf_len != gf_bs_read_data(bs, buf, buf_len)) {
gf_free(buf);
return GF_ISOM_INVALID_FILE;
}
string_len = 1;
string_start = 0;
for (i = 0; i < buf_len; i++) {
if (buf[i] == 0) {
if (!ptr->item_name) {
ptr->item_name = (char*)gf_malloc(sizeof(char)*string_len);
if (!ptr->item_name) return GF_OUT_OF_MEM;
memcpy(ptr->item_name, buf+string_start, string_len);
} else if (!ptr->content_type) {
ptr->content_type = (char*)gf_malloc(sizeof(char)*string_len);
if (!ptr->content_type) return GF_OUT_OF_MEM;
memcpy(ptr->content_type, buf+string_start, string_len);
} else {
ptr->content_encoding = (char*)gf_malloc(sizeof(char)*string_len);
if (!ptr->content_encoding) return GF_OUT_OF_MEM;
memcpy(ptr->content_encoding, buf+string_start, string_len);
}
string_start += string_len;
string_len = 0;
if (ptr->content_encoding && ptr->version == 1) {
break;
}
}
string_len++;
}
gf_free(buf);
if (!ptr->item_name || (!ptr->content_type && ptr->version < 2)) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[isoff] Infe without name or content type !\n"));
}
return GF_OK;
} | 1 | CVE-2021-33363 | CWE-787 | Out-of-bounds Write | The product writes data past the end, or before the beginning, of the intended buffer. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333].
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 1,030 |
raptor | a676f235309a59d4aa78eeffd2574ae5d341fcb0 | raptor_rss_parse_start(raptor_parser *rdf_parser)
{
raptor_uri *uri = rdf_parser->base_uri;
raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context;
int n;
/* base URI required for RSS */
if(!uri)
return 1;
for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++)
rss_parser->nspaces_seen[n] = 'N';
/* Optionally forbid internal network and file requests in the XML parser */
raptor_sax2_set_option(rss_parser->sax2,
RAPTOR_OPTION_NO_NET, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET));
raptor_sax2_set_option(rss_parser->sax2,
RAPTOR_OPTION_NO_FILE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE));
if(rdf_parser->uri_filter)
raptor_sax2_set_uri_filter(rss_parser->sax2, rdf_parser->uri_filter,
rdf_parser->uri_filter_user_data);
raptor_sax2_parse_start(rss_parser->sax2, uri);
return 0;
}
| 1 | CVE-2012-0037 | 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,576 |
php-src | 4cc0286f2f3780abc6084bcdae5dce595daa3c12 | ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC)
{
GC_REFCOUNT(ht) = 1;
GC_TYPE_INFO(ht) = IS_ARRAY;
ht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS;
ht->nTableSize = zend_hash_check_size(nSize);
ht->nTableMask = HT_MIN_MASK;
HT_SET_DATA_ADDR(ht, &uninitialized_bucket);
ht->nNumUsed = 0;
ht->nNumOfElements = 0;
ht->nInternalPointer = HT_INVALID_IDX;
ht->nNextFreeElement = 0;
ht->pDestructor = pDestructor;
}
| 1 | CVE-2017-5340 | 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. | 832 |
Android | 295c883fe3105b19bcd0f9e07d54c6b589fc5bff | OMX_ERRORTYPE SoftOpus::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch ((int)index) {
case OMX_IndexParamAudioAndroidOpus:
{
OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams =
(OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params;
if (opusParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
opusParams->nAudioBandWidth = 0;
opusParams->nSampleRate = kRate;
opusParams->nBitRate = 0;
if (!isConfigured()) {
opusParams->nChannels = 1;
} else {
opusParams->nChannels = mHeader->channels;
}
return OMX_ErrorNone;
}
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->nSamplingRate = kRate;
if (!isConfigured()) {
pcmParams->nChannels = 1;
} else {
pcmParams->nChannels = mHeader->channels;
}
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). | 6,437 |
Chrome | dc7b094a338c6c521f918f478e993f0f74bbea0d | void MaybeRestoreConnections() {
if (IBusConnectionsAreAlive()) {
return;
}
MaybeCreateIBus();
MaybeRestoreIBusConfig();
if (IBusConnectionsAreAlive()) {
ConnectPanelServiceSignals();
if (connection_change_handler_) {
LOG(INFO) << "Notifying Chrome that IBus is ready.";
connection_change_handler_(language_library_, true);
}
}
}
| 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,343 |
poppler | 27354e9d9696ee2bc063910a6c9a6b27c5184a52 | void JBIG2Stream::readTextRegionSeg(unsigned int segNum, bool imm, bool lossless, unsigned int length, unsigned int *refSegs, unsigned int nRefSegs)
{
std::unique_ptr<JBIG2Bitmap> bitmap;
JBIG2HuffmanTable runLengthTab[36];
JBIG2HuffmanTable *symCodeTab = nullptr;
const JBIG2HuffmanTable *huffFSTable, *huffDSTable, *huffDTTable;
const JBIG2HuffmanTable *huffRDWTable, *huffRDHTable;
const JBIG2HuffmanTable *huffRDXTable, *huffRDYTable, *huffRSizeTable;
JBIG2Segment *seg;
std::vector<JBIG2Segment *> codeTables;
JBIG2SymbolDict *symbolDict;
JBIG2Bitmap **syms;
unsigned int w, h, x, y, segInfoFlags, extCombOp;
unsigned int flags, huff, refine, logStrips, refCorner, transposed;
unsigned int combOp, defPixel, templ;
int sOffset;
unsigned int huffFlags, huffFS, huffDS, huffDT;
unsigned int huffRDW, huffRDH, huffRDX, huffRDY, huffRSize;
unsigned int numInstances, numSyms, symCodeLen;
int atx[2], aty[2];
unsigned int i, k, kk;
int j = 0;
// region segment info field
if (!readULong(&w) || !readULong(&h) || !readULong(&x) || !readULong(&y) || !readUByte(&segInfoFlags)) {
goto eofError;
}
extCombOp = segInfoFlags & 7;
// rest of the text region header
if (!readUWord(&flags)) {
goto eofError;
}
huff = flags & 1;
refine = (flags >> 1) & 1;
logStrips = (flags >> 2) & 3;
refCorner = (flags >> 4) & 3;
transposed = (flags >> 6) & 1;
combOp = (flags >> 7) & 3;
defPixel = (flags >> 9) & 1;
sOffset = (flags >> 10) & 0x1f;
if (sOffset & 0x10) {
sOffset |= -1 - 0x0f;
}
templ = (flags >> 15) & 1;
huffFS = huffDS = huffDT = 0; // make gcc happy
huffRDW = huffRDH = huffRDX = huffRDY = huffRSize = 0; // make gcc happy
if (huff) {
if (!readUWord(&huffFlags)) {
goto eofError;
}
huffFS = huffFlags & 3;
huffDS = (huffFlags >> 2) & 3;
huffDT = (huffFlags >> 4) & 3;
huffRDW = (huffFlags >> 6) & 3;
huffRDH = (huffFlags >> 8) & 3;
huffRDX = (huffFlags >> 10) & 3;
huffRDY = (huffFlags >> 12) & 3;
huffRSize = (huffFlags >> 14) & 1;
}
if (refine && templ == 0) {
if (!readByte(&atx[0]) || !readByte(&aty[0]) || !readByte(&atx[1]) || !readByte(&aty[1])) {
goto eofError;
}
}
if (!readULong(&numInstances)) {
goto eofError;
}
// get symbol dictionaries and tables
numSyms = 0;
for (i = 0; i < nRefSegs; ++i) {
if ((seg = findSegment(refSegs[i]))) {
if (seg->getType() == jbig2SegSymbolDict) {
numSyms += ((JBIG2SymbolDict *)seg)->getSize();
} else if (seg->getType() == jbig2SegCodeTable) {
codeTables.push_back(seg);
}
} else {
error(errSyntaxError, curStr->getPos(), "Invalid segment reference in JBIG2 text region");
return;
}
}
i = numSyms;
if (i <= 1) {
symCodeLen = huff ? 1 : 0;
} else {
--i;
symCodeLen = 0;
// i = floor((numSyms-1) / 2^symCodeLen)
while (i > 0) {
++symCodeLen;
i >>= 1;
}
}
// get the symbol bitmaps
syms = (JBIG2Bitmap **)gmallocn_checkoverflow(numSyms, sizeof(JBIG2Bitmap *));
if (numSyms > 0 && !syms) {
return;
}
kk = 0;
for (i = 0; i < nRefSegs; ++i) {
if ((seg = findSegment(refSegs[i]))) {
if (seg->getType() == jbig2SegSymbolDict) {
symbolDict = (JBIG2SymbolDict *)seg;
for (k = 0; k < symbolDict->getSize(); ++k) {
syms[kk++] = symbolDict->getBitmap(k);
}
}
}
}
// get the Huffman tables
huffFSTable = huffDSTable = huffDTTable = nullptr; // make gcc happy
huffRDWTable = huffRDHTable = nullptr; // make gcc happy
huffRDXTable = huffRDYTable = huffRSizeTable = nullptr; // make gcc happy
i = 0;
if (huff) {
if (huffFS == 0) {
huffFSTable = huffTableF;
} else if (huffFS == 1) {
huffFSTable = huffTableG;
} else {
if (i >= codeTables.size()) {
goto codeTableError;
}
huffFSTable = ((JBIG2CodeTable *)codeTables[i++])->getHuffTable();
}
if (huffDS == 0) {
huffDSTable = huffTableH;
} else if (huffDS == 1) {
huffDSTable = huffTableI;
} else if (huffDS == 2) {
huffDSTable = huffTableJ;
} else {
if (i >= codeTables.size()) {
goto codeTableError;
}
huffDSTable = ((JBIG2CodeTable *)codeTables[i++])->getHuffTable();
}
if (huffDT == 0) {
huffDTTable = huffTableK;
} else if (huffDT == 1) {
huffDTTable = huffTableL;
} else if (huffDT == 2) {
huffDTTable = huffTableM;
} else {
if (i >= codeTables.size()) {
goto codeTableError;
}
huffDTTable = ((JBIG2CodeTable *)codeTables[i++])->getHuffTable();
}
if (huffRDW == 0) {
huffRDWTable = huffTableN;
} else if (huffRDW == 1) {
huffRDWTable = huffTableO;
} else {
if (i >= codeTables.size()) {
goto codeTableError;
}
huffRDWTable = ((JBIG2CodeTable *)codeTables[i++])->getHuffTable();
}
if (huffRDH == 0) {
huffRDHTable = huffTableN;
} else if (huffRDH == 1) {
huffRDHTable = huffTableO;
} else {
if (i >= codeTables.size()) {
goto codeTableError;
}
huffRDHTable = ((JBIG2CodeTable *)codeTables[i++])->getHuffTable();
}
if (huffRDX == 0) {
huffRDXTable = huffTableN;
} else if (huffRDX == 1) {
huffRDXTable = huffTableO;
} else {
if (i >= codeTables.size()) {
goto codeTableError;
}
huffRDXTable = ((JBIG2CodeTable *)codeTables[i++])->getHuffTable();
}
if (huffRDY == 0) {
huffRDYTable = huffTableN;
} else if (huffRDY == 1) {
huffRDYTable = huffTableO;
} else {
if (i >= codeTables.size()) {
goto codeTableError;
}
huffRDYTable = ((JBIG2CodeTable *)codeTables[i++])->getHuffTable();
}
if (huffRSize == 0) {
huffRSizeTable = huffTableA;
} else {
if (i >= codeTables.size()) {
goto codeTableError;
}
huffRSizeTable = ((JBIG2CodeTable *)codeTables[i++])->getHuffTable();
}
}
// symbol ID Huffman decoding table
if (huff) {
huffDecoder->reset();
for (i = 0; i < 32; ++i) {
runLengthTab[i].val = i;
runLengthTab[i].prefixLen = huffDecoder->readBits(4);
runLengthTab[i].rangeLen = 0;
}
runLengthTab[32].val = 0x103;
runLengthTab[32].prefixLen = huffDecoder->readBits(4);
runLengthTab[32].rangeLen = 2;
runLengthTab[33].val = 0x203;
runLengthTab[33].prefixLen = huffDecoder->readBits(4);
runLengthTab[33].rangeLen = 3;
runLengthTab[34].val = 0x20b;
runLengthTab[34].prefixLen = huffDecoder->readBits(4);
runLengthTab[34].rangeLen = 7;
runLengthTab[35].prefixLen = 0;
runLengthTab[35].rangeLen = jbig2HuffmanEOT;
if (!JBIG2HuffmanDecoder::buildTable(runLengthTab, 35)) {
huff = false;
}
}
if (huff) {
symCodeTab = (JBIG2HuffmanTable *)gmallocn_checkoverflow(numSyms + 1, sizeof(JBIG2HuffmanTable));
if (!symCodeTab) {
gfree(syms);
return;
}
for (i = 0; i < numSyms; ++i) {
symCodeTab[i].val = i;
symCodeTab[i].rangeLen = 0;
}
i = 0;
while (i < numSyms) {
huffDecoder->decodeInt(&j, runLengthTab);
if (j > 0x200) {
for (j -= 0x200; j && i < numSyms; --j) {
symCodeTab[i++].prefixLen = 0;
}
} else if (j > 0x100) {
if (unlikely(i == 0)) {
symCodeTab[i].prefixLen = 0;
++i;
}
for (j -= 0x100; j && i < numSyms; --j) {
symCodeTab[i].prefixLen = symCodeTab[i - 1].prefixLen;
++i;
}
} else {
symCodeTab[i++].prefixLen = j;
}
}
symCodeTab[numSyms].prefixLen = 0;
symCodeTab[numSyms].rangeLen = jbig2HuffmanEOT;
if (!JBIG2HuffmanDecoder::buildTable(symCodeTab, numSyms)) {
huff = false;
gfree(symCodeTab);
symCodeTab = nullptr;
}
huffDecoder->reset();
// set up the arithmetic decoder
}
if (!huff) {
if (!resetIntStats(symCodeLen)) {
gfree(syms);
return;
}
arithDecoder->start();
}
if (refine) {
resetRefinementStats(templ, nullptr);
}
bitmap = readTextRegion(huff, refine, w, h, numInstances, logStrips, numSyms, symCodeTab, symCodeLen, syms, defPixel, combOp, transposed, refCorner, sOffset, huffFSTable, huffDSTable, huffDTTable, huffRDWTable, huffRDHTable,
huffRDXTable, huffRDYTable, huffRSizeTable, templ, atx, aty);
gfree(syms);
if (bitmap) {
// combine the region bitmap into the page bitmap
if (imm) {
if (pageH == 0xffffffff && y + h > curPageH) {
pageBitmap->expand(y + h, pageDefPixel);
}
if (pageBitmap->isOk()) {
pageBitmap->combine(bitmap.get(), x, y, extCombOp);
}
// store the region bitmap
} else {
bitmap->setSegNum(segNum);
segments.push_back(std::move(bitmap));
}
}
// clean up the Huffman decoder
if (huff) {
gfree(symCodeTab);
}
return;
codeTableError:
error(errSyntaxError, curStr->getPos(), "Missing code table in JBIG2 text region");
gfree(syms);
return;
eofError:
error(errSyntaxError, curStr->getPos(), "Unexpected EOF in JBIG2 stream");
return;
} | 1 | CVE-2022-38784 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 9,826 |
wpitchoune | 8b10426dcc0246c1712a99460dd470dcb1cc4d9c | static struct MHD_Response *create_response_file(const char *nurl,
const char *method,
unsigned int *rp_code,
const char *fpath)
{
struct stat st;
int ret;
FILE *file;
ret = stat(fpath, &st);
if (!ret && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))) {
file = fopen(fpath, "rb");
if (file) {
*rp_code = MHD_HTTP_OK;
if (!st.st_size) {
fclose(file);
return MHD_create_response_from_data
(0, NULL, MHD_NO, MHD_NO);
}
return MHD_create_response_from_callback
(st.st_size,
32 * 1024,
&file_reader,
file,
(MHD_ContentReaderFreeCallback)&fclose);
} else {
log_err("Failed to open: %s.", fpath);
}
}
return NULL;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,365 |
postgres | 4318daecc959886d001a6e79c6ea853e8b1dfb4b | PGTYPESdate_mdyjul(int *mdy, date * jdate)
{
/* month is mdy[0] */
/* day is mdy[1] */
/* year is mdy[2] */
*jdate = (date) (date2j(mdy[2], mdy[0], mdy[1]) - date2j(2000, 1, 1));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,936 |
ImageMagick6 | 072d7b10dbe74d1cf4ec0d008990c1a28c076f9e | static PixelList **AcquirePixelListThreadSet(const size_t width,
const size_t height)
{
PixelList
**pixel_list;
ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixel_list=(PixelList **) AcquireQuantumMemory(number_threads,
sizeof(*pixel_list));
if (pixel_list == (PixelList **) NULL)
return((PixelList **) NULL);
(void) memset(pixel_list,0,number_threads*sizeof(*pixel_list));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixel_list[i]=AcquirePixelList(width,height);
if (pixel_list[i] == (PixelList *) NULL)
return(DestroyPixelListThreadSet(pixel_list));
}
return(pixel_list);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,044 |
linux | 8176cced706b5e5d15887584150764894e94e02f | static void perf_free_event(struct perf_event *event,
struct perf_event_context *ctx)
{
struct perf_event *parent = event->parent;
if (WARN_ON_ONCE(!parent))
return;
mutex_lock(&parent->child_mutex);
list_del_init(&event->child_list);
mutex_unlock(&parent->child_mutex);
put_event(parent);
perf_group_detach(event);
list_del_event(event, ctx);
free_event(event);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,574 |
sqlite | 660ee55663fb8aa26a7ebd764ec5c94440bcd62f | void sqlite3SelectAddColumnTypeAndCollation(
Parse *pParse, /* Parsing contexts */
Table *pTab, /* Add column type information to this table */
Select *pSelect /* SELECT used to determine types and collations */
){
sqlite3 *db = pParse->db;
NameContext sNC;
Column *pCol;
CollSeq *pColl;
int i;
Expr *p;
struct ExprList_item *a;
assert( pSelect!=0 );
assert( (pSelect->selFlags & SF_Resolved)!=0 );
assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
if( db->mallocFailed ) return;
memset(&sNC, 0, sizeof(sNC));
sNC.pSrcList = pSelect->pSrc;
a = pSelect->pEList->a;
for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
const char *zType;
int n, m;
p = a[i].pExpr;
zType = columnType(&sNC, p, 0, 0, 0);
/* pCol->szEst = ... // Column size est for SELECT tables never used */
pCol->affinity = sqlite3ExprAffinity(p);
if( zType ){
m = sqlite3Strlen30(zType);
n = sqlite3Strlen30(pCol->zName);
pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
if( pCol->zName ){
memcpy(&pCol->zName[n+1], zType, m+1);
pCol->colFlags |= COLFLAG_HASTYPE;
}
}
if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
pColl = sqlite3ExprCollSeq(pParse, p);
if( pColl && pCol->zColl==0 ){
pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
}
}
pTab->szTabRow = 1; /* Any non-zero value works */
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,005 |
FFmpeg | f1caaa1c61310beba705957e6366f0392a0b005b | static int dnxhd_calc_bits_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)
{
DNXHDEncContext *ctx = avctx->priv_data;
int mb_y = jobnr, mb_x;
int qscale = ctx->qscale;
LOCAL_ALIGNED_16(int16_t, block, [64]);
ctx = ctx->thread[threadnr];
ctx->m.last_dc[0] =
ctx->m.last_dc[1] =
ctx->m.last_dc[2] = 1 << (ctx->cid_table->bit_depth + 2);
for (mb_x = 0; mb_x < ctx->m.mb_width; mb_x++) {
unsigned mb = mb_y * ctx->m.mb_width + mb_x;
int ssd = 0;
int ac_bits = 0;
int dc_bits = 0;
int i;
dnxhd_get_blocks(ctx, mb_x, mb_y);
for (i = 0; i < 8; i++) {
int16_t *src_block = ctx->blocks[i];
int overflow, nbits, diff, last_index;
int n = dnxhd_switch_matrix(ctx, i);
memcpy(block, src_block, 64*sizeof(*block));
last_index = ctx->m.dct_quantize(&ctx->m, block, 4&(2*i), qscale, &overflow);
ac_bits += dnxhd_calc_ac_bits(ctx, block, last_index);
diff = block[0] - ctx->m.last_dc[n];
if (diff < 0) nbits = av_log2_16bit(-2*diff);
else nbits = av_log2_16bit( 2*diff);
av_assert1(nbits < ctx->cid_table->bit_depth + 4);
dc_bits += ctx->cid_table->dc_bits[nbits] + nbits;
ctx->m.last_dc[n] = block[0];
if (avctx->mb_decision == FF_MB_DECISION_RD || !RC_VARIANCE) {
dnxhd_unquantize_c(ctx, block, i, qscale, last_index);
ctx->m.dsp.idct(block);
ssd += dnxhd_ssd_block(block, src_block);
}
}
ctx->mb_rc[qscale][mb].ssd = ssd;
ctx->mb_rc[qscale][mb].bits = ac_bits+dc_bits+12+8*ctx->vlc_bits[0];
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,383 |
linux | 7caac62ed598a196d6ddf8d9c121e12e082cac3a | mwifiex_uap_bss_wep(u8 **tlv_buf, void *cmd_buf, u16 *param_size)
{
struct host_cmd_tlv_wep_key *wep_key;
u16 cmd_size = *param_size;
int i;
u8 *tlv = *tlv_buf;
struct mwifiex_uap_bss_param *bss_cfg = cmd_buf;
for (i = 0; i < NUM_WEP_KEYS; i++) {
if (bss_cfg->wep_cfg[i].length &&
(bss_cfg->wep_cfg[i].length == WLAN_KEY_LEN_WEP40 ||
bss_cfg->wep_cfg[i].length == WLAN_KEY_LEN_WEP104)) {
wep_key = (struct host_cmd_tlv_wep_key *)tlv;
wep_key->header.type =
cpu_to_le16(TLV_TYPE_UAP_WEP_KEY);
wep_key->header.len =
cpu_to_le16(bss_cfg->wep_cfg[i].length + 2);
wep_key->key_index = bss_cfg->wep_cfg[i].key_index;
wep_key->is_default = bss_cfg->wep_cfg[i].is_default;
memcpy(wep_key->key, bss_cfg->wep_cfg[i].key,
bss_cfg->wep_cfg[i].length);
cmd_size += sizeof(struct mwifiex_ie_types_header) + 2 +
bss_cfg->wep_cfg[i].length;
tlv += sizeof(struct mwifiex_ie_types_header) + 2 +
bss_cfg->wep_cfg[i].length;
}
}
*param_size = cmd_size;
*tlv_buf = tlv;
return;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,731 |
Chrome | 8cfe2463cec6835c7b0b73dcb2ab2edaf035e3f9 | AppControllerImpl::AppControllerImpl(Profile* profile)
//// static
: profile_(profile),
app_service_proxy_(apps::AppServiceProxy::Get(profile)),
url_prefix_(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
chromeos::switches::kKioskNextHomeUrlPrefix)) {
app_service_proxy_->AppRegistryCache().AddObserver(this);
if (profile) {
content::URLDataSource::Add(profile,
std::make_unique<apps::AppIconSource>(profile));
}
}
| 1 | CVE-2016-5183 | 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,614 |
Chrome | 032c3339bfb454c65ce38e7eafe49a54bac83073 | void SVGElement::RemoveInstanceMapping(SVGElement* instance) {
DCHECK(instance);
DCHECK(instance->InUseShadowTree());
if (!HasSVGRareData())
return;
HeapHashSet<WeakMember<SVGElement>>& instances =
SvgRareData()->ElementInstances();
instances.erase(instance);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,092 |
Chrome | 33827275411b33371e7bb750cce20f11de85002d | void FrameSelection::MoveRangeSelectionExtent(const IntPoint& contents_point) {
if (ComputeVisibleSelectionInDOMTree().IsNone())
return;
SetSelection(
SelectionInDOMTree::Builder(
GetGranularityStrategy()->UpdateExtent(contents_point, frame_))
.SetIsHandleVisible(true)
.Build(),
SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetDoNotClearStrategy(true)
.SetSetSelectionBy(SetSelectionBy::kUser)
.Build());
}
| 1 | CVE-2015-6773 | 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,340 |
Subsets and Splits