project
stringclasses
765 values
commit_id
stringlengths
6
81
func
stringlengths
19
482k
vul
int64
0
1
CVE ID
stringlengths
13
16
CWE ID
stringclasses
13 values
CWE Name
stringclasses
13 values
CWE Description
stringclasses
13 values
Potential Mitigation
stringclasses
11 values
__index_level_0__
int64
0
23.9k
ImageMagick
8598a497e2d1f556a34458cf54b40ba40674734c
static MagickBooleanType IsPostscriptRendered(const char *path) { MagickBooleanType status; struct stat attributes; if ((path == (const char *) NULL) || (*path == '\0')) return(MagickFalse); status=GetPathAttributes(path,&attributes); if ((status != MagickFalse) && S_ISREG(attributes.st_mode) && (attributes.st_size > 0)) return(MagickTrue); return(MagickFalse); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,834
linux
999653786df6954a31044528ac3f7a5dadca08f4
mask_from_posix(unsigned short perm, unsigned int flags) { int mask = NFS4_ANYONE_MODE; if (flags & NFS4_ACL_OWNER) mask |= NFS4_OWNER_MODE; if (perm & ACL_READ) mask |= NFS4_READ_MODE; if (perm & ACL_WRITE) mask |= NFS4_WRITE_MODE; if ((perm & ACL_WRITE) && (flags & NFS4_ACL_DIR)) mask |= NFS4_ACE_DELETE_CHILD; if (perm & ACL_EXECUTE) mask |= NFS4_EXECUTE_MODE; return mask; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,144
php-src
c4cca4c20e75359c9a13a1f9a36cb7b4e9601d29
*/ static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1])); break; } } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i+1]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) { zval *tmp; char *key; char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(",")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,547
aubio
b1559f4c9ce2b304d8d27ffdc7128b6795ca82e5
uint_t aubio_tempo_set_tatum_signature (aubio_tempo_t *o, uint_t signature) { if (signature < 1 || signature > 64) { return AUBIO_FAIL; } else { o->tatum_signature = signature; return AUBIO_OK; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,508
Chrome
3c8e4852477d5b1e2da877808c998dc57db9460f
Response StorageHandler::UntrackIndexedDBForOrigin(const std::string& origin) { if (!process_) return Response::InternalError(); GURL origin_url(origin); if (!origin_url.is_valid()) return Response::InvalidParams(origin + " is not a valid URL"); GetIndexedDBObserver()->TaskRunner()->PostTask( FROM_HERE, base::BindOnce(&IndexedDBObserver::UntrackOriginOnIDBThread, base::Unretained(GetIndexedDBObserver()), url::Origin::Create(origin_url))); return Response::OK(); }
1
CVE-2018-6111
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
1,013
libming
2be22fcf56a223dafe8de0e8a20fe20e8bbdb0b9
decompileArithmeticOp(int n, SWF_ACTION *actions, int maxn) { struct SWF_ACTIONPUSHPARAM *left, *right; int op_l = OpCode(actions, n, maxn); int op_r = OpCode(actions, n+1, maxn); right=pop(); left=pop(); switch(OpCode(actions, n, maxn)) { /* case SWFACTION_GETMEMBER: decompilePUSHPARAM(peek(),0); break; */ case SWFACTION_INSTANCEOF: if (precedence(op_l, op_r)) push(newVar3(getString(left)," instanceof ",getString(right))); else push(newVar_N("(",getString(left)," instanceof ",getString(right),0,")")); break; case SWFACTION_ADD: case SWFACTION_ADD2: if (precedence(op_l, op_r)) push(newVar3(getString(left),"+",getString(right))); else push(newVar_N("(",getString(left),"+",getString(right),0,")")); break; case SWFACTION_SUBTRACT: if (precedence(op_l, op_r)) push(newVar3(getString(left),"-",getString(right))); else push(newVar_N("(",getString(left),"-",getString(right),0,")")); break; case SWFACTION_MULTIPLY: if (precedence(op_l, op_r)) push(newVar3(getString(left),"*",getString(right))); else push(newVar_N("(",getString(left),"*",getString(right),0,")")); break; case SWFACTION_DIVIDE: if (precedence(op_l, op_r)) push(newVar3(getString(left),"/",getString(right))); else push(newVar_N("(",getString(left),"/",getString(right),0,")")); break; case SWFACTION_MODULO: if (precedence(op_l, op_r)) push(newVar3(getString(left),"%",getString(right))); else push(newVar_N("(",getString(left),"%",getString(right),0,")")); break; case SWFACTION_SHIFTLEFT: if (precedence(op_l, op_r)) push(newVar3(getString(left),"<<",getString(right))); else push(newVar_N("(",getString(left),"<<",getString(right),0,")")); break; case SWFACTION_SHIFTRIGHT: if (precedence(op_l, op_r)) push(newVar3(getString(left),">>",getString(right))); else push(newVar_N("(",getString(left),">>",getString(right),0,")")); break; case SWFACTION_SHIFTRIGHT2: if (precedence(op_l, op_r)) push(newVar3(getString(left),">>>",getString(right))); else push(newVar_N("(",getString(left),">>>",getString(right),0,")")); break; case SWFACTION_LOGICALAND: if (precedence(op_l, op_r)) push(newVar3(getString(left),"&&",getString(right))); else push(newVar_N("(",getString(left),"&&",getString(right),0,")")); break; case SWFACTION_LOGICALOR: if (precedence(op_l, op_r)) push(newVar3(getString(left),"||",getString(right))); else push(newVar_N("(",getString(left),"||",getString(right),0,")")); break; case SWFACTION_BITWISEAND: if (precedence(op_l, op_r)) push(newVar3(getString(left),"&",getString(right))); else push(newVar_N("(",getString(left),"&",getString(right),0,")")); break; case SWFACTION_BITWISEOR: if (precedence(op_l, op_r)) push(newVar3(getString(left),"|",getString(right))); else push(newVar_N("(",getString(left),"|",getString(right),0,")")); break; case SWFACTION_BITWISEXOR: if (precedence(op_l, op_r)) push(newVar3(getString(left),"^",getString(right))); else push(newVar_N("(",getString(left),"^",getString(right),0,")")); break; case SWFACTION_EQUALS2: /* including negation */ case SWFACTION_EQUAL: if( OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT && OpCode(actions, n+2, maxn) != SWFACTION_IF) { op_r = OpCode(actions, n+1, maxn); if (precedence(op_l, op_r)) push(newVar3(getString(left),"!=",getString(right))); else push(newVar_N("(",getString(left),"!=",getString(right),0,")")); return 1; /* due negation op */ } if (precedence(op_l, op_r)) push(newVar3(getString(left),"==",getString(right))); else push(newVar_N("(",getString(left),"==",getString(right),0,")")); break; case SWFACTION_LESS2: if( OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT && OpCode(actions, n+2, maxn) != SWFACTION_IF ) { op_r = OpCode(actions, n+2, maxn); if (precedence(op_l, op_r)) push(newVar3(getString(left),">=",getString(right))); else push(newVar_N("(",getString(left),">=",getString(right),0,")")); return 1; /* due negation op */ } if (precedence(op_l, op_r)) push(newVar3(getString(left),"<",getString(right))); else push(newVar_N("(",getString(left),"<",getString(right),0,")")); break; case SWFACTION_GREATER: if (precedence(op_l, op_r)) push(newVar3(getString(left),">",getString(right))); else push(newVar_N("(",getString(left),">",getString(right),0,")")); break; case SWFACTION_LESSTHAN: if (precedence(op_l, op_r)) push(newVar3(getString(left),"<",getString(right))); else push(newVar_N("(",getString(left),"<",getString(right),0,")")); break; case SWFACTION_STRINGEQ: if (precedence(op_l, op_r)) push(newVar3(getString(left),"==",getString(right))); else push(newVar_N("(",getString(left),"==",getString(right),0,")")); break; case SWFACTION_STRINGCOMPARE: puts("STRINGCOMPARE"); break; case SWFACTION_STRICTEQUALS: #ifdef DECOMP_SWITCH if (OpCode(actions, n, maxn) == SWFACTION_IF) { int code = actions[n+1].SWF_ACTIONIF.Actions[0].SWF_ACTIONRECORD.ActionCode; if(check_switch(code)) { push(right); // keep left and right side separated push(left); // because it seems we have found a switch(){} and break; // let decompileIF() once more do all the dirty work } } #endif if( OpCode(actions, n+1, maxn) == SWFACTION_LOGICALNOT && OpCode(actions, n+2, maxn) != SWFACTION_IF ) { op_r = OpCode(actions, n+2, maxn); if (precedence(op_l, op_r)) push(newVar3(getString(left),"!==",getString(right))); else push(newVar_N("(",getString(left),"!==",getString(right),0,")")); return 1; /* due negation op */ } else { if (precedence(op_l, op_r)) push(newVar3(getString(left),"===",getString(right))); else push(newVar_N("(",getString(left),"===",getString(right),0,")")); break; } default: printf("Unhandled Arithmetic/Logic OP %x\n", OpCode(actions, n, maxn)); } return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,377
oniguruma
3661ae526bc1cfe1b93ec31fc03c0fe72e1fe6c1
onig_print_compiled_byte_code(FILE* f, Operation* p, Operation* start, OnigEncoding enc) { int i, n; RelAddrType addr; LengthType len; MemNumType mem; OnigCodePoint code; ModeType mode; UChar *q; fprintf(f, "%s", op2name(p->opcode)); switch (p->opcode) { case OP_EXACT1: p_string(f, 1, p->exact.s); break; case OP_EXACT2: p_string(f, 2, p->exact.s); break; case OP_EXACT3: p_string(f, 3, p->exact.s); break; case OP_EXACT4: p_string(f, 4, p->exact.s); break; case OP_EXACT5: p_string(f, 5, p->exact.s); break; case OP_EXACTN: len = p->exact_n.n; p_string(f, len, p->exact_n.s); break; case OP_EXACTMB2N1: p_string(f, 2, p->exact.s); break; case OP_EXACTMB2N2: p_string(f, 4, p->exact.s); break; case OP_EXACTMB2N3: p_string(f, 3, p->exact.s); break; case OP_EXACTMB2N: len = p->exact_n.n; p_len_string(f, len, 2, p->exact_n.s); break; case OP_EXACTMB3N: len = p->exact_n.n; p_len_string(f, len, 3, p->exact_n.s); break; case OP_EXACTMBN: { int mb_len; mb_len = p->exact_len_n.len; len = p->exact_len_n.n; q = p->exact_len_n.s; fprintf(f, ":%d:%d:", mb_len, len); n = len * mb_len; while (n-- > 0) { fputc(*q++, f); } } break; case OP_EXACT1_IC: len = enclen(enc, p->exact.s); p_string(f, len, p->exact.s); break; case OP_EXACTN_IC: len = p->exact_n.n; p_len_string(f, len, 1, p->exact_n.s); break; case OP_CCLASS: case OP_CCLASS_NOT: n = bitset_on_num(p->cclass.bs); fprintf(f, ":%d", n); break; case OP_CCLASS_MB: case OP_CCLASS_MB_NOT: { OnigCodePoint ncode; OnigCodePoint* codes; codes = (OnigCodePoint* )p->cclass_mb.mb; GET_CODE_POINT(ncode, codes); codes++; GET_CODE_POINT(code, codes); fprintf(f, ":%u:%u", code, ncode); } break; case OP_CCLASS_MIX: case OP_CCLASS_MIX_NOT: { OnigCodePoint ncode; OnigCodePoint* codes; codes = (OnigCodePoint* )p->cclass_mix.mb; n = bitset_on_num(p->cclass_mix.bs); GET_CODE_POINT(ncode, codes); codes++; GET_CODE_POINT(code, codes); fprintf(f, ":%d:%u:%u", n, code, ncode); } break; case OP_ANYCHAR_STAR_PEEK_NEXT: case OP_ANYCHAR_ML_STAR_PEEK_NEXT: p_string(f, 1, &(p->anychar_star_peek_next.c)); break; case OP_WORD_BOUNDARY: case OP_NO_WORD_BOUNDARY: case OP_WORD_BEGIN: case OP_WORD_END: mode = p->word_boundary.mode; fprintf(f, ":%d", mode); break; case OP_BACKREF_N: case OP_BACKREF_N_IC: mem = p->backref_n.n1; fprintf(f, ":%d", mem); break; case OP_BACKREF_MULTI_IC: case OP_BACKREF_MULTI: case OP_BACKREF_CHECK: fputs(" ", f); n = p->backref_general.num; for (i = 0; i < n; i++) { mem = (n == 1) ? p->backref_general.n1 : p->backref_general.ns[i]; if (i > 0) fputs(", ", f); fprintf(f, "%d", mem); } break; case OP_BACKREF_WITH_LEVEL: case OP_BACKREF_WITH_LEVEL_IC: case OP_BACKREF_CHECK_WITH_LEVEL: { LengthType level; level = p->backref_general.nest_level; fprintf(f, ":%d", level); fputs(" ", f); n = p->backref_general.num; for (i = 0; i < n; i++) { mem = (n == 1) ? p->backref_general.n1 : p->backref_general.ns[i]; if (i > 0) fputs(", ", f); fprintf(f, "%d", mem); } } break; case OP_MEMORY_START: case OP_MEMORY_START_PUSH: mem = p->memory_start.num; fprintf(f, ":%d", mem); break; case OP_MEMORY_END_PUSH: case OP_MEMORY_END_PUSH_REC: case OP_MEMORY_END: case OP_MEMORY_END_REC: mem = p->memory_end.num; fprintf(f, ":%d", mem); break; case OP_JUMP: addr = p->jump.addr; fputc(':', f); p_rel_addr(f, addr, p, start); break; case OP_PUSH: case OP_PUSH_SUPER: addr = p->push.addr; fputc(':', f); p_rel_addr(f, addr, p, start); break; #ifdef USE_OP_PUSH_OR_JUMP_EXACT case OP_PUSH_OR_JUMP_EXACT1: addr = p->push_or_jump_exact1.addr; fputc(':', f); p_rel_addr(f, addr, p, start); p_string(f, 1, &(p->push_or_jump_exact1.c)); break; #endif case OP_PUSH_IF_PEEK_NEXT: addr = p->push_if_peek_next.addr; fputc(':', f); p_rel_addr(f, addr, p, start); p_string(f, 1, &(p->push_if_peek_next.c)); break; case OP_REPEAT: case OP_REPEAT_NG: mem = p->repeat.id; addr = p->repeat.addr; fprintf(f, ":%d:", mem); p_rel_addr(f, addr, p, start); break; case OP_REPEAT_INC: case OP_REPEAT_INC_NG: case OP_REPEAT_INC_SG: case OP_REPEAT_INC_NG_SG: mem = p->repeat.id; fprintf(f, ":%d", mem); break; case OP_EMPTY_CHECK_START: mem = p->empty_check_start.mem; fprintf(f, ":%d", mem); break; case OP_EMPTY_CHECK_END: case OP_EMPTY_CHECK_END_MEMST: case OP_EMPTY_CHECK_END_MEMST_PUSH: mem = p->empty_check_end.mem; fprintf(f, ":%d", mem); break; case OP_PREC_READ_NOT_START: addr = p->prec_read_not_start.addr; fputc(':', f); p_rel_addr(f, addr, p, start); break; case OP_LOOK_BEHIND: len = p->look_behind.len; fprintf(f, ":%d", len); break; case OP_LOOK_BEHIND_NOT_START: addr = p->look_behind_not_start.addr; len = p->look_behind_not_start.len; fprintf(f, ":%d:", len); p_rel_addr(f, addr, p, start); break; case OP_CALL: addr = p->call.addr; fprintf(f, ":{/%d}", addr); break; case OP_PUSH_SAVE_VAL: { SaveType type; type = p->push_save_val.type; mem = p->push_save_val.id; fprintf(f, ":%d:%d", type, mem); } break; case OP_UPDATE_VAR: { UpdateVarType type; type = p->update_var.type; mem = p->update_var.id; fprintf(f, ":%d:%d", type, mem); } break; #ifdef USE_CALLOUT case OP_CALLOUT_CONTENTS: mem = p->callout_contents.num; fprintf(f, ":%d", mem); break; case OP_CALLOUT_NAME: { int id; id = p->callout_name.id; mem = p->callout_name.num; fprintf(f, ":%d:%d", id, mem); } break; #endif case OP_FINISH: case OP_END: case OP_ANYCHAR: case OP_ANYCHAR_ML: case OP_ANYCHAR_STAR: case OP_ANYCHAR_ML_STAR: case OP_WORD: case OP_WORD_ASCII: case OP_NO_WORD: case OP_NO_WORD_ASCII: case OP_EXTENDED_GRAPHEME_CLUSTER_BOUNDARY: case OP_NO_EXTENDED_GRAPHEME_CLUSTER_BOUNDARY: case OP_BEGIN_BUF: case OP_END_BUF: case OP_BEGIN_LINE: case OP_END_LINE: case OP_SEMI_END_BUF: case OP_BEGIN_POSITION: case OP_BACKREF1: case OP_BACKREF2: case OP_FAIL: case OP_POP_OUT: case OP_PREC_READ_START: case OP_PREC_READ_END: case OP_PREC_READ_NOT_END: case OP_ATOMIC_START: case OP_ATOMIC_END: case OP_LOOK_BEHIND_NOT_END: case OP_RETURN: break; default: fprintf(stderr, "onig_print_compiled_byte_code: undefined code %d\n", p->opcode); break; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,327
linux-stable
8ba8682107ee2ca3347354e018865d8e1967c5f4
SYSCALL_DEFINE3(ioprio_set, int, which, int, who, int, ioprio) { int class = IOPRIO_PRIO_CLASS(ioprio); int data = IOPRIO_PRIO_DATA(ioprio); struct task_struct *p, *g; struct user_struct *user; struct pid *pgrp; kuid_t uid; int ret; switch (class) { case IOPRIO_CLASS_RT: if (!capable(CAP_SYS_ADMIN)) return -EPERM; /* fall through, rt has prio field too */ case IOPRIO_CLASS_BE: if (data >= IOPRIO_BE_NR || data < 0) return -EINVAL; break; case IOPRIO_CLASS_IDLE: break; case IOPRIO_CLASS_NONE: if (data) return -EINVAL; break; default: return -EINVAL; } ret = -ESRCH; rcu_read_lock(); switch (which) { case IOPRIO_WHO_PROCESS: if (!who) p = current; else p = find_task_by_vpid(who); if (p) ret = set_task_ioprio(p, ioprio); break; case IOPRIO_WHO_PGRP: if (!who) pgrp = task_pgrp(current); else pgrp = find_vpid(who); do_each_pid_thread(pgrp, PIDTYPE_PGID, p) { ret = set_task_ioprio(p, ioprio); if (ret) break; } while_each_pid_thread(pgrp, PIDTYPE_PGID, p); break; case IOPRIO_WHO_USER: uid = make_kuid(current_user_ns(), who); if (!uid_valid(uid)) break; if (!who) user = current_user(); else user = find_user(uid); if (!user) break; do_each_thread(g, p) { if (!uid_eq(task_uid(p), uid) || !task_pid_vnr(p)) continue; ret = set_task_ioprio(p, ioprio); if (ret) goto free_uid; } while_each_thread(g, p); free_uid: if (who) free_uid(user); break; default: ret = -EINVAL; } rcu_read_unlock(); return ret; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,049
wireshark
2c13e97d656c1c0ac4d76eb9d307664aae0e0cf7
dissect_rpcap_error (tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, gint offset) { proto_item *ti; gint len; len = tvb_captured_length_remaining (tvb, offset); if (len <= 0) return; col_append_fstr (pinfo->cinfo, COL_INFO, ": %s", tvb_format_text_wsp (tvb, offset, len)); ti = proto_tree_add_item (parent_tree, hf_error, tvb, offset, len, ENC_ASCII|ENC_NA); expert_add_info_format(pinfo, ti, &ei_error, "Error: %s", tvb_format_text_wsp (tvb, offset, len)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,286
qemu
a9c380db3b8c6af19546a68145c8d1438a09c92b
static void ssi_sd_class_init(ObjectClass *klass, void *data) { SSISlaveClass *k = SSI_SLAVE_CLASS(klass); k->init = ssi_sd_init; k->transfer = ssi_sd_transfer; k->cs_polarity = SSI_CS_LOW; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,286
tk
ebd0fc80d62eeb7b8556522256f8d035e013eb65
setup_rubytkkit(void) { init_static_tcltk_packages(); { ID const_id; const_id = rb_intern(RUBYTK_KITPATH_CONST_NAME); if (rb_const_defined(rb_cObject, const_id)) { volatile VALUE pathobj; pathobj = rb_const_get(rb_cObject, const_id); if (rb_obj_is_kind_of(pathobj, rb_cString)) { #ifdef HAVE_RUBY_ENCODING_H pathobj = rb_str_export_to_enc(pathobj, rb_utf8_encoding()); #endif set_rubytk_kitpath(RSTRING_PTR(pathobj)); } } } #ifdef CREATE_RUBYTK_KIT if (rubytk_kitpath == NULL) { #ifdef __WIN32__ /* rbtk_win32_SetHINSTANCE("tcltklib.so"); */ { volatile VALUE basename; basename = rb_funcall(rb_cFile, rb_intern("basename"), 1, rb_str_new2(rb_sourcefile())); rbtk_win32_SetHINSTANCE(RSTRING_PTR(basename)); } #endif set_rubytk_kitpath(rb_sourcefile()); } #endif if (rubytk_kitpath == NULL) { set_rubytk_kitpath(Tcl_GetNameOfExecutable()); } TclSetPreInitScript(rubytkkit_preInitCmd); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,774
libtpms
ea62fd9679f8c6fc5e79471b33cfbd8227bfed72
ObjectGetProperties( TPM_HANDLE handle ) { return HandleToObject(handle)->attributes; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,512
postgres
29725b3db67ad3f09da1a7fb6690737d2f8d6c0a
leading_pad(int zpad, int *signvalue, int *padlen, PrintfTarget *target) { if (*padlen > 0 && zpad) { if (*signvalue) { dopr_outch(*signvalue, target); --(*padlen); *signvalue = 0; } while (*padlen > 0) { dopr_outch(zpad, target); --(*padlen); } } while (*padlen > (*signvalue != 0)) { dopr_outch(' ', target); --(*padlen); } if (*signvalue) { dopr_outch(*signvalue, target); if (*padlen > 0) --(*padlen); else if (*padlen < 0) ++(*padlen); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,821
php-src
6a7cc8ff85827fa9ac715b3a83c2d9147f33cd43?w=1
static inline int object_common2(UNSERIALIZE_PARAMETER, long elements) { zval *retval_ptr = NULL; zval fname; if (Z_TYPE_PP(rval) != IS_OBJECT) { return 0; } if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_OBJPROP_PP(rval), elements, 1)) { /* We've got partially constructed object on our hands here. Wipe it. */ if(Z_TYPE_PP(rval) == IS_OBJECT) { zend_hash_clean(Z_OBJPROP_PP(rval)); } ZVAL_NULL(*rval); return 0; } if (Z_TYPE_PP(rval) != IS_OBJECT) { return 0; } if (Z_OBJCE_PP(rval) != PHP_IC_ENTRY && zend_hash_exists(&Z_OBJCE_PP(rval)->function_table, "__wakeup", sizeof("__wakeup"))) { INIT_PZVAL(&fname); ZVAL_STRINGL(&fname, "__wakeup", sizeof("__wakeup") - 1, 0); BG(serialize_lock)++; call_user_function_ex(CG(function_table), rval, &fname, &retval_ptr, 0, 0, 1, NULL TSRMLS_CC); BG(serialize_lock)--; } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (EG(exception)) { return 0; } return finish_nested_data(UNSERIALIZE_PASSTHRU); }
1
CVE-2016-7411
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,000
libidn
5e3cb9c7b5bf0ce665b9d68f5ddf095af5c9ba60
main (int argc, char *argv[]) { struct gengetopt_args_info args_info; char *line = NULL; size_t linelen = 0; char *p, *r; uint32_t *q; unsigned cmdn = 0; int rc; setlocale (LC_ALL, ""); set_program_name (argv[0]); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (cmdline_parser (argc, argv, &args_info) != 0) return EXIT_FAILURE; if (args_info.version_given) { version_etc (stdout, "idn", PACKAGE_NAME, VERSION, "Simon Josefsson", (char *) NULL); return EXIT_SUCCESS; } if (args_info.help_given) usage (EXIT_SUCCESS); /* Backwards compatibility: -n has always been the documented short form for --nfkc but, before v1.10, -k was the implemented short form. We now accept both to avoid documentation changes. */ if (args_info.hidden_nfkc_given) args_info.nfkc_given = 1; if (!args_info.stringprep_given && !args_info.punycode_encode_given && !args_info.punycode_decode_given && !args_info.idna_to_ascii_given && !args_info.idna_to_unicode_given && !args_info.nfkc_given) args_info.idna_to_ascii_given = 1; if ((args_info.stringprep_given ? 1 : 0) + (args_info.punycode_encode_given ? 1 : 0) + (args_info.punycode_decode_given ? 1 : 0) + (args_info.idna_to_ascii_given ? 1 : 0) + (args_info.idna_to_unicode_given ? 1 : 0) + (args_info.nfkc_given ? 1 : 0) != 1) { error (0, 0, _("only one of -s, -e, -d, -a, -u or -n can be specified")); usage (EXIT_FAILURE); } if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, "%s %s\n" GREETING, PACKAGE, VERSION); if (args_info.debug_given) fprintf (stderr, _("Charset `%s'.\n"), stringprep_locale_charset ()); if (!args_info.quiet_given && args_info.inputs_num == 0 && isatty (fileno (stdin))) fprintf (stderr, _("Type each input string on a line by itself, " "terminated by a newline character.\n")); do { if (cmdn < args_info.inputs_num) line = strdup (args_info.inputs[cmdn++]); else if (getline (&line, &linelen, stdin) == -1) { if (feof (stdin)) break; error (EXIT_FAILURE, errno, _("input error")); } if (strlen (line) > 0) if (line[strlen (line) - 1] == '\n') line[strlen (line) - 1] = '\0'; if (args_info.stringprep_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); rc = stringprep_profile (p, &r, args_info.profile_given ? args_info.profile_arg : "Nameprep", 0); free (p); if (rc != STRINGPREP_OK) error (EXIT_FAILURE, 0, _("stringprep_profile: %s"), stringprep_strerror (rc)); q = stringprep_utf8_to_ucs4 (r, -1, NULL); if (!q) { free (r); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.punycode_encode_given) { char encbuf[BUFSIZ]; size_t len, len2; p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, &len); free (p); if (!q) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); if (args_info.debug_given) { size_t i; for (i = 0; i < len; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } len2 = BUFSIZ - 1; rc = punycode_encode (len, q, NULL, &len2, encbuf); free (q); if (rc != PUNYCODE_SUCCESS) error (EXIT_FAILURE, 0, _("punycode_encode: %s"), punycode_strerror (rc)); encbuf[len2] = '\0'; p = stringprep_utf8_to_locale (encbuf); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.punycode_decode_given) { size_t len; len = BUFSIZ; q = (uint32_t *) malloc (len * sizeof (q[0])); if (!q) error (EXIT_FAILURE, ENOMEM, N_("malloc")); rc = punycode_decode (strlen (line), line, &len, q, NULL); if (rc != PUNYCODE_SUCCESS) { free (q); error (EXIT_FAILURE, 0, _("punycode_decode: %s"), punycode_strerror (rc)); } if (args_info.debug_given) { size_t i; for (i = 0; i < len; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } q[len] = 0; r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL); free (q); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); p = stringprep_utf8_to_locale (r); free (r); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.idna_to_ascii_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); free (p); if (!q) error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } rc = idna_to_ascii_4z (q, &p, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); free (q); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_ascii_4z: %s"), idna_strerror (rc)); #ifdef WITH_TLD if (args_info.tld_flag && !args_info.no_tld_flag) { size_t errpos; rc = idna_to_unicode_8z4z (p, &q, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z (TLD): %s"), idna_strerror (rc)); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "tld[%lu] = U+%04x\n", (unsigned long) i, q[i]); } rc = tld_check_4z (q, &errpos, NULL); free (q); if (rc == TLD_INVALID) error (EXIT_FAILURE, 0, _("tld_check_4z (position %lu): %s"), (unsigned long) errpos, tld_strerror (rc)); if (rc != TLD_SUCCESS) error (EXIT_FAILURE, 0, _("tld_check_4z: %s"), tld_strerror (rc)); } #endif if (args_info.debug_given) { size_t i; for (i = 0; p[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, p[i]); } fprintf (stdout, "%s\n", p); free (p); } if (args_info.idna_to_unicode_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UCS-4 to UTF-8")); } if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); } free (q); rc = idna_to_unicode_8z4z (p, &q, (args_info.allow_unassigned_given ? IDNA_ALLOW_UNASSIGNED : 0) | (args_info.usestd3asciirules_given ? IDNA_USE_STD3_ASCII_RULES : 0)); free (p); if (rc != IDNA_SUCCESS) error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z: %s"), idna_strerror (rc)); if (args_info.debug_given) { size_t i; for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); } #ifdef WITH_TLD if (args_info.tld_flag) { size_t errpos; rc = tld_check_4z (q, &errpos, NULL); if (rc == TLD_INVALID) { free (q); error (EXIT_FAILURE, 0, _("tld_check_4z (position %lu): %s"), (unsigned long) errpos, tld_strerror (rc)); } if (rc != TLD_SUCCESS) { free (q); error (EXIT_FAILURE, 0, _("tld_check_4z: %s"), tld_strerror (rc)); } } #endif r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL); free (q); if (!r) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } if (args_info.nfkc_given) { p = stringprep_locale_to_utf8 (line); if (!p) error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"), stringprep_locale_charset ()); if (args_info.debug_given) { size_t i; q = stringprep_utf8_to_ucs4 (p, -1, NULL); if (!q) { free (p); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } for (i = 0; q[i]; i++) fprintf (stderr, "input[%lu] = U+%04x\n", (unsigned long) i, q[i]); free (q); } r = stringprep_utf8_nfkc_normalize (p, -1); free (p); if (!r) error (EXIT_FAILURE, 0, _("could not do NFKC normalization")); if (args_info.debug_given) { size_t i; q = stringprep_utf8_to_ucs4 (r, -1, NULL); if (!q) { free (r); error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to UCS-4")); } for (i = 0; q[i]; i++) fprintf (stderr, "output[%lu] = U+%04x\n", (unsigned long) i, q[i]); free (q); } p = stringprep_utf8_to_locale (r); free (r); if (!p) error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"), stringprep_locale_charset ()); fprintf (stdout, "%s\n", p); free (p); } fflush (stdout); } while (!feof (stdin) && !ferror (stdin) && (args_info.inputs_num == 0 || cmdn < args_info.inputs_num)); free (line); return EXIT_SUCCESS; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,963
poppler
fada09a2ccc11a3a1d308e810f1336d8df6011fd
PDFDoc *PDFDoc::ErrorPDFDoc(int errorCode, const GooString *fileNameA) { PDFDoc *doc = new PDFDoc(); doc->errCode = errorCode; doc->fileName = fileNameA; return doc; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,786
Android
295c883fe3105b19bcd0f9e07d54c6b589fc5bff
OMX_ERRORTYPE SoftAACEncoder2::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_encoder.aac", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAAC)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mBitRate = aacParams->nBitRate; mNumChannels = aacParams->nChannels; mSampleRate = aacParams->nSampleRate; if (aacParams->eAACProfile != OMX_AUDIO_AACObjectNull) { mAACProfile = aacParams->eAACProfile; } if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR) && !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) { mSBRMode = 0; mSBRRatio = 0; } else if ((aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR) && !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) { mSBRMode = 1; mSBRRatio = 1; } else if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR) && (aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) { mSBRMode = 1; mSBRRatio = 2; } else { mSBRMode = -1; // codec default sbr mode mSBRRatio = 0; } if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSampleRate = pcmParams->nSamplingRate; if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
1
CVE-2016-2476
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
1,698
Chrome
69b4b9ef7455753b12c3efe4eec71647e6fb1da1
net::BackoffEntry* DataReductionProxyConfigServiceClient::GetBackoffEntry() { DCHECK(thread_checker_.CalledOnValidThread()); return &backoff_entry_; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,897
Chrome
f6ac1dba5e36f338a490752a2cbef3339096d9fe
bool WebGLRenderingContextBase::ValidateBlendFuncFactors( const char* function_name, GLenum src, GLenum dst) { if (((src == GL_CONSTANT_COLOR || src == GL_ONE_MINUS_CONSTANT_COLOR) && (dst == GL_CONSTANT_ALPHA || dst == GL_ONE_MINUS_CONSTANT_ALPHA)) || ((dst == GL_CONSTANT_COLOR || dst == GL_ONE_MINUS_CONSTANT_COLOR) && (src == GL_CONSTANT_ALPHA || src == GL_ONE_MINUS_CONSTANT_ALPHA))) { SynthesizeGLError(GL_INVALID_OPERATION, function_name, "incompatible src and dst"); return false; } return true; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,561
qemu
c1b886c45dc70f247300f549dce9833f3fa2def5
uint32_t vga_ioport_read(void *opaque, uint32_t addr) { VGACommonState *s = opaque; int val, index; if (vga_ioport_invalid(s, addr)) { val = 0xff; } else { switch(addr) { case VGA_ATT_W: if (s->ar_flip_flop == 0) { val = s->ar_index; } else { val = 0; } break; case VGA_ATT_R: index = s->ar_index & 0x1f; if (index < VGA_ATT_C) { val = s->ar[index]; } else { val = 0; } break; case VGA_MIS_W: val = s->st00; break; case VGA_SEQ_I: val = s->sr_index; break; case VGA_SEQ_D: val = s->sr[s->sr_index]; #ifdef DEBUG_VGA_REG printf("vga: read SR%x = 0x%02x\n", s->sr_index, val); #endif break; case VGA_PEL_IR: val = s->dac_state; break; case VGA_PEL_IW: val = s->dac_write_index; break; case VGA_PEL_D: val = s->palette[s->dac_read_index * 3 + s->dac_sub_index]; if (++s->dac_sub_index == 3) { s->dac_sub_index = 0; s->dac_read_index++; } break; case VGA_FTC_R: val = s->fcr; break; case VGA_MIS_R: val = s->msr; break; case VGA_GFX_I: val = s->gr_index; break; case VGA_GFX_D: val = s->gr[s->gr_index]; #ifdef DEBUG_VGA_REG printf("vga: read GR%x = 0x%02x\n", s->gr_index, val); #endif break; case VGA_CRT_IM: case VGA_CRT_IC: val = s->cr_index; break; case VGA_CRT_DM: case VGA_CRT_DC: val = s->cr[s->cr_index]; #ifdef DEBUG_VGA_REG printf("vga: read CR%x = 0x%02x\n", s->cr_index, val); #endif break; case VGA_IS1_RM: case VGA_IS1_RC: /* just toggle to fool polling */ val = s->st01 = s->retrace(s); s->ar_flip_flop = 0; break; default: val = 0x00; break; } } #if defined(DEBUG_VGA) printf("VGA: read addr=0x%04x data=0x%02x\n", addr, val); #endif return val; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,965
Android
5a9753fca56f0eeb9f61e342b2fccffc364f9426
virtual void DecompressedFrameHook(const vpx_image_t &img, const unsigned int frame_number) { ASSERT_TRUE(md5_file_ != NULL); char expected_md5[33]; char junk[128]; const int res = fscanf(md5_file_, "%s %s", expected_md5, junk); ASSERT_NE(EOF, res) << "Read md5 data failed"; expected_md5[32] = '\0'; ::libvpx_test::MD5 md5_res; md5_res.Add(&img); const char *const actual_md5 = md5_res.Get(); ASSERT_STREQ(expected_md5, actual_md5) << "Md5 checksums don't match: frame number = " << frame_number; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,599
php
2cc4e69cc6d8dbc4b3568ad3dd583324a7c11d64
PHP_MINFO_FUNCTION(pgsql) { char buf[256]; php_info_print_table_start(); php_info_print_table_header(2, "PostgreSQL Support", "enabled"); #if HAVE_PG_CONFIG_H php_info_print_table_row(2, "PostgreSQL(libpq) Version", PG_VERSION); php_info_print_table_row(2, "PostgreSQL(libpq) ", PG_VERSION_STR); #ifdef HAVE_PGSQL_WITH_MULTIBYTE_SUPPORT php_info_print_table_row(2, "Multibyte character support", "enabled"); #else php_info_print_table_row(2, "Multibyte character support", "disabled"); #endif #ifdef USE_SSL php_info_print_table_row(2, "SSL support", "enabled"); #else php_info_print_table_row(2, "SSL support", "disabled"); #endif #endif /* HAVE_PG_CONFIG_H */ snprintf(buf, sizeof(buf), "%ld", PGG(num_persistent)); php_info_print_table_row(2, "Active Persistent Links", buf); snprintf(buf, sizeof(buf), "%ld", PGG(num_links)); php_info_print_table_row(2, "Active Links", buf); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,122
Chrome
ce891a86763d3540e2612be26938a6163310efe0
void ChromeContentRendererClient::RenderThreadStarted() { chrome_observer_.reset(new ChromeRenderProcessObserver()); extension_dispatcher_.reset(new ExtensionDispatcher()); histogram_snapshots_.reset(new RendererHistogramSnapshots()); net_predictor_.reset(new RendererNetPredictor()); spellcheck_.reset(new SpellCheck()); visited_link_slave_.reset(new VisitedLinkSlave()); phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create()); RenderThread* thread = RenderThread::current(); thread->AddFilter(new DevToolsAgentFilter()); thread->AddObserver(chrome_observer_.get()); thread->AddObserver(extension_dispatcher_.get()); thread->AddObserver(histogram_snapshots_.get()); thread->AddObserver(phishing_classifier_.get()); thread->AddObserver(spellcheck_.get()); thread->AddObserver(visited_link_slave_.get()); thread->RegisterExtension(extensions_v8::ExternalExtension::Get()); thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get()); thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get()); v8::Extension* search_extension = extensions_v8::SearchExtension::Get(); if (search_extension) thread->RegisterExtension(search_extension); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDomAutomationController)) { thread->RegisterExtension(DomAutomationV8Extension::Get()); } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableIPCFuzzing)) { thread->channel()->set_outgoing_message_filter(LoadExternalIPCFuzzer()); } WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_ui_scheme); WebString extension_scheme(ASCIIToUTF16(chrome::kExtensionScheme)); WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme); }
1
CVE-2011-2798
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
6,196
Chrome
32a9879fc01c24f9216bb2975200ab8a4afac80c
void ForeignSessionHelper::DeleteForeignSession( JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jstring>& session_tag) { OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate(profile_); if (open_tabs) open_tabs->DeleteForeignSession(ConvertJavaStringToUTF8(env, session_tag)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,858
Chrome
b944f670bb7a8a919daac497a4ea0536c954c201
EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithUnsignedLongArray(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); Vector<unsigned long> unsignedLongArray(jsUnsignedLongArrayToVector(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->methodWithUnsignedLongArray(unsignedLongArray); return JSValue::encode(jsUndefined()); }
1
CVE-2011-2350
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,359
linux
0031c41be5c529f8329e327b63cde92ba1284842
bool radeon_atom_get_tv_timings(struct radeon_device *rdev, int index, struct drm_display_mode *mode) { struct radeon_mode_info *mode_info = &rdev->mode_info; ATOM_ANALOG_TV_INFO *tv_info; ATOM_ANALOG_TV_INFO_V1_2 *tv_info_v1_2; ATOM_DTD_FORMAT *dtd_timings; int data_index = GetIndexIntoMasterTable(DATA, AnalogTV_Info); u8 frev, crev; u16 data_offset, misc; if (!atom_parse_data_header(mode_info->atom_context, data_index, NULL, &frev, &crev, &data_offset)) return false; switch (crev) { case 1: tv_info = (ATOM_ANALOG_TV_INFO *)(mode_info->atom_context->bios + data_offset); if (index > MAX_SUPPORTED_TV_TIMING) return false; mode->crtc_htotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Total); mode->crtc_hdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Disp); mode->crtc_hsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart); mode->crtc_hsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart) + le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncWidth); mode->crtc_vtotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Total); mode->crtc_vdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Disp); mode->crtc_vsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart); mode->crtc_vsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart) + le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncWidth); mode->flags = 0; misc = le16_to_cpu(tv_info->aModeTimings[index].susModeMiscInfo.usAccess); if (misc & ATOM_VSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NVSYNC; if (misc & ATOM_HSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NHSYNC; if (misc & ATOM_COMPOSITESYNC) mode->flags |= DRM_MODE_FLAG_CSYNC; if (misc & ATOM_INTERLACE) mode->flags |= DRM_MODE_FLAG_INTERLACE; if (misc & ATOM_DOUBLE_CLOCK_MODE) mode->flags |= DRM_MODE_FLAG_DBLSCAN; mode->clock = le16_to_cpu(tv_info->aModeTimings[index].usPixelClock) * 10; if (index == 1) { /* PAL timings appear to have wrong values for totals */ mode->crtc_htotal -= 1; mode->crtc_vtotal -= 1; } break; case 2: tv_info_v1_2 = (ATOM_ANALOG_TV_INFO_V1_2 *)(mode_info->atom_context->bios + data_offset); if (index > MAX_SUPPORTED_TV_TIMING_V1_2) return false; dtd_timings = &tv_info_v1_2->aModeTimings[index]; mode->crtc_htotal = le16_to_cpu(dtd_timings->usHActive) + le16_to_cpu(dtd_timings->usHBlanking_Time); mode->crtc_hdisplay = le16_to_cpu(dtd_timings->usHActive); mode->crtc_hsync_start = le16_to_cpu(dtd_timings->usHActive) + le16_to_cpu(dtd_timings->usHSyncOffset); mode->crtc_hsync_end = mode->crtc_hsync_start + le16_to_cpu(dtd_timings->usHSyncWidth); mode->crtc_vtotal = le16_to_cpu(dtd_timings->usVActive) + le16_to_cpu(dtd_timings->usVBlanking_Time); mode->crtc_vdisplay = le16_to_cpu(dtd_timings->usVActive); mode->crtc_vsync_start = le16_to_cpu(dtd_timings->usVActive) + le16_to_cpu(dtd_timings->usVSyncOffset); mode->crtc_vsync_end = mode->crtc_vsync_start + le16_to_cpu(dtd_timings->usVSyncWidth); mode->flags = 0; misc = le16_to_cpu(dtd_timings->susModeMiscInfo.usAccess); if (misc & ATOM_VSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NVSYNC; if (misc & ATOM_HSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NHSYNC; if (misc & ATOM_COMPOSITESYNC) mode->flags |= DRM_MODE_FLAG_CSYNC; if (misc & ATOM_INTERLACE) mode->flags |= DRM_MODE_FLAG_INTERLACE; if (misc & ATOM_DOUBLE_CLOCK_MODE) mode->flags |= DRM_MODE_FLAG_DBLSCAN; mode->clock = le16_to_cpu(dtd_timings->usPixClk) * 10; break; } return true; }
1
CVE-2010-5331
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,768
jasper
988f8365f7d8ad8073b6786e433d34c553ecf568
jas_matrix_t *jas_matrix_create(int numrows, int numcols) { jas_matrix_t *matrix; int i; if (numrows < 0 || numcols < 0) { return 0; } 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-10249
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.
6,984
Chrome
4504a474c069d07104237d0c03bfce7b29a42de6
void HTMLMediaElement::PauseInternal() { BLINK_MEDIA_LOG << "pauseInternal(" << (void*)this << ")"; if (network_state_ == kNetworkEmpty) InvokeResourceSelectionAlgorithm(); can_autoplay_ = false; if (!paused_) { paused_ = true; ScheduleTimeupdateEvent(false); ScheduleEvent(EventTypeNames::pause); SetOfficialPlaybackPosition(CurrentPlaybackPosition()); ScheduleRejectPlayPromises(kAbortError); } UpdatePlayState(); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,922
linux
45f6fad84cc305103b28d73482b344d7f5b76f39
static struct dst_entry *inet6_csk_route_socket(struct sock *sk, struct flowi6 *fl6) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *final_p, final; struct dst_entry *dst; memset(fl6, 0, sizeof(*fl6)); fl6->flowi6_proto = sk->sk_protocol; fl6->daddr = sk->sk_v6_daddr; fl6->saddr = np->saddr; fl6->flowlabel = np->flow_label; IP6_ECN_flow_xmit(sk, fl6->flowlabel); fl6->flowi6_oif = sk->sk_bound_dev_if; fl6->flowi6_mark = sk->sk_mark; fl6->fl6_sport = inet->inet_sport; fl6->fl6_dport = inet->inet_dport; security_sk_classify_flow(sk, flowi6_to_flowi(fl6)); final_p = fl6_update_dst(fl6, np->opt, &final); dst = __inet6_csk_dst_check(sk, np->dst_cookie); if (!dst) { dst = ip6_dst_lookup_flow(sk, fl6, final_p); if (!IS_ERR(dst)) __inet6_csk_dst_store(sk, dst, NULL, NULL); } return dst; }
1
CVE-2016-3841
CWE-416
Use After Free
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
Phase: Architecture and Design Strategy: Language Selection Choose a language that provides automatic memory management. Phase: Implementation Strategy: Attack Surface Reduction When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy. Effectiveness: Defense in Depth Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution.
3,908
linux
9ad2de43f1aee7e7274a4e0d41465489299e344b
static int rfcomm_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct bt_security sec; int len, err = 0; BT_DBG("sk %p", sk); if (level == SOL_RFCOMM) return rfcomm_sock_getsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; break; } sec.level = rfcomm_pi(sk)->sec_level; len = min_t(unsigned int, len, sizeof(sec)); if (copy_to_user(optval, (char *) &sec, len)) err = -EFAULT; break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags), (u32 __user *) optval)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; }
1
CVE-2012-6545
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.
9,858
tensorflow
c99d98cd189839dcf51aee94e7437b54b31f8abd
NodeDef* Node::mutable_def() { return &props_->node_def; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,180
Android
c57fc3703ae2e0d41b1f6580c50015937f2d23c1
WORD32 ih264d_cavlc_parse_8x8block_none_available(WORD16 *pi2_coeff_block, UWORD32 u4_sub_block_strd, UWORD32 u4_isdc, dec_struct_t * ps_dec, UWORD8 *pu1_top_nnz, UWORD8 *pu1_left_nnz, UWORD8 u1_tran_form8x8, UWORD8 u1_mb_field_decodingflag, UWORD32 *pu4_csbp) { UWORD32 u4_num_coeff, u4_n, u4_subblock_coded; UWORD32 u4_top0, u4_top1; UWORD32 *pu4_dummy; WORD32 (**pf_cavlc_parse4x4coeff)(WORD16 *pi2_coeff_block, UWORD32 u4_isdc, WORD32 u4_n, struct _DecStruct *ps_dec, UWORD32 *pu4_dummy) = ps_dec->pf_cavlc_parse4x4coeff; UWORD32 u4_idx = 0; UWORD8 *puc_temp; WORD32 ret; *pu4_csbp = 0; puc_temp = ps_dec->pu1_inv_scan; /*------------------------------------------------------*/ /* Residual 4x4 decoding: SubBlock 0 */ /*------------------------------------------------------*/ if(u1_tran_form8x8) { if(!u1_mb_field_decodingflag) { ps_dec->pu1_inv_scan = (UWORD8*)gau1_ih264d_inv_scan_prog8x8_cavlc[0]; } else { ps_dec->pu1_inv_scan = (UWORD8*)gau1_ih264d_inv_scan_int8x8_cavlc[0]; } } ret = pf_cavlc_parse4x4coeff[0](pi2_coeff_block, u4_isdc, 0, ps_dec, &u4_num_coeff); if(ret != OK) return ret; u4_top0 = u4_num_coeff; u4_subblock_coded = (u4_num_coeff != 0); INSERT_BIT(*pu4_csbp, u4_idx, u4_subblock_coded); /*------------------------------------------------------*/ /* Residual 4x4 decoding: SubBlock 1 */ /*------------------------------------------------------*/ u4_idx++; if(u1_tran_form8x8) { if(!u1_mb_field_decodingflag) { ps_dec->pu1_inv_scan = (UWORD8*)gau1_ih264d_inv_scan_prog8x8_cavlc[1]; } else { ps_dec->pu1_inv_scan = (UWORD8*)gau1_ih264d_inv_scan_int8x8_cavlc[1]; } } else { pi2_coeff_block += NUM_COEFFS_IN_4x4BLK; } u4_n = u4_num_coeff; ret = pf_cavlc_parse4x4coeff[(u4_n > 7)](pi2_coeff_block, u4_isdc, u4_n, ps_dec, &u4_num_coeff); if(ret != OK) return ret; u4_top1 = pu1_left_nnz[0] = u4_num_coeff; u4_subblock_coded = (u4_num_coeff != 0); INSERT_BIT(*pu4_csbp, u4_idx, u4_subblock_coded); /*------------------------------------------------------*/ /* Residual 4x4 decoding: SubBlock 2 */ /*------------------------------------------------------*/ u4_idx += (u4_sub_block_strd - 1); if(u1_tran_form8x8) { if(!u1_mb_field_decodingflag) { ps_dec->pu1_inv_scan = (UWORD8*)gau1_ih264d_inv_scan_prog8x8_cavlc[2]; } else { ps_dec->pu1_inv_scan = (UWORD8*)gau1_ih264d_inv_scan_int8x8_cavlc[2]; } } else { pi2_coeff_block += ((u4_sub_block_strd - 1) * NUM_COEFFS_IN_4x4BLK); } u4_n = u4_top0; ret = pf_cavlc_parse4x4coeff[(u4_n > 7)](pi2_coeff_block, u4_isdc, u4_n, ps_dec, &u4_num_coeff); if(ret != OK) return ret; pu1_top_nnz[0] = u4_num_coeff; u4_subblock_coded = (u4_num_coeff != 0); INSERT_BIT(*pu4_csbp, u4_idx, u4_subblock_coded); /*------------------------------------------------------*/ /* Residual 4x4 decoding: SubBlock 3 */ /*------------------------------------------------------*/ u4_idx++; if(u1_tran_form8x8) { if(!u1_mb_field_decodingflag) { ps_dec->pu1_inv_scan = (UWORD8*)gau1_ih264d_inv_scan_prog8x8_cavlc[3]; } else { ps_dec->pu1_inv_scan = (UWORD8*)gau1_ih264d_inv_scan_int8x8_cavlc[3]; } } else { pi2_coeff_block += NUM_COEFFS_IN_4x4BLK; } u4_n = (u4_top1 + u4_num_coeff + 1) >> 1; ret = pf_cavlc_parse4x4coeff[(u4_n > 7)](pi2_coeff_block, u4_isdc, u4_n, ps_dec, &u4_num_coeff); if(ret != OK) return ret; pu1_top_nnz[1] = pu1_left_nnz[1] = u4_num_coeff; u4_subblock_coded = (u4_num_coeff != 0); INSERT_BIT(*pu4_csbp, u4_idx, u4_subblock_coded); ps_dec->pu1_inv_scan = puc_temp; return OK; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,909
qemu
f6091d86ba9ea05f4e111b9b42ee0005c37a6779
virgl_cmd_ctx_detach_resource(VuGpu *g, struct virtio_gpu_ctrl_command *cmd) { struct virtio_gpu_ctx_resource det_res; VUGPU_FILL_CMD(det_res); virgl_renderer_ctx_detach_resource(det_res.hdr.ctx_id, det_res.resource_id); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,711
libvncserver
57433015f856cc12753378254ce4f1c78f5d9c7b
static void CopyRectangleFromRectangle(rfbClient* client, int src_x, int src_y, int w, int h, int dest_x, int dest_y) { int i,j; if (client->frameBuffer == NULL) { return; } if (!CheckRect(client, src_x, src_y, w, h)) { rfbClientLog("Source rect out of bounds: %dx%d at (%d, %d)\n", src_x, src_y, w, h); return; } if (!CheckRect(client, dest_x, dest_y, w, h)) { rfbClientLog("Dest rect out of bounds: %dx%d at (%d, %d)\n", dest_x, dest_y, w, h); return; } #define COPY_RECT_FROM_RECT(BPP) \ { \ uint##BPP##_t* _buffer=((uint##BPP##_t*)client->frameBuffer)+(src_y-dest_y)*client->width+src_x-dest_x; \ if (dest_y < src_y) { \ for(j = dest_y*client->width; j < (dest_y+h)*client->width; j += client->width) { \ if (dest_x < src_x) { \ for(i = dest_x; i < dest_x+w; i++) { \ ((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \ } \ } else { \ for(i = dest_x+w-1; i >= dest_x; i--) { \ ((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \ } \ } \ } \ } else { \ for(j = (dest_y+h-1)*client->width; j >= dest_y*client->width; j-=client->width) { \ if (dest_x < src_x) { \ for(i = dest_x; i < dest_x+w; i++) { \ ((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \ } \ } else { \ for(i = dest_x+w-1; i >= dest_x; i--) { \ ((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \ } \ } \ } \ } \ } switch(client->format.bitsPerPixel) { case 8: COPY_RECT_FROM_RECT(8); break; case 16: COPY_RECT_FROM_RECT(16); break; case 32: COPY_RECT_FROM_RECT(32); break; default: rfbClientLog("Unsupported bitsPerPixel: %d\n",client->format.bitsPerPixel); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,541
poppler
b1026b5978c385328f2a15a2185c599a563edf91
int StreamPredictor::getChar() { if (predIdx >= rowBytes) { if (!getNextLine()) { return EOF; } } return predLine[predIdx++]; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,643
ImageMagick
56d6e20de489113617cbbddaf41e92600a34db22
ModuleExport size_t RegisterMSLImage(void) { MagickInfo *entry; #if defined(MAGICKCORE_XML_DELEGATE) xmlInitParser(); #endif entry=SetMagickInfo("MSL"); #if defined(MAGICKCORE_XML_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadMSLImage; entry->encoder=(EncodeImageHandler *) WriteMSLImage; #endif entry->format_type=ImplicitFormatType; entry->description=ConstantString("Magick Scripting Language"); entry->module=ConstantString("MSL"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,153
Chrome
c63f2b7fe4fe2977f858a8e36d5f48db17eff2e7
ExtensionTtsPlatformImpl* ExtensionTtsController::GetPlatformImpl() { if (!platform_impl_) platform_impl_ = ExtensionTtsPlatformImpl::GetInstance(); return platform_impl_; }
1
CVE-2011-2839
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
2,672
openssl
32cc2479b473c49ce869e57fded7e9a77b695c0d
void ssl3_cbc_digest_record( const EVP_MD_CTX *ctx, unsigned char* md_out, size_t* md_out_size, const unsigned char header[13], const unsigned char *data, size_t data_plus_mac_size, size_t data_plus_mac_plus_padding_size, const unsigned char *mac_secret, unsigned mac_secret_length, char is_sslv3) { union { double align; unsigned char c[sizeof(LARGEST_DIGEST_CTX)]; } md_state; void (*md_final_raw)(void *ctx, unsigned char *md_out); void (*md_transform)(void *ctx, const unsigned char *block); unsigned md_size, md_block_size = 64; unsigned sslv3_pad_length = 40, header_length, variance_blocks, len, max_mac_bytes, num_blocks, num_starting_blocks, k, mac_end_offset, c, index_a, index_b; unsigned int bits; /* at most 18 bits */ unsigned char length_bytes[MAX_HASH_BIT_COUNT_BYTES]; /* hmac_pad is the masked HMAC key. */ unsigned char hmac_pad[MAX_HASH_BLOCK_SIZE]; unsigned char first_block[MAX_HASH_BLOCK_SIZE]; unsigned char mac_out[EVP_MAX_MD_SIZE]; unsigned i, j, md_out_size_u; EVP_MD_CTX md_ctx; /* mdLengthSize is the number of bytes in the length field that terminates * the hash. */ unsigned md_length_size = 8; char length_is_big_endian = 1; /* This is a, hopefully redundant, check that allows us to forget about * many possible overflows later in this function. */ OPENSSL_assert(data_plus_mac_plus_padding_size < 1024*1024); switch (EVP_MD_CTX_type(ctx)) { case NID_md5: MD5_Init((MD5_CTX*)md_state.c); md_final_raw = tls1_md5_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) MD5_Transform; md_size = 16; sslv3_pad_length = 48; length_is_big_endian = 0; break; case NID_sha1: SHA1_Init((SHA_CTX*)md_state.c); md_final_raw = tls1_sha1_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA1_Transform; md_size = 20; break; #ifndef OPENSSL_NO_SHA256 case NID_sha224: SHA224_Init((SHA256_CTX*)md_state.c); md_final_raw = tls1_sha256_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA256_Transform; md_size = 224/8; break; case NID_sha256: SHA256_Init((SHA256_CTX*)md_state.c); md_final_raw = tls1_sha256_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA256_Transform; md_size = 32; break; #endif #ifndef OPENSSL_NO_SHA512 case NID_sha384: SHA384_Init((SHA512_CTX*)md_state.c); md_final_raw = tls1_sha512_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA512_Transform; md_size = 384/8; md_block_size = 128; md_length_size = 16; break; case NID_sha512: SHA512_Init((SHA512_CTX*)md_state.c); md_final_raw = tls1_sha512_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA512_Transform; md_size = 64; md_block_size = 128; md_length_size = 16; break; #endif default: /* ssl3_cbc_record_digest_supported should have been * called first to check that the hash function is * supported. */ OPENSSL_assert(0); if (md_out_size) *md_out_size = -1; return; } OPENSSL_assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES); OPENSSL_assert(md_block_size <= MAX_HASH_BLOCK_SIZE); OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE); header_length = 13; if (is_sslv3) { header_length = mac_secret_length + sslv3_pad_length + 8 /* sequence number */ + 1 /* record type */ + 2 /* record length */; } /* variance_blocks is the number of blocks of the hash that we have to * calculate in constant time because they could be altered by the * padding value. * * In SSLv3, the padding must be minimal so the end of the plaintext * varies by, at most, 15+20 = 35 bytes. (We conservatively assume that * the MAC size varies from 0..20 bytes.) In case the 9 bytes of hash * termination (0x80 + 64-bit length) don't fit in the final block, we * say that the final two blocks can vary based on the padding. * * TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not * required to be minimal. Therefore we say that the final six blocks * can vary based on the padding. * * Later in the function, if the message is short and there obviously * cannot be this many blocks then variance_blocks can be reduced. */ variance_blocks = is_sslv3 ? 2 : 6; /* From now on we're dealing with the MAC, which conceptually has 13 * bytes of `header' before the start of the data (TLS) or 71/75 bytes * (SSLv3) */ len = data_plus_mac_plus_padding_size + header_length; /* max_mac_bytes contains the maximum bytes of bytes in the MAC, including * |header|, assuming that there's no padding. */ max_mac_bytes = len - md_size - 1; /* num_blocks is the maximum number of hash blocks. */ num_blocks = (max_mac_bytes + 1 + md_length_size + md_block_size - 1) / md_block_size; /* In order to calculate the MAC in constant time we have to handle * the final blocks specially because the padding value could cause the * end to appear somewhere in the final |variance_blocks| blocks and we * can't leak where. However, |num_starting_blocks| worth of data can * be hashed right away because no padding value can affect whether * they are plaintext. */ num_starting_blocks = 0; /* k is the starting byte offset into the conceptual header||data where * we start processing. */ k = 0; /* mac_end_offset is the index just past the end of the data to be * MACed. */ mac_end_offset = data_plus_mac_size + header_length - md_size; /* c is the index of the 0x80 byte in the final hash block that * contains application data. */ c = mac_end_offset % md_block_size; /* index_a is the hash block number that contains the 0x80 terminating * value. */ index_a = mac_end_offset / md_block_size; /* index_b is the hash block number that contains the 64-bit hash * length, in bits. */ index_b = (mac_end_offset + md_length_size) / md_block_size; /* bits is the hash-length in bits. It includes the additional hash * block for the masked HMAC key, or whole of |header| in the case of * SSLv3. */ /* For SSLv3, if we're going to have any starting blocks then we need * at least two because the header is larger than a single block. */ if (num_blocks > variance_blocks + (is_sslv3 ? 1 : 0)) { num_starting_blocks = num_blocks - variance_blocks; k = md_block_size*num_starting_blocks; } bits = 8*mac_end_offset; if (!is_sslv3) { /* Compute the initial HMAC block. For SSLv3, the padding and * secret bytes are included in |header| because they take more * than a single block. */ bits += 8*md_block_size; memset(hmac_pad, 0, md_block_size); OPENSSL_assert(mac_secret_length <= sizeof(hmac_pad)); memcpy(hmac_pad, mac_secret, mac_secret_length); for (i = 0; i < md_block_size; i++) hmac_pad[i] ^= 0x36; md_transform(md_state.c, hmac_pad); } if (length_is_big_endian) { memset(length_bytes,0,md_length_size-4); length_bytes[md_length_size-4] = (unsigned char)(bits>>24); length_bytes[md_length_size-3] = (unsigned char)(bits>>16); length_bytes[md_length_size-2] = (unsigned char)(bits>>8); length_bytes[md_length_size-1] = (unsigned char)bits; } else { memset(length_bytes,0,md_length_size); length_bytes[md_length_size-5] = (unsigned char)(bits>>24); length_bytes[md_length_size-6] = (unsigned char)(bits>>16); length_bytes[md_length_size-7] = (unsigned char)(bits>>8); length_bytes[md_length_size-8] = (unsigned char)bits; } if (k > 0) { if (is_sslv3) { /* The SSLv3 header is larger than a single block. * overhang is the number of bytes beyond a single * block that the header consumes: either 7 bytes * (SHA1) or 11 bytes (MD5). */ unsigned overhang = header_length-md_block_size; md_transform(md_state.c, header); memcpy(first_block, header + md_block_size, overhang); memcpy(first_block + overhang, data, md_block_size-overhang); md_transform(md_state.c, first_block); for (i = 1; i < k/md_block_size - 1; i++) md_transform(md_state.c, data + md_block_size*i - overhang); } else { /* k is a multiple of md_block_size. */ memcpy(first_block, header, 13); memcpy(first_block+13, data, md_block_size-13); md_transform(md_state.c, first_block); for (i = 1; i < k/md_block_size; i++) md_transform(md_state.c, data + md_block_size*i - 13); } } memset(mac_out, 0, sizeof(mac_out)); /* We now process the final hash blocks. For each block, we construct * it in constant time. If the |i==index_a| then we'll include the 0x80 * bytes and zero pad etc. For each block we selectively copy it, in * constant time, to |mac_out|. */ for (i = num_starting_blocks; i <= num_starting_blocks+variance_blocks; i++) { unsigned char block[MAX_HASH_BLOCK_SIZE]; unsigned char is_block_a = constant_time_eq_8(i, index_a); unsigned char is_block_b = constant_time_eq_8(i, index_b); for (j = 0; j < md_block_size; j++) { unsigned char b = 0, is_past_c, is_past_cp1; if (k < header_length) b = header[k]; else if (k < data_plus_mac_plus_padding_size + header_length) b = data[k-header_length]; k++; is_past_c = is_block_a & constant_time_ge(j, c); is_past_cp1 = is_block_a & constant_time_ge(j, c+1); /* If this is the block containing the end of the * application data, and we are at the offset for the * 0x80 value, then overwrite b with 0x80. */ b = (b&~is_past_c) | (0x80&is_past_c); /* If this the the block containing the end of the * application data and we're past the 0x80 value then * just write zero. */ b = b&~is_past_cp1; /* If this is index_b (the final block), but not * index_a (the end of the data), then the 64-bit * length didn't fit into index_a and we're having to * add an extra block of zeros. */ b &= ~is_block_b | is_block_a; /* The final bytes of one of the blocks contains the * length. */ if (j >= md_block_size - md_length_size) { /* If this is index_b, write a length byte. */ b = (b&~is_block_b) | (is_block_b&length_bytes[j-(md_block_size-md_length_size)]); } block[j] = b; } md_transform(md_state.c, block); md_final_raw(md_state.c, block); /* If this is index_b, copy the hash value to |mac_out|. */ for (j = 0; j < md_size; j++) mac_out[j] |= block[j]&is_block_b; } EVP_MD_CTX_init(&md_ctx); EVP_DigestInit_ex(&md_ctx, ctx->digest, NULL /* engine */); if (is_sslv3) { /* We repurpose |hmac_pad| to contain the SSLv3 pad2 block. */ memset(hmac_pad, 0x5c, sslv3_pad_length); EVP_DigestUpdate(&md_ctx, mac_secret, mac_secret_length); EVP_DigestUpdate(&md_ctx, hmac_pad, sslv3_pad_length); EVP_DigestUpdate(&md_ctx, mac_out, md_size); } else { /* Complete the HMAC in the standard manner. */ for (i = 0; i < md_block_size; i++) hmac_pad[i] ^= 0x6a; EVP_DigestUpdate(&md_ctx, hmac_pad, md_block_size); EVP_DigestUpdate(&md_ctx, mac_out, md_size); } EVP_DigestFinal(&md_ctx, md_out, &md_out_size_u); if (md_out_size) *md_out_size = md_out_size_u; EVP_MD_CTX_cleanup(&md_ctx); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,075
qemu
1e7aed70144b4673fc26e73062064b6724795e5f
void virtio_queue_set_align(VirtIODevice *vdev, int n, int align) { BusState *qbus = qdev_get_parent_bus(DEVICE(vdev)); VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); /* virtio-1 compliant devices cannot change the alignment */ if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) { error_report("tried to modify queue alignment for virtio-1 device"); return; } /* Check that the transport told us it was going to do this * (so a buggy transport will immediately assert rather than * silently failing to migrate this state) */ assert(k->has_variable_vring_alignment); vdev->vq[n].vring.align = align; virtio_queue_update_rings(vdev, n); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,521
libsoup
0e7b2c1466434a992b6a387497432e1c97b6125c
soup_ntlm_parse_challenge (const char *challenge, char **nonce, char **default_domain, gboolean *ntlmv2_session) { gsize clen; NTLMString domain; guchar *chall; guint32 flags; chall = g_base64_decode (challenge, &clen); if (clen < NTLM_CHALLENGE_DOMAIN_STRING_OFFSET || clen < NTLM_CHALLENGE_NONCE_OFFSET + NTLM_CHALLENGE_NONCE_LENGTH) { g_free (chall); return FALSE; } memcpy (&flags, chall + NTLM_CHALLENGE_FLAGS_OFFSET, sizeof(flags)); flags = GUINT_FROM_LE (flags); *ntlmv2_session = (flags & NTLM_FLAGS_NEGOTIATE_NTLMV2) ? TRUE : FALSE; if (default_domain) { memcpy (&domain, chall + NTLM_CHALLENGE_DOMAIN_STRING_OFFSET, sizeof (domain)); domain.length = GUINT16_FROM_LE (domain.length); domain.offset = GUINT16_FROM_LE (domain.offset); if (clen < domain.length + domain.offset) { g_free (chall); return FALSE; } *default_domain = g_convert ((char *)chall + domain.offset, domain.length, "UTF-8", "UCS-2LE", NULL, NULL, NULL); } if (nonce) { *nonce = g_memdup (chall + NTLM_CHALLENGE_NONCE_OFFSET, NTLM_CHALLENGE_NONCE_LENGTH); } g_free (chall); return TRUE; }
1
CVE-2019-17266
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.
1,661
linux
8f3fafc9c2f0ece10832c25f7ffcb07c97a32ad4
static int cdrom_ioctl_drive_status(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_DRIVE_STATUS\n"); if (!(cdi->ops->capability & CDC_DRIVE_STATUS)) return -ENOSYS; if (!CDROM_CAN(CDC_SELECT_DISC) || (arg == CDSL_CURRENT || arg == CDSL_NONE)) return cdi->ops->drive_status(cdi, CDSL_CURRENT); if (((int)arg >= cdi->capacity)) return -EINVAL; return cdrom_slot_status(cdi, arg); }
1
CVE-2018-16658
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.
1,282
linux
89189557b47b35683a27c80ee78aef18248eefb4
static void drop_sysctl_table(struct ctl_table_header *header) { struct ctl_dir *parent = header->parent; if (--header->nreg) return; if (parent) { put_links(header); start_unregistering(header); } if (!--header->count) kfree_rcu(header, rcu); if (parent) drop_sysctl_table(&parent->header); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,492
Chrome
9ad7483d8e7c20e9f1a5a08d00150fb51899f14c
explicit ShutdownWatchDogThread(const base::TimeDelta& duration) : base::Watchdog(duration, "Shutdown watchdog thread", true) { }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,544
ompl
abb4fadcb4e4fe4c9cf41e5e7706143a66948eb7
ompl::geometric::VFRRT::VFRRT(const base::SpaceInformationPtr &si, VectorField vf, double exploration, double initial_lambda, unsigned int update_freq) : RRT(si) , vf_(std::move(vf)) , explorationSetting_(exploration) , lambda_(initial_lambda) , nth_step_(update_freq) { setName("VFRRT"); maxDistance_ = si->getStateValidityCheckingResolution(); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,280
Chrome
e3de7fc7dbb642ed034afa1c1fed70a748a60f35
void OverscrollControllerAndroid::Disable() { if (!enabled_) return; enabled_ = false; if (!enabled_) { if (refresh_effect_) refresh_effect_->Reset(); if (glow_effect_) glow_effect_->Reset(); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,575
Bento4
5eb8cf89d724ccb0b4ce5f24171ec7c11f0a7647
AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size, AP4_UI08 version, AP4_UI32 flags, AP4_ByteStream& stream) : AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags) { AP4_UI32 predefined; stream.ReadUI32(predefined); stream.ReadUI32(m_HandlerType); stream.ReadUI32(m_Reserved[0]); stream.ReadUI32(m_Reserved[1]); stream.ReadUI32(m_Reserved[2]); // read the name unless it is empty if (size < AP4_FULL_ATOM_HEADER_SIZE+20) return; AP4_UI32 name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20); char* name = new char[name_size+1]; if (name == NULL) return; stream.Read(name, name_size); name[name_size] = '\0'; // force a null termination // handle a special case: the Quicktime files have a pascal // string here, but ISO MP4 files have a C string. // we try to detect a pascal encoding and correct it. if (name[0] == name_size-1) { m_HandlerName = name+1; } else { m_HandlerName = name; } delete[] name; }
1
CVE-2017-14643
CWE-125
Out-of-bounds Read
The product reads data past the end, or before the beginning, of the intended buffer.
Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs. Phase: Architecture and Design Strategy: Language Selection Use a language that provides appropriate memory abstractions.
3,207
krb5
e3b5a5e5267818c97750b266df50b6a3d4649604
pkinit_server_verify_padata(krb5_context context, krb5_data *req_pkt, krb5_kdc_req * request, krb5_enc_tkt_part * enc_tkt_reply, krb5_pa_data * data, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_kdcpreauth_moddata moddata, krb5_kdcpreauth_verify_respond_fn respond, void *arg) { krb5_error_code retval = 0; krb5_data authp_data = {0, 0, NULL}, krb5_authz = {0, 0, NULL}; krb5_pa_pk_as_req *reqp = NULL; krb5_pa_pk_as_req_draft9 *reqp9 = NULL; krb5_auth_pack *auth_pack = NULL; krb5_auth_pack_draft9 *auth_pack9 = NULL; pkinit_kdc_context plgctx = NULL; pkinit_kdc_req_context reqctx = NULL; krb5_checksum cksum = {0, 0, 0, NULL}; krb5_data *der_req = NULL; int valid_eku = 0, valid_san = 0; krb5_data k5data; int is_signed = 1; krb5_pa_data **e_data = NULL; krb5_kdcpreauth_modreq modreq = NULL; pkiDebug("pkinit_verify_padata: entered!\n"); if (data == NULL || data->length <= 0 || data->contents == NULL) { (*respond)(arg, 0, NULL, NULL, NULL); return; } if (moddata == NULL) { (*respond)(arg, EINVAL, NULL, NULL, NULL); return; } plgctx = pkinit_find_realm_context(context, moddata, request->server); if (plgctx == NULL) { (*respond)(arg, 0, NULL, NULL, NULL); return; } #ifdef DEBUG_ASN1 print_buffer_bin(data->contents, data->length, "/tmp/kdc_as_req"); #endif /* create a per-request context */ retval = pkinit_init_kdc_req_context(context, &reqctx); if (retval) goto cleanup; reqctx->pa_type = data->pa_type; PADATA_TO_KRB5DATA(data, &k5data); switch ((int)data->pa_type) { case KRB5_PADATA_PK_AS_REQ: pkiDebug("processing KRB5_PADATA_PK_AS_REQ\n"); retval = k5int_decode_krb5_pa_pk_as_req(&k5data, &reqp); if (retval) { pkiDebug("decode_krb5_pa_pk_as_req failed\n"); goto cleanup; } #ifdef DEBUG_ASN1 print_buffer_bin(reqp->signedAuthPack.data, reqp->signedAuthPack.length, "/tmp/kdc_signed_data"); #endif retval = cms_signeddata_verify(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_CLIENT, plgctx->opts->require_crl_checking, (unsigned char *) reqp->signedAuthPack.data, reqp->signedAuthPack.length, (unsigned char **)&authp_data.data, &authp_data.length, (unsigned char **)&krb5_authz.data, &krb5_authz.length, &is_signed); break; case KRB5_PADATA_PK_AS_REP_OLD: case KRB5_PADATA_PK_AS_REQ_OLD: pkiDebug("processing KRB5_PADATA_PK_AS_REQ_OLD\n"); retval = k5int_decode_krb5_pa_pk_as_req_draft9(&k5data, &reqp9); if (retval) { pkiDebug("decode_krb5_pa_pk_as_req_draft9 failed\n"); goto cleanup; } #ifdef DEBUG_ASN1 print_buffer_bin(reqp9->signedAuthPack.data, reqp9->signedAuthPack.length, "/tmp/kdc_signed_data_draft9"); #endif retval = cms_signeddata_verify(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_DRAFT9, plgctx->opts->require_crl_checking, (unsigned char *) reqp9->signedAuthPack.data, reqp9->signedAuthPack.length, (unsigned char **)&authp_data.data, &authp_data.length, (unsigned char **)&krb5_authz.data, &krb5_authz.length, NULL); break; default: pkiDebug("unrecognized pa_type = %d\n", data->pa_type); retval = EINVAL; goto cleanup; } if (retval) { pkiDebug("pkcs7_signeddata_verify failed\n"); goto cleanup; } if (is_signed) { retval = verify_client_san(context, plgctx, reqctx, request->client, &valid_san); if (retval) goto cleanup; if (!valid_san) { pkiDebug("%s: did not find an acceptable SAN in user " "certificate\n", __FUNCTION__); retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto cleanup; } retval = verify_client_eku(context, plgctx, reqctx, &valid_eku); if (retval) goto cleanup; if (!valid_eku) { pkiDebug("%s: did not find an acceptable EKU in user " "certificate\n", __FUNCTION__); retval = KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE; goto cleanup; } } else { /* !is_signed */ if (!krb5_principal_compare(context, request->client, krb5_anonymous_principal())) { retval = KRB5KDC_ERR_PREAUTH_FAILED; krb5_set_error_message(context, retval, _("Pkinit request not signed, but client " "not anonymous.")); goto cleanup; } } #ifdef DEBUG_ASN1 print_buffer_bin(authp_data.data, authp_data.length, "/tmp/kdc_auth_pack"); #endif OCTETDATA_TO_KRB5DATA(&authp_data, &k5data); switch ((int)data->pa_type) { case KRB5_PADATA_PK_AS_REQ: retval = k5int_decode_krb5_auth_pack(&k5data, &auth_pack); if (retval) { pkiDebug("failed to decode krb5_auth_pack\n"); goto cleanup; } retval = krb5_check_clockskew(context, auth_pack->pkAuthenticator.ctime); if (retval) goto cleanup; /* check dh parameters */ if (auth_pack->clientPublicValue != NULL) { retval = server_check_dh(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, &auth_pack->clientPublicValue->algorithm.parameters, plgctx->opts->dh_min_bits); if (retval) { pkiDebug("bad dh parameters\n"); goto cleanup; } } else if (!is_signed) { /*Anonymous pkinit requires DH*/ retval = KRB5KDC_ERR_PREAUTH_FAILED; krb5_set_error_message(context, retval, _("Anonymous pkinit without DH public " "value not supported.")); goto cleanup; } der_req = cb->request_body(context, rock); retval = krb5_c_make_checksum(context, CKSUMTYPE_NIST_SHA, NULL, 0, der_req, &cksum); if (retval) { pkiDebug("unable to calculate AS REQ checksum\n"); goto cleanup; } if (cksum.length != auth_pack->pkAuthenticator.paChecksum.length || k5_bcmp(cksum.contents, auth_pack->pkAuthenticator.paChecksum.contents, cksum.length) != 0) { pkiDebug("failed to match the checksum\n"); #ifdef DEBUG_CKSUM pkiDebug("calculating checksum on buf size (%d)\n", req_pkt->length); print_buffer(req_pkt->data, req_pkt->length); pkiDebug("received checksum type=%d size=%d ", auth_pack->pkAuthenticator.paChecksum.checksum_type, auth_pack->pkAuthenticator.paChecksum.length); print_buffer(auth_pack->pkAuthenticator.paChecksum.contents, auth_pack->pkAuthenticator.paChecksum.length); pkiDebug("expected checksum type=%d size=%d ", cksum.checksum_type, cksum.length); print_buffer(cksum.contents, cksum.length); #endif retval = KRB5KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED; goto cleanup; } /* check if kdcPkId present and match KDC's subjectIdentifier */ if (reqp->kdcPkId.data != NULL) { int valid_kdcPkId = 0; retval = pkinit_check_kdc_pkid(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, (unsigned char *)reqp->kdcPkId.data, reqp->kdcPkId.length, &valid_kdcPkId); if (retval) goto cleanup; if (!valid_kdcPkId) pkiDebug("kdcPkId in AS_REQ does not match KDC's cert" "RFC says to ignore and proceed\n"); } /* remember the decoded auth_pack for verify_padata routine */ reqctx->rcv_auth_pack = auth_pack; auth_pack = NULL; break; case KRB5_PADATA_PK_AS_REP_OLD: case KRB5_PADATA_PK_AS_REQ_OLD: retval = k5int_decode_krb5_auth_pack_draft9(&k5data, &auth_pack9); if (retval) { pkiDebug("failed to decode krb5_auth_pack_draft9\n"); goto cleanup; } if (auth_pack9->clientPublicValue != NULL) { retval = server_check_dh(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, &auth_pack9->clientPublicValue->algorithm.parameters, plgctx->opts->dh_min_bits); if (retval) { pkiDebug("bad dh parameters\n"); goto cleanup; } } /* remember the decoded auth_pack for verify_padata routine */ reqctx->rcv_auth_pack9 = auth_pack9; auth_pack9 = NULL; break; } /* remember to set the PREAUTH flag in the reply */ enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH; modreq = (krb5_kdcpreauth_modreq)reqctx; reqctx = NULL; cleanup: if (retval && data->pa_type == KRB5_PADATA_PK_AS_REQ) { pkiDebug("pkinit_verify_padata failed: creating e-data\n"); if (pkinit_create_edata(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, plgctx->opts, retval, &e_data)) pkiDebug("pkinit_create_edata failed\n"); } switch ((int)data->pa_type) { case KRB5_PADATA_PK_AS_REQ: free_krb5_pa_pk_as_req(&reqp); free(cksum.contents); break; case KRB5_PADATA_PK_AS_REP_OLD: case KRB5_PADATA_PK_AS_REQ_OLD: free_krb5_pa_pk_as_req_draft9(&reqp9); } free(authp_data.data); free(krb5_authz.data); if (reqctx != NULL) pkinit_fini_kdc_req_context(context, reqctx); free_krb5_auth_pack(&auth_pack); free_krb5_auth_pack_draft9(context, &auth_pack9); (*respond)(arg, retval, modreq, e_data, NULL); }
1
CVE-2015-2694
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
610
openssl
8e20499629b6bcf868d0072c7011e590b5c2294d
static int rc4_hmac_md5_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { EVP_RC4_HMAC_MD5 *key = data(ctx); switch (type) { case EVP_CTRL_AEAD_SET_MAC_KEY: { unsigned int i; unsigned char hmac_key[64]; memset(hmac_key, 0, sizeof(hmac_key)); if (arg > (int)sizeof(hmac_key)) { MD5_Init(&key->head); MD5_Update(&key->head, ptr, arg); MD5_Final(hmac_key, &key->head); } else { memcpy(hmac_key, ptr, arg); } for (i = 0; i < sizeof(hmac_key); i++) hmac_key[i] ^= 0x36; /* ipad */ MD5_Init(&key->head); MD5_Update(&key->head, hmac_key, sizeof(hmac_key)); for (i = 0; i < sizeof(hmac_key); i++) hmac_key[i] ^= 0x36 ^ 0x5c; /* opad */ MD5_Init(&key->tail); MD5_Update(&key->tail, hmac_key, sizeof(hmac_key)); OPENSSL_cleanse(hmac_key, sizeof(hmac_key)); return 1; } case EVP_CTRL_AEAD_TLS1_AAD: { unsigned char *p = ptr; unsigned int len; if (arg != EVP_AEAD_TLS1_AAD_LEN) return -1; len = p[arg - 2] << 8 | p[arg - 1]; if (!EVP_CIPHER_CTX_encrypting(ctx)) { len -= MD5_DIGEST_LENGTH; p[arg - 2] = len >> 8; p[arg - 1] = len; } key->payload_length = len; key->md = key->head; MD5_Update(&key->md, p, arg); return MD5_DIGEST_LENGTH; } default: return -1; } }
1
CVE-2017-3731
CWE-125
Out-of-bounds Read
The product reads data past the end, or before the beginning, of the intended buffer.
Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs. Phase: Architecture and Design Strategy: Language Selection Use a language that provides appropriate memory abstractions.
3,026
linux
8dca4a41f1ad65043a78c2338d9725f859c8d2c3
static void amd_irq_ack(struct irq_data *d) { /* * based on HW design,there is no need to ack HW * before handle current irq. But this routine is * necessary for handle_edge_irq */ }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,066
libarchive
6e06b1c89dd0d16f74894eac4cfc1327a06ee4a0
archive_read_open2(struct archive *a, void *client_data, archive_open_callback *client_opener, archive_read_callback *client_reader, archive_skip_callback *client_skipper, archive_close_callback *client_closer) { /* Old archive_read_open2() is just a thin shell around * archive_read_open1. */ archive_read_set_callback_data(a, client_data); archive_read_set_open_callback(a, client_opener); archive_read_set_read_callback(a, client_reader); archive_read_set_skip_callback(a, client_skipper); archive_read_set_close_callback(a, client_closer); return archive_read_open1(a); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,098
radare2
a7ce29647fcb38386d7439696375e16e093d6acb
R_API RList *r_anal_var_all_list(RAnal *anal, RAnalFunction *fcn) { // r_anal_var_list if there are not vars with that kind returns a list with // zero element.. which is an unnecessary loss of cpu time RList *list = r_list_new (); if (!list) { return NULL; } RList *reg_vars = r_anal_var_list (anal, fcn, R_ANAL_VAR_KIND_REG); RList *bpv_vars = r_anal_var_list (anal, fcn, R_ANAL_VAR_KIND_BPV); RList *spv_vars = r_anal_var_list (anal, fcn, R_ANAL_VAR_KIND_SPV); r_list_join (list, reg_vars); r_list_join (list, bpv_vars); r_list_join (list, spv_vars); r_list_free (reg_vars); r_list_free (bpv_vars); r_list_free (spv_vars); return list; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,603
lxc
81f466d05f2a89cb4f122ef7f593ff3f279b165c
static int attach_child_main(void* data) { struct attach_clone_payload* payload = (struct attach_clone_payload*)data; int ipc_socket = payload->ipc_socket; int procfd = payload->procfd; lxc_attach_options_t* options = payload->options; struct lxc_proc_context_info* init_ctx = payload->init_ctx; #if HAVE_SYS_PERSONALITY_H long new_personality; #endif int ret; int status; int expected; long flags; int fd; uid_t new_uid; gid_t new_gid; /* wait for the initial thread to signal us that it's ready * for us to start initializing */ expected = 0; status = -1; ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error using IPC to receive notification from initial process (0)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* A description of the purpose of this functionality is * provided in the lxc-attach(1) manual page. We have to * remount here and not in the parent process, otherwise * /proc may not properly reflect the new pid namespace. */ if (!(options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) { ret = lxc_attach_remount_sys_proc(); if (ret < 0) { shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* now perform additional attachments*/ #if HAVE_SYS_PERSONALITY_H if (options->personality < 0) new_personality = init_ctx->personality; else new_personality = options->personality; if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) { ret = personality(new_personality); if (ret < 0) { SYSERROR("could not ensure correct architecture"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } #endif if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) { ret = lxc_attach_drop_privs(init_ctx); if (ret < 0) { ERROR("could not drop privileges"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL) if you want this to be a no-op) */ ret = lxc_attach_set_environment(options->env_policy, options->extra_env_vars, options->extra_keep_env); if (ret < 0) { ERROR("could not set initial environment for attached process"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* set user / group id */ new_uid = 0; new_gid = 0; /* ignore errors, we will fall back to root in that case * (/proc was not mounted etc.) */ if (options->namespaces & CLONE_NEWUSER) lxc_attach_get_init_uidgid(&new_uid, &new_gid); if (options->uid != (uid_t)-1) new_uid = options->uid; if (options->gid != (gid_t)-1) new_gid = options->gid; /* setup the control tty */ if (options->stdin_fd && isatty(options->stdin_fd)) { if (setsid() < 0) { SYSERROR("unable to setsid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } if (ioctl(options->stdin_fd, TIOCSCTTY, (char *)NULL) < 0) { SYSERROR("unable to TIOCSTTY"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* try to set the uid/gid combination */ if ((new_gid != 0 || options->namespaces & CLONE_NEWUSER)) { if (setgid(new_gid) || setgroups(0, NULL)) { SYSERROR("switching to container gid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } if ((new_uid != 0 || options->namespaces & CLONE_NEWUSER) && setuid(new_uid)) { SYSERROR("switching to container uid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* tell initial process it may now put us into the cgroups */ status = 1; ret = lxc_write_nointr(ipc_socket, &status, sizeof(status)); if (ret != sizeof(status)) { ERROR("error using IPC to notify initial process for initialization (1)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* wait for the initial thread to signal us that it has done * everything for us when it comes to cgroups etc. */ expected = 2; status = -1; ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error using IPC to receive final notification from initial process (2)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } shutdown(ipc_socket, SHUT_RDWR); close(ipc_socket); if ((init_ctx->container && init_ctx->container->lxc_conf && init_ctx->container->lxc_conf->no_new_privs) || (options->attach_flags & LXC_ATTACH_NO_NEW_PRIVS)) { if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) { SYSERROR("PR_SET_NO_NEW_PRIVS could not be set. " "Process can use execve() gainable " "privileges."); rexit(-1); } INFO("PR_SET_NO_NEW_PRIVS is set. Process cannot use execve() " "gainable privileges."); } /* set new apparmor profile/selinux context */ if ((options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_LSM) && init_ctx->lsm_label) { int on_exec; on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? 1 : 0; if (lsm_set_label_at(procfd, on_exec, init_ctx->lsm_label) < 0) { rexit(-1); } } if (init_ctx->container && init_ctx->container->lxc_conf && init_ctx->container->lxc_conf->seccomp && (lxc_seccomp_load(init_ctx->container->lxc_conf) != 0)) { ERROR("Loading seccomp policy"); rexit(-1); } lxc_proc_put_context_info(init_ctx); /* The following is done after the communication socket is * shut down. That way, all errors that might (though * unlikely) occur up until this point will have their messages * printed to the original stderr (if logging is so configured) * and not the fd the user supplied, if any. */ /* fd handling for stdin, stdout and stderr; * ignore errors here, user may want to make sure * the fds are closed, for example */ if (options->stdin_fd >= 0 && options->stdin_fd != 0) dup2(options->stdin_fd, 0); if (options->stdout_fd >= 0 && options->stdout_fd != 1) dup2(options->stdout_fd, 1); if (options->stderr_fd >= 0 && options->stderr_fd != 2) dup2(options->stderr_fd, 2); /* close the old fds */ if (options->stdin_fd > 2) close(options->stdin_fd); if (options->stdout_fd > 2) close(options->stdout_fd); if (options->stderr_fd > 2) close(options->stderr_fd); /* try to remove CLOEXEC flag from stdin/stdout/stderr, * but also here, ignore errors */ for (fd = 0; fd <= 2; fd++) { flags = fcntl(fd, F_GETFL); if (flags < 0) continue; if (flags & FD_CLOEXEC) if (fcntl(fd, F_SETFL, flags & ~FD_CLOEXEC) < 0) SYSERROR("Unable to clear CLOEXEC from fd"); } /* we don't need proc anymore */ close(procfd); /* we're done, so we can now do whatever the user intended us to do */ rexit(payload->exec_function(payload->exec_payload)); }
1
CVE-2016-8649
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
Not Found in CWE Page
4,481
cantata
afc4f8315d3e96574925fb530a7004cc9e6ce3d3
static inline bool mpOk(const QString &mp) { return !mp.isEmpty() && mp.startsWith("/home/"); // ) && mp.contains("cantata"); }
1
CVE-2018-12559
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
7,253
Chrome
6c6888565ff1fde9ef21ef17c27ad4c8304643d2
bool TopSitesImpl::GetTemporaryPageThumbnailScore(const GURL& url, ThumbnailScore* score) { for (const TempImage& temp_image : temp_images_) { if (temp_image.first == url) { *score = temp_image.second.thumbnail_score; return true; } } return false; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,135
samba
52dd9f8f835bc23415ec51dcc344478497e208c3
kdc_code kpasswd_process(struct kdc_server *kdc, TALLOC_CTX *mem_ctx, DATA_BLOB *request, DATA_BLOB *reply, struct tsocket_address *remote_addr, struct tsocket_address *local_addr, int datagram) { uint16_t len; uint16_t verno; uint16_t ap_req_len; uint16_t enc_data_len; DATA_BLOB ap_req_blob = data_blob_null; DATA_BLOB ap_rep_blob = data_blob_null; DATA_BLOB enc_data_blob = data_blob_null; DATA_BLOB dec_data_blob = data_blob_null; DATA_BLOB kpasswd_dec_reply = data_blob_null; const char *error_string = NULL; krb5_error_code error_code = 0; struct cli_credentials *server_credentials; struct gensec_security *gensec_security; #ifndef SAMBA4_USES_HEIMDAL struct sockaddr_storage remote_ss; #endif struct sockaddr_storage local_ss; ssize_t socklen; TALLOC_CTX *tmp_ctx; kdc_code rc = KDC_ERROR; krb5_error_code code = 0; NTSTATUS status; int rv; bool is_inet; bool ok; if (kdc->am_rodc) { return KDC_PROXY_REQUEST; } tmp_ctx = talloc_new(mem_ctx); if (tmp_ctx == NULL) { return KDC_ERROR; } is_inet = tsocket_address_is_inet(remote_addr, "ip"); if (!is_inet) { DBG_WARNING("Invalid remote IP address"); goto done; } #ifndef SAMBA4_USES_HEIMDAL /* * FIXME: Heimdal fails to to do a krb5_rd_req() in gensec_krb5 if we * set the remote address. */ /* remote_addr */ socklen = tsocket_address_bsd_sockaddr(remote_addr, (struct sockaddr *)&remote_ss, sizeof(struct sockaddr_storage)); if (socklen < 0) { DBG_WARNING("Invalid remote IP address"); goto done; } #endif /* local_addr */ socklen = tsocket_address_bsd_sockaddr(local_addr, (struct sockaddr *)&local_ss, sizeof(struct sockaddr_storage)); if (socklen < 0) { DBG_WARNING("Invalid local IP address"); goto done; } if (request->length <= HEADER_LEN) { DBG_WARNING("Request truncated\n"); goto done; } len = RSVAL(request->data, 0); if (request->length != len) { DBG_WARNING("Request length does not match\n"); goto done; } verno = RSVAL(request->data, 2); if (verno != 1 && verno != RFC3244_VERSION) { DBG_WARNING("Unsupported version: 0x%04x\n", verno); } ap_req_len = RSVAL(request->data, 4); if ((ap_req_len >= len) || ((ap_req_len + HEADER_LEN) >= len)) { DBG_WARNING("AP_REQ truncated\n"); goto done; } ap_req_blob = data_blob_const(&request->data[HEADER_LEN], ap_req_len); enc_data_len = len - ap_req_len; enc_data_blob = data_blob_const(&request->data[HEADER_LEN + ap_req_len], enc_data_len); server_credentials = cli_credentials_init(tmp_ctx); if (server_credentials == NULL) { DBG_ERR("Failed to initialize server credentials!\n"); goto done; } /* * We want the credentials subsystem to use the krb5 context we already * have, rather than a new context. * * On this context the KDB plugin has been loaded, so we can access * dsdb. */ status = cli_credentials_set_krb5_context(server_credentials, kdc->smb_krb5_context); if (!NT_STATUS_IS_OK(status)) { goto done; } ok = cli_credentials_set_conf(server_credentials, kdc->task->lp_ctx); if (!ok) { goto done; } /* * After calling cli_credentials_set_conf(), explicitly set the realm * with CRED_SPECIFIED. We need to do this so the result of * principal_from_credentials() called from the gensec layer is * CRED_SPECIFIED rather than CRED_SMB_CONF, avoiding a fallback to * match-by-key (very undesirable in this case). */ ok = cli_credentials_set_realm(server_credentials, lpcfg_realm(kdc->task->lp_ctx), CRED_SPECIFIED); if (!ok) { goto done; } ok = cli_credentials_set_username(server_credentials, "kadmin/changepw", CRED_SPECIFIED); if (!ok) { goto done; } /* Check that the server principal is indeed CRED_SPECIFIED. */ { char *principal = NULL; enum credentials_obtained obtained; principal = cli_credentials_get_principal_and_obtained(server_credentials, tmp_ctx, &obtained); if (obtained < CRED_SPECIFIED) { goto done; } TALLOC_FREE(principal); } rv = cli_credentials_set_keytab_name(server_credentials, kdc->task->lp_ctx, kdc->kpasswd_keytab_name, CRED_SPECIFIED); if (rv != 0) { DBG_ERR("Failed to set credentials keytab name\n"); goto done; } status = samba_server_gensec_start(tmp_ctx, kdc->task->event_ctx, kdc->task->msg_ctx, kdc->task->lp_ctx, server_credentials, "kpasswd", &gensec_security); if (!NT_STATUS_IS_OK(status)) { goto done; } status = gensec_set_local_address(gensec_security, local_addr); if (!NT_STATUS_IS_OK(status)) { goto done; } #ifndef SAMBA4_USES_HEIMDAL status = gensec_set_remote_address(gensec_security, remote_addr); if (!NT_STATUS_IS_OK(status)) { goto done; } #endif /* We want the GENSEC wrap calls to generate PRIV tokens */ gensec_want_feature(gensec_security, GENSEC_FEATURE_SEAL); /* Use the krb5 gesec mechanism so we can load DB modules */ status = gensec_start_mech_by_name(gensec_security, "krb5"); if (!NT_STATUS_IS_OK(status)) { goto done; } /* * Accept the AP-REQ and generate the AP-REP we need for the reply * * We only allow KRB5 and make sure the backend to is RPC/IPC free. * * See gensec_krb5_update_internal() as GENSEC_SERVER. * * It allows gensec_update() not to block. * * If that changes in future we need to use * gensec_update_send/recv here! */ status = gensec_update(gensec_security, tmp_ctx, ap_req_blob, &ap_rep_blob); if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) { ap_rep_blob = data_blob_null; error_code = KRB5_KPASSWD_HARDERROR; error_string = talloc_asprintf(tmp_ctx, "gensec_update failed - %s\n", nt_errstr(status)); DBG_ERR("%s", error_string); goto reply; } status = gensec_unwrap(gensec_security, tmp_ctx, &enc_data_blob, &dec_data_blob); if (!NT_STATUS_IS_OK(status)) { ap_rep_blob = data_blob_null; error_code = KRB5_KPASSWD_HARDERROR; error_string = talloc_asprintf(tmp_ctx, "gensec_unwrap failed - %s\n", nt_errstr(status)); DBG_ERR("%s", error_string); goto reply; } code = kpasswd_handle_request(kdc, tmp_ctx, gensec_security, verno, &dec_data_blob, &kpasswd_dec_reply, &error_string); if (code != 0) { ap_rep_blob = data_blob_null; error_code = code; goto reply; } status = gensec_wrap(gensec_security, tmp_ctx, &kpasswd_dec_reply, &enc_data_blob); if (!NT_STATUS_IS_OK(status)) { ap_rep_blob = data_blob_null; error_code = KRB5_KPASSWD_HARDERROR; error_string = talloc_asprintf(tmp_ctx, "gensec_wrap failed - %s\n", nt_errstr(status)); DBG_ERR("%s", error_string); goto reply; } reply: if (error_code != 0) { krb5_data k_enc_data; krb5_data k_dec_data; const char *principal_string; krb5_principal server_principal; if (error_string == NULL) { DBG_ERR("Invalid error string! This should not happen\n"); goto done; } ok = kpasswd_make_error_reply(tmp_ctx, error_code, error_string, &dec_data_blob); if (!ok) { DBG_ERR("Failed to create error reply\n"); goto done; } k_dec_data.length = dec_data_blob.length; k_dec_data.data = (char *)dec_data_blob.data; principal_string = cli_credentials_get_principal(server_credentials, tmp_ctx); if (principal_string == NULL) { goto done; } code = smb_krb5_parse_name(kdc->smb_krb5_context->krb5_context, principal_string, &server_principal); if (code != 0) { DBG_ERR("Failed to create principal: %s\n", error_message(code)); goto done; } code = smb_krb5_mk_error(kdc->smb_krb5_context->krb5_context, KRB5KDC_ERR_NONE + error_code, NULL, /* e_text */ &k_dec_data, NULL, /* client */ server_principal, &k_enc_data); krb5_free_principal(kdc->smb_krb5_context->krb5_context, server_principal); if (code != 0) { DBG_ERR("Failed to create krb5 error reply: %s\n", error_message(code)); goto done; } enc_data_blob = data_blob_talloc(tmp_ctx, k_enc_data.data, k_enc_data.length); if (enc_data_blob.data == NULL) { DBG_ERR("Failed to allocate memory for error reply\n"); goto done; } } *reply = data_blob_talloc(mem_ctx, NULL, HEADER_LEN + ap_rep_blob.length + enc_data_blob.length); if (reply->data == NULL) { goto done; } RSSVAL(reply->data, 0, reply->length); RSSVAL(reply->data, 2, 1); RSSVAL(reply->data, 4, ap_rep_blob.length); memcpy(reply->data + HEADER_LEN, ap_rep_blob.data, ap_rep_blob.length); memcpy(reply->data + HEADER_LEN + ap_rep_blob.length, enc_data_blob.data, enc_data_blob.length); rc = KDC_OK; done: talloc_free(tmp_ctx); return rc; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,815
linux
5ae94c0d2f0bed41d6718be743985d61b7f5c47d
static int irda_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; struct sockaddr_irda *addr = (struct sockaddr_irda *) uaddr; struct irda_sock *self = irda_sk(sk); int err; IRDA_DEBUG(2, "%s(%p)\n", __func__, self); lock_sock(sk); /* Don't allow connect for Ultra sockets */ err = -ESOCKTNOSUPPORT; if ((sk->sk_type == SOCK_DGRAM) && (sk->sk_protocol == IRDAPROTO_ULTRA)) goto out; if (sk->sk_state == TCP_ESTABLISHED && sock->state == SS_CONNECTING) { sock->state = SS_CONNECTED; err = 0; goto out; /* Connect completed during a ERESTARTSYS event */ } if (sk->sk_state == TCP_CLOSE && sock->state == SS_CONNECTING) { sock->state = SS_UNCONNECTED; err = -ECONNREFUSED; goto out; } err = -EISCONN; /* No reconnect on a seqpacket socket */ if (sk->sk_state == TCP_ESTABLISHED) goto out; sk->sk_state = TCP_CLOSE; sock->state = SS_UNCONNECTED; err = -EINVAL; if (addr_len != sizeof(struct sockaddr_irda)) goto out; /* Check if user supplied any destination device address */ if ((!addr->sir_addr) || (addr->sir_addr == DEV_ADDR_ANY)) { /* Try to find one suitable */ err = irda_discover_daddr_and_lsap_sel(self, addr->sir_name); if (err) { IRDA_DEBUG(0, "%s(), auto-connect failed!\n", __func__); goto out; } } else { /* Use the one provided by the user */ self->daddr = addr->sir_addr; IRDA_DEBUG(1, "%s(), daddr = %08x\n", __func__, self->daddr); /* If we don't have a valid service name, we assume the * user want to connect on a specific LSAP. Prevent * the use of invalid LSAPs (IrLMP 1.1 p10). Jean II */ if((addr->sir_name[0] != '\0') || (addr->sir_lsap_sel >= 0x70)) { /* Query remote LM-IAS using service name */ err = irda_find_lsap_sel(self, addr->sir_name); if (err) { IRDA_DEBUG(0, "%s(), connect failed!\n", __func__); goto out; } } else { /* Directly connect to the remote LSAP * specified by the sir_lsap field. * Please use with caution, in IrDA LSAPs are * dynamic and there is no "well-known" LSAP. */ self->dtsap_sel = addr->sir_lsap_sel; } } /* Check if we have opened a local TSAP */ if (!self->tsap) irda_open_tsap(self, LSAP_ANY, addr->sir_name); /* Move to connecting socket, start sending Connect Requests */ sock->state = SS_CONNECTING; sk->sk_state = TCP_SYN_SENT; /* Connect to remote device */ err = irttp_connect_request(self->tsap, self->dtsap_sel, self->saddr, self->daddr, NULL, self->max_sdu_size_rx, NULL); if (err) { IRDA_DEBUG(0, "%s(), connect failed!\n", __func__); goto out; } /* Now the loop */ err = -EINPROGRESS; if (sk->sk_state != TCP_ESTABLISHED && (flags & O_NONBLOCK)) goto out; err = -ERESTARTSYS; if (wait_event_interruptible(*(sk_sleep(sk)), (sk->sk_state != TCP_SYN_SENT))) goto out; if (sk->sk_state != TCP_ESTABLISHED) { sock->state = SS_UNCONNECTED; if (sk->sk_prot->disconnect(sk, flags)) sock->state = SS_DISCONNECTING; err = sock_error(sk); if (!err) err = -ECONNRESET; goto out; } sock->state = SS_CONNECTED; /* At this point, IrLMP has assigned our source address */ self->saddr = irttp_get_saddr(self->tsap); err = 0; out: release_sock(sk); return err; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,800
linux
93362fa47fe98b62e4a34ab408c4a418432e7939
static struct ctl_dir *get_subdir(struct ctl_dir *dir, const char *name, int namelen) { struct ctl_table_set *set = dir->header.set; struct ctl_dir *subdir, *new = NULL; int err; spin_lock(&sysctl_lock); subdir = find_subdir(dir, name, namelen); if (!IS_ERR(subdir)) goto found; if (PTR_ERR(subdir) != -ENOENT) goto failed; spin_unlock(&sysctl_lock); new = new_dir(set, name, namelen); spin_lock(&sysctl_lock); subdir = ERR_PTR(-ENOMEM); if (!new) goto failed; /* Was the subdir added while we dropped the lock? */ subdir = find_subdir(dir, name, namelen); if (!IS_ERR(subdir)) goto found; if (PTR_ERR(subdir) != -ENOENT) goto failed; /* Nope. Use the our freshly made directory entry. */ err = insert_header(dir, &new->header); subdir = ERR_PTR(err); if (err) goto failed; subdir = new; found: subdir->header.nreg++; failed: if (IS_ERR(subdir)) { pr_err("sysctl could not get directory: "); sysctl_print_dir(dir); pr_cont("/%*.*s %ld\n", namelen, namelen, name, PTR_ERR(subdir)); } drop_sysctl_table(&dir->header); if (new) drop_sysctl_table(&new->header); spin_unlock(&sysctl_lock); return subdir; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,946
libarchive
94821008d6eea81e315c5881cdf739202961040a
DEFINE_TEST(test_read_format_rar5_multiarchive_solid_skip_all) { const char* reffiles[] = { "test_read_format_rar5_multiarchive_solid.part01.rar", "test_read_format_rar5_multiarchive_solid.part02.rar", "test_read_format_rar5_multiarchive_solid.part03.rar", "test_read_format_rar5_multiarchive_solid.part04.rar", NULL }; PROLOGUE_MULTI(reffiles); assertA(0 == archive_read_next_header(a, &ae)); assertEqualString("cebula.txt", archive_entry_pathname(ae)); assertA(0 == archive_read_next_header(a, &ae)); assertEqualString("test.bin", archive_entry_pathname(ae)); assertA(0 == archive_read_next_header(a, &ae)); assertEqualString("test1.bin", archive_entry_pathname(ae)); assertA(0 == archive_read_next_header(a, &ae)); assertEqualString("test2.bin", archive_entry_pathname(ae)); assertA(0 == archive_read_next_header(a, &ae)); assertEqualString("test3.bin", archive_entry_pathname(ae)); assertA(0 == archive_read_next_header(a, &ae)); assertEqualString("test4.bin", archive_entry_pathname(ae)); assertA(0 == archive_read_next_header(a, &ae)); assertEqualString("test5.bin", archive_entry_pathname(ae)); assertA(0 == archive_read_next_header(a, &ae)); assertEqualString("test6.bin", archive_entry_pathname(ae)); assertA(0 == archive_read_next_header(a, &ae)); assertEqualString("elf-Linux-ARMv7-ls", archive_entry_pathname(ae)); assertA(ARCHIVE_EOF == archive_read_next_header(a, &ae)); EPILOGUE(); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,656
qpdf
701b518d5c56a1449825a3a37a716c58e05e1c3e
QPDF::resolve(int objid, int generation) { // Check object cache before checking xref table. This allows us // to insert things into the object cache that don't actually // exist in the file. QPDFObjGen og(objid, generation); if (this->resolving.count(og)) { // This can happen if an object references itself directly or // indirectly in some key that has to be resolved during // object parsing, such as stream length. QTC::TC("qpdf", "QPDF recursion loop in resolve"); warn(QPDFExc(qpdf_e_damaged_pdf, this->file->getName(), "", this->file->getLastOffset(), "loop detected resolving object " + QUtil::int_to_string(objid) + " " + QUtil::int_to_string(generation))); return new QPDF_Null; } ResolveRecorder rr(this, og); if (! this->obj_cache.count(og)) { if (! this->xref_table.count(og)) { // PDF spec says unknown objects resolve to the null object. return new QPDF_Null; } QPDFXRefEntry const& entry = this->xref_table[og]; switch (entry.getType()) { case 1: { qpdf_offset_t offset = entry.getOffset(); // Object stored in cache by readObjectAtOffset int aobjid; int ageneration; QPDFObjectHandle oh = readObjectAtOffset(true, offset, "", objid, generation, aobjid, ageneration); } break; case 2: resolveObjectsInStream(entry.getObjStreamNumber()); break; default: throw QPDFExc(qpdf_e_damaged_pdf, this->file->getName(), "", 0, "object " + QUtil::int_to_string(objid) + "/" + QUtil::int_to_string(generation) + " has unexpected xref entry type"); } } return this->obj_cache[og].object; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,089
Chrome
41cc463ecc5f0ba708a2c8282a7e7208ca7daa57
HeadlessDevToolsManagerDelegate::CreateTarget( content::DevToolsAgentHost* agent_host, int session_id, int command_id, const base::DictionaryValue* params) { std::string url; std::string browser_context_id; int width = browser_->options()->window_size.width(); int height = browser_->options()->window_size.height(); if (!params || !params->GetString("url", &url)) return CreateInvalidParamResponse(command_id, "url"); bool enable_begin_frame_control = false; params->GetString("browserContextId", &browser_context_id); params->GetInteger("width", &width); params->GetInteger("height", &height); params->GetBoolean("enableBeginFrameControl", &enable_begin_frame_control); #if defined(OS_MACOSX) if (enable_begin_frame_control) { return CreateErrorResponse( command_id, kErrorServerError, "BeginFrameControl is not supported on MacOS yet"); } #endif HeadlessBrowserContext* context = browser_->GetBrowserContextForId(browser_context_id); if (!browser_context_id.empty()) { context = browser_->GetBrowserContextForId(browser_context_id); if (!context) return CreateInvalidParamResponse(command_id, "browserContextId"); } else { context = browser_->GetDefaultBrowserContext(); if (!context) { return CreateErrorResponse(command_id, kErrorServerError, "You specified no |browserContextId|, but " "there is no default browser context set on " "HeadlessBrowser"); } } HeadlessWebContentsImpl* web_contents_impl = HeadlessWebContentsImpl::From( context->CreateWebContentsBuilder() .SetInitialURL(GURL(url)) .SetWindowSize(gfx::Size(width, height)) .SetEnableBeginFrameControl(enable_begin_frame_control) .Build()); std::unique_ptr<base::Value> result( target::CreateTargetResult::Builder() .SetTargetId(web_contents_impl->GetDevToolsAgentHostId()) .Build() ->Serialize()); return CreateSuccessResponse(command_id, std::move(result)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,967
Chrome
fd6a5115103b3e6a52ce15858c5ad4956df29300
void AudioNode::DidAddOutput(unsigned number_of_outputs) { connected_nodes_.push_back(nullptr); DCHECK_EQ(number_of_outputs, connected_nodes_.size()); connected_params_.push_back(nullptr); DCHECK_EQ(number_of_outputs, connected_params_.size()); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,831
ImageMagick
8187d2d8fd010d2d6b1a3a8edd935beec404dddc
static inline Quantum GetPixelChannel(const Image *magick_restrict image, const PixelChannel channel,const Quantum *magick_restrict pixel) { if (image->channel_map[channel].traits == UndefinedPixelTrait) return((Quantum) 0); return(pixel[image->channel_map[channel].offset]); }
1
CVE-2019-13299
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
5,515
ntopng
30610bda60cbfc058f90a1c0a17d0e8f4516221a
static void get_qsvar(const struct mg_request_info *request_info, const char *name, char *dst, size_t dst_len) { const char *qs = request_info->query_string; mg_get_var(qs, strlen(qs == NULL ? "" : qs), name, dst, dst_len); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,443
openjpeg
baf0c1ad4572daa89caa3b12985bdd93530f0dd7
static OPJ_BOOL bmp_read_info_header(FILE* IN, OPJ_BITMAPINFOHEADER* header) { memset(header, 0, sizeof(*header)); /* INFO HEADER */ /* ------------- */ header->biSize = (OPJ_UINT32)getc(IN); header->biSize |= (OPJ_UINT32)getc(IN) << 8; header->biSize |= (OPJ_UINT32)getc(IN) << 16; header->biSize |= (OPJ_UINT32)getc(IN) << 24; switch (header->biSize) { case 12U: /* BITMAPCOREHEADER */ case 40U: /* BITMAPINFOHEADER */ case 52U: /* BITMAPV2INFOHEADER */ case 56U: /* BITMAPV3INFOHEADER */ case 108U: /* BITMAPV4HEADER */ case 124U: /* BITMAPV5HEADER */ break; default: fprintf(stderr, "Error, unknown BMP header size %d\n", header->biSize); return OPJ_FALSE; } header->biWidth = (OPJ_UINT32)getc(IN); header->biWidth |= (OPJ_UINT32)getc(IN) << 8; header->biWidth |= (OPJ_UINT32)getc(IN) << 16; header->biWidth |= (OPJ_UINT32)getc(IN) << 24; header->biHeight = (OPJ_UINT32)getc(IN); header->biHeight |= (OPJ_UINT32)getc(IN) << 8; header->biHeight |= (OPJ_UINT32)getc(IN) << 16; header->biHeight |= (OPJ_UINT32)getc(IN) << 24; header->biPlanes = (OPJ_UINT16)getc(IN); header->biPlanes |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); header->biBitCount = (OPJ_UINT16)getc(IN); header->biBitCount |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); if (header->biBitCount == 0) { fprintf(stderr, "Error, invalid biBitCount %d\n", 0); return OPJ_FALSE; } if (header->biSize >= 40U) { header->biCompression = (OPJ_UINT32)getc(IN); header->biCompression |= (OPJ_UINT32)getc(IN) << 8; header->biCompression |= (OPJ_UINT32)getc(IN) << 16; header->biCompression |= (OPJ_UINT32)getc(IN) << 24; header->biSizeImage = (OPJ_UINT32)getc(IN); header->biSizeImage |= (OPJ_UINT32)getc(IN) << 8; header->biSizeImage |= (OPJ_UINT32)getc(IN) << 16; header->biSizeImage |= (OPJ_UINT32)getc(IN) << 24; header->biXpelsPerMeter = (OPJ_UINT32)getc(IN); header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8; header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16; header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24; header->biYpelsPerMeter = (OPJ_UINT32)getc(IN); header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8; header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16; header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24; header->biClrUsed = (OPJ_UINT32)getc(IN); header->biClrUsed |= (OPJ_UINT32)getc(IN) << 8; header->biClrUsed |= (OPJ_UINT32)getc(IN) << 16; header->biClrUsed |= (OPJ_UINT32)getc(IN) << 24; header->biClrImportant = (OPJ_UINT32)getc(IN); header->biClrImportant |= (OPJ_UINT32)getc(IN) << 8; header->biClrImportant |= (OPJ_UINT32)getc(IN) << 16; header->biClrImportant |= (OPJ_UINT32)getc(IN) << 24; } if (header->biSize >= 56U) { header->biRedMask = (OPJ_UINT32)getc(IN); header->biRedMask |= (OPJ_UINT32)getc(IN) << 8; header->biRedMask |= (OPJ_UINT32)getc(IN) << 16; header->biRedMask |= (OPJ_UINT32)getc(IN) << 24; header->biGreenMask = (OPJ_UINT32)getc(IN); header->biGreenMask |= (OPJ_UINT32)getc(IN) << 8; header->biGreenMask |= (OPJ_UINT32)getc(IN) << 16; header->biGreenMask |= (OPJ_UINT32)getc(IN) << 24; header->biBlueMask = (OPJ_UINT32)getc(IN); header->biBlueMask |= (OPJ_UINT32)getc(IN) << 8; header->biBlueMask |= (OPJ_UINT32)getc(IN) << 16; header->biBlueMask |= (OPJ_UINT32)getc(IN) << 24; header->biAlphaMask = (OPJ_UINT32)getc(IN); header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 8; header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 16; header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 24; } if (header->biSize >= 108U) { header->biColorSpaceType = (OPJ_UINT32)getc(IN); header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 8; header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 16; header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 24; if (fread(&(header->biColorSpaceEP), 1U, sizeof(header->biColorSpaceEP), IN) != sizeof(header->biColorSpaceEP)) { fprintf(stderr, "Error, can't read BMP header\n"); return OPJ_FALSE; } header->biRedGamma = (OPJ_UINT32)getc(IN); header->biRedGamma |= (OPJ_UINT32)getc(IN) << 8; header->biRedGamma |= (OPJ_UINT32)getc(IN) << 16; header->biRedGamma |= (OPJ_UINT32)getc(IN) << 24; header->biGreenGamma = (OPJ_UINT32)getc(IN); header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 8; header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 16; header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 24; header->biBlueGamma = (OPJ_UINT32)getc(IN); header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 8; header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 16; header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 24; } if (header->biSize >= 124U) { header->biIntent = (OPJ_UINT32)getc(IN); header->biIntent |= (OPJ_UINT32)getc(IN) << 8; header->biIntent |= (OPJ_UINT32)getc(IN) << 16; header->biIntent |= (OPJ_UINT32)getc(IN) << 24; header->biIccProfileData = (OPJ_UINT32)getc(IN); header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 8; header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 16; header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 24; header->biIccProfileSize = (OPJ_UINT32)getc(IN); header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 8; header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 16; header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 24; header->biReserved = (OPJ_UINT32)getc(IN); header->biReserved |= (OPJ_UINT32)getc(IN) << 8; header->biReserved |= (OPJ_UINT32)getc(IN) << 16; header->biReserved |= (OPJ_UINT32)getc(IN) << 24; } return OPJ_TRUE; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,672
libmspack
8759da8db6ec9e866cb8eb143313f397f925bb4f
static unsigned char *read_sys_file(struct mschm_decompressor_p *self, struct mschmd_file *file) { struct mspack_system *sys = self->system; unsigned char *data = NULL; int len; if (!file || !file->section || (file->section->id != 0)) { self->error = MSPACK_ERR_DATAFORMAT; return NULL; } len = (int) file->length; if (!(data = (unsigned char *) sys->alloc(sys, (size_t) len))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } if (sys->seek(self->d->infh, file->section->chm->sec0.offset + file->offset, MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; sys->free(data); return NULL; } if (sys->read(self->d->infh, data, len) != len) { self->error = MSPACK_ERR_READ; sys->free(data); return NULL; } return data; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,848
linux-2.6
59839dfff5eabca01cc4e20b45797a60a80af8cb
static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps) { int r = 0; memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state)); kvm_pit_load_count(kvm, 0, ps->channels[0].count); return r; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,380
jansson
64ce0ad3731ebd77e02897b07920eadd0e2cc318
static int lex_scan(lex_t *lex, json_error_t *error) { int c; strbuffer_clear(&lex->saved_text); if(lex->token == TOKEN_STRING) lex_free_string(lex); do c = lex_get(lex, error); while(c == ' ' || c == '\t' || c == '\n' || c == '\r'); if(c == STREAM_STATE_EOF) { lex->token = TOKEN_EOF; goto out; } if(c == STREAM_STATE_ERROR) { lex->token = TOKEN_INVALID; goto out; } lex_save(lex, c); if(c == '{' || c == '}' || c == '[' || c == ']' || c == ':' || c == ',') lex->token = c; else if(c == '"') lex_scan_string(lex, error); else if(l_isdigit(c) || c == '-') { if(lex_scan_number(lex, c, error)) goto out; } else if(l_isalpha(c)) { /* eat up the whole identifier for clearer error messages */ const char *saved_text; do c = lex_get_save(lex, error); while(l_isalpha(c)); lex_unget_unsave(lex, c); saved_text = strbuffer_value(&lex->saved_text); if(strcmp(saved_text, "true") == 0) lex->token = TOKEN_TRUE; else if(strcmp(saved_text, "false") == 0) lex->token = TOKEN_FALSE; else if(strcmp(saved_text, "null") == 0) lex->token = TOKEN_NULL; else lex->token = TOKEN_INVALID; } else { /* save the rest of the input UTF-8 sequence to get an error message of valid UTF-8 */ lex_save_cached(lex); lex->token = TOKEN_INVALID; } out: return lex->token; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,351
libjpeg-turbo
c30b1e72dac76343ef9029833d1561de07d29bad
static int fullTest(unsigned char *srcBuf, int w, int h, int subsamp, int jpegQual, char *fileName) { char tempStr[1024], tempStr2[80]; FILE *file = NULL; tjhandle handle = NULL; unsigned char **jpegBuf = NULL, *yuvBuf = NULL, *tmpBuf = NULL, *srcPtr, *srcPtr2; double start, elapsed, elapsedEncode; int totalJpegSize = 0, row, col, i, tilew = w, tileh = h, retval = 0; int iter; unsigned long *jpegSize = NULL, yuvSize = 0; int ps = tjPixelSize[pf]; int ntilesw = 1, ntilesh = 1, pitch = w * ps; const char *pfStr = pixFormatStr[pf]; if ((unsigned long long)pitch * (unsigned long long)h > (unsigned long long)((size_t)-1)) THROW("allocating temporary image buffer", "Image is too large"); if ((tmpBuf = (unsigned char *)malloc((size_t)pitch * h)) == NULL) THROW_UNIX("allocating temporary image buffer"); if (!quiet) printf(">>>>> %s (%s) <--> JPEG %s Q%d <<<<<\n", pfStr, (flags & TJFLAG_BOTTOMUP) ? "Bottom-up" : "Top-down", subNameLong[subsamp], jpegQual); for (tilew = doTile ? 8 : w, tileh = doTile ? 8 : h; ; tilew *= 2, tileh *= 2) { if (tilew > w) tilew = w; if (tileh > h) tileh = h; ntilesw = (w + tilew - 1) / tilew; ntilesh = (h + tileh - 1) / tileh; if ((jpegBuf = (unsigned char **)malloc(sizeof(unsigned char *) * ntilesw * ntilesh)) == NULL) THROW_UNIX("allocating JPEG tile array"); memset(jpegBuf, 0, sizeof(unsigned char *) * ntilesw * ntilesh); if ((jpegSize = (unsigned long *)malloc(sizeof(unsigned long) * ntilesw * ntilesh)) == NULL) THROW_UNIX("allocating JPEG size array"); memset(jpegSize, 0, sizeof(unsigned long) * ntilesw * ntilesh); if ((flags & TJFLAG_NOREALLOC) != 0) for (i = 0; i < ntilesw * ntilesh; i++) { if (tjBufSize(tilew, tileh, subsamp) > (unsigned long)INT_MAX) THROW("getting buffer size", "Image is too large"); if ((jpegBuf[i] = (unsigned char *) tjAlloc(tjBufSize(tilew, tileh, subsamp))) == NULL) THROW_UNIX("allocating JPEG tiles"); } /* Compression test */ if (quiet == 1) printf("%-4s (%s) %-5s %-3d ", pfStr, (flags & TJFLAG_BOTTOMUP) ? "BU" : "TD", subNameLong[subsamp], jpegQual); for (i = 0; i < h; i++) memcpy(&tmpBuf[pitch * i], &srcBuf[w * ps * i], w * ps); if ((handle = tjInitCompress()) == NULL) THROW_TJ("executing tjInitCompress()"); if (doYUV) { yuvSize = tjBufSizeYUV2(tilew, yuvPad, tileh, subsamp); if (yuvSize == (unsigned long)-1) THROW_TJ("allocating YUV buffer"); if ((yuvBuf = (unsigned char *)malloc(yuvSize)) == NULL) THROW_UNIX("allocating YUV buffer"); memset(yuvBuf, 127, yuvSize); } /* Benchmark */ iter = -1; elapsed = elapsedEncode = 0.; while (1) { int tile = 0; totalJpegSize = 0; start = getTime(); for (row = 0, srcPtr = srcBuf; row < ntilesh; row++, srcPtr += pitch * tileh) { for (col = 0, srcPtr2 = srcPtr; col < ntilesw; col++, tile++, srcPtr2 += ps * tilew) { int width = min(tilew, w - col * tilew); int height = min(tileh, h - row * tileh); if (doYUV) { double startEncode = getTime(); if (tjEncodeYUV3(handle, srcPtr2, width, pitch, height, pf, yuvBuf, yuvPad, subsamp, flags) == -1) THROW_TJ("executing tjEncodeYUV3()"); if (iter >= 0) elapsedEncode += getTime() - startEncode; if (tjCompressFromYUV(handle, yuvBuf, width, yuvPad, height, subsamp, &jpegBuf[tile], &jpegSize[tile], jpegQual, flags) == -1) THROW_TJ("executing tjCompressFromYUV()"); } else { if (tjCompress2(handle, srcPtr2, width, pitch, height, pf, &jpegBuf[tile], &jpegSize[tile], subsamp, jpegQual, flags) == -1) THROW_TJ("executing tjCompress2()"); } totalJpegSize += jpegSize[tile]; } } elapsed += getTime() - start; if (iter >= 0) { iter++; if (elapsed >= benchTime) break; } else if (elapsed >= warmup) { iter = 0; elapsed = elapsedEncode = 0.; } } if (doYUV) elapsed -= elapsedEncode; if (tjDestroy(handle) == -1) THROW_TJ("executing tjDestroy()"); handle = NULL; if (quiet == 1) printf("%-5d %-5d ", tilew, tileh); if (quiet) { if (doYUV) printf("%-6s%s", sigfig((double)(w * h) / 1000000. * (double)iter / elapsedEncode, 4, tempStr, 1024), quiet == 2 ? "\n" : " "); printf("%-6s%s", sigfig((double)(w * h) / 1000000. * (double)iter / elapsed, 4, tempStr, 1024), quiet == 2 ? "\n" : " "); printf("%-6s%s", sigfig((double)(w * h * ps) / (double)totalJpegSize, 4, tempStr2, 80), quiet == 2 ? "\n" : " "); } else { printf("\n%s size: %d x %d\n", doTile ? "Tile" : "Image", tilew, tileh); if (doYUV) { printf("Encode YUV --> Frame rate: %f fps\n", (double)iter / elapsedEncode); printf(" Output image size: %lu bytes\n", yuvSize); printf(" Compression ratio: %f:1\n", (double)(w * h * ps) / (double)yuvSize); printf(" Throughput: %f Megapixels/sec\n", (double)(w * h) / 1000000. * (double)iter / elapsedEncode); printf(" Output bit stream: %f Megabits/sec\n", (double)yuvSize * 8. / 1000000. * (double)iter / elapsedEncode); } printf("%s --> Frame rate: %f fps\n", doYUV ? "Comp from YUV" : "Compress ", (double)iter / elapsed); printf(" Output image size: %d bytes\n", totalJpegSize); printf(" Compression ratio: %f:1\n", (double)(w * h * ps) / (double)totalJpegSize); printf(" Throughput: %f Megapixels/sec\n", (double)(w * h) / 1000000. * (double)iter / elapsed); printf(" Output bit stream: %f Megabits/sec\n", (double)totalJpegSize * 8. / 1000000. * (double)iter / elapsed); } if (tilew == w && tileh == h && doWrite) { snprintf(tempStr, 1024, "%s_%s_Q%d.jpg", fileName, subName[subsamp], jpegQual); if ((file = fopen(tempStr, "wb")) == NULL) THROW_UNIX("opening reference image"); if (fwrite(jpegBuf[0], jpegSize[0], 1, file) != 1) THROW_UNIX("writing reference image"); fclose(file); file = NULL; if (!quiet) printf("Reference image written to %s\n", tempStr); } /* Decompression test */ if (!compOnly) { if (decomp(srcBuf, jpegBuf, jpegSize, tmpBuf, w, h, subsamp, jpegQual, fileName, tilew, tileh) == -1) goto bailout; } else if (quiet == 1) printf("N/A\n"); for (i = 0; i < ntilesw * ntilesh; i++) { if (jpegBuf[i]) tjFree(jpegBuf[i]); jpegBuf[i] = NULL; } free(jpegBuf); jpegBuf = NULL; free(jpegSize); jpegSize = NULL; if (doYUV) { free(yuvBuf); yuvBuf = NULL; } if (tilew == w && tileh == h) break; } bailout: if (file) { fclose(file); file = NULL; } if (jpegBuf) { for (i = 0; i < ntilesw * ntilesh; i++) { if (jpegBuf[i]) tjFree(jpegBuf[i]); jpegBuf[i] = NULL; } free(jpegBuf); jpegBuf = NULL; } if (yuvBuf) { free(yuvBuf); yuvBuf = NULL; } if (jpegSize) { free(jpegSize); jpegSize = NULL; } if (tmpBuf) { free(tmpBuf); tmpBuf = NULL; } if (handle) { tjDestroy(handle); handle = NULL; } return retval; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,060
linux
635682a14427d241bab7bbdeebb48a7d7b91638e
static void sctp_generate_timeout_event(struct sctp_association *asoc, sctp_event_timeout_t timeout_type) { struct net *net = sock_net(asoc->base.sk); int error = 0; bh_lock_sock(asoc->base.sk); if (sock_owned_by_user(asoc->base.sk)) { pr_debug("%s: sock is busy: timer %d\n", __func__, timeout_type); /* Try again later. */ if (!mod_timer(&asoc->timers[timeout_type], jiffies + (HZ/20))) sctp_association_hold(asoc); goto out_unlock; } /* Is this association really dead and just waiting around for * the timer to let go of the reference? */ if (asoc->base.dead) goto out_unlock; /* Run through the state machine. */ error = sctp_do_sm(net, SCTP_EVENT_T_TIMEOUT, SCTP_ST_TIMEOUT(timeout_type), asoc->state, asoc->ep, asoc, (void *)timeout_type, GFP_ATOMIC); if (error) asoc->base.sk->sk_err = -error; out_unlock: bh_unlock_sock(asoc->base.sk); sctp_association_put(asoc); }
1
CVE-2015-8767
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
821
Chrome
7cde8513c12a6e8ec5d1d1eb1cfd078d9adad3ef
base::string16 PageInfoUI::PermissionTypeToUIString(ContentSettingsType type) { for (const PermissionsUIInfo& info : GetContentSettingsUIInfo()) { if (info.type == type) return l10n_util::GetStringUTF16(info.string_id); } NOTREACHED(); return base::string16(); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,496
php
c351b47ce85a3a147cfa801fa9f0149ab4160834
static void pcre_handle_exec_error(int pcre_code TSRMLS_DC) /* {{{ */ { int preg_code = 0; switch (pcre_code) { case PCRE_ERROR_MATCHLIMIT: preg_code = PHP_PCRE_BACKTRACK_LIMIT_ERROR; break; case PCRE_ERROR_RECURSIONLIMIT: preg_code = PHP_PCRE_RECURSION_LIMIT_ERROR; break; case PCRE_ERROR_BADUTF8: preg_code = PHP_PCRE_BAD_UTF8_ERROR; break; case PCRE_ERROR_BADUTF8_OFFSET: preg_code = PHP_PCRE_BAD_UTF8_OFFSET_ERROR; break; default: preg_code = PHP_PCRE_INTERNAL_ERROR; break; } PCRE_G(error_code) = preg_code; } /* }}} */
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,513
Chrome
ff4330a2ca6bf69d24f9f9fb6f12dc81387b205a
explicit ScopedTargetContentsOwner(browser::NavigateParams* params) : params_(params) { }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,779
Chrome
b15c87071f906301bccc824ce013966ca93998c7
WorkerProcessLauncher::Core::Core( scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner, scoped_ptr<WorkerProcessLauncher::Delegate> launcher_delegate, WorkerProcessIpcDelegate* worker_delegate) : caller_task_runner_(caller_task_runner), launcher_delegate_(launcher_delegate.Pass()), worker_delegate_(worker_delegate), ipc_enabled_(false), launch_backoff_(&kDefaultBackoffPolicy), stopping_(false) { DCHECK(caller_task_runner_->BelongsToCurrentThread()); ipc_error_timer_.reset(new base::OneShotTimer<Core>()); launch_success_timer_.reset(new base::OneShotTimer<Core>()); launch_timer_.reset(new base::OneShotTimer<Core>()); }
1
CVE-2012-5156
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
179
qemu
8f4754ede56e3f9ea3fd7207f4a7c4453e59285b
void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify) { notifier_list_add(&bs->close_notifiers, notify); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,832
oniguruma
6eb4aca6a7f2f60f473580576d86686ed6a6ebec
st_insert_callout_name_table(hash_table_type* table, OnigEncoding enc, int type, UChar* str_key, UChar* end_key, hash_data_type value) { st_callout_name_key* key; int result; key = (st_callout_name_key* )xmalloc(sizeof(st_callout_name_key)); CHECK_NULL_RETURN_MEMERR(key); /* key->s: don't duplicate, because str_key is duped in callout_name_entry() */ key->enc = enc; key->type = type; key->s = str_key; key->end = end_key; result = onig_st_insert(table, (st_data_t )key, value); if (result) { xfree(key); } return result; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,549
libdwarf-code
8151575a6ace77d005ca5bb5d71c1bfdba3f7069
dwarf_get_cu_die_offset_given_cu_header_offset_b(Dwarf_Debug dbg, Dwarf_Off in_cu_header_offset, Dwarf_Bool is_info, Dwarf_Off * out_cu_die_offset, Dwarf_Error * error) { Dwarf_Off headerlen = 0; int cres = 0; if (!dbg || dbg->de_magic != DBG_IS_VALID) { _dwarf_error_string(NULL, error, DW_DLE_DBG_NULL, "DW_DLE_DBG_NULL: " "calling dwarf_get_cu_die_offset_given" "cu_header_offset_b Dwarf_Debug is" "either null or it is" "a stale Dwarf_Debug pointer"); return DW_DLV_ERROR; } cres = _dwarf_length_of_cu_header(dbg, in_cu_header_offset,is_info, &headerlen,error); if (cres != DW_DLV_OK) { return cres; } *out_cu_die_offset = in_cu_header_offset + headerlen; return DW_DLV_OK; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,175
tensorflow
a74768f8e4efbda4def9f16ee7e13cf3922ac5f7
static void SpatialMaxPoolWithArgMaxHelper( OpKernelContext* context, Tensor* output, Tensor* output_arg_max, Tensor* input_backprop, const Tensor& tensor_in, const Tensor& out_backprop, const PoolParameters& params, const bool include_batch_in_index) { if (input_backprop != nullptr) { OP_REQUIRES( context, include_batch_in_index, errors::Internal( "SpatialMaxPoolWithArgMaxHelper requires include_batch_in_index " "to be True when input_backprop != nullptr")); OP_REQUIRES( context, (std::is_same<Targmax, int64>::value), errors::Internal("SpatialMaxPoolWithArgMaxHelper requires Targmax " "to be int64 when input_backprop != nullptr")); } typedef Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>> ConstEigenMatrixMap; typedef Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>> EigenMatrixMap; typedef Eigen::Map<Eigen::Matrix<Targmax, Eigen::Dynamic, Eigen::Dynamic>> EigenIndexMatrixMap; ConstEigenMatrixMap in_mat( tensor_in.flat<T>().data(), params.depth, params.tensor_in_cols * params.tensor_in_rows * params.tensor_in_batch); EigenMatrixMap out_mat( output->flat<T>().data(), params.depth, params.out_width * params.out_height * params.tensor_in_batch); EigenIndexMatrixMap out_arg_max_mat( output_arg_max->flat<Targmax>().data(), params.depth, params.out_width * params.out_height * params.tensor_in_batch); const DeviceBase::CpuWorkerThreads& worker_threads = *(context->device()->tensorflow_cpu_worker_threads()); // The following code basically does the following: // 1. Flattens the input and output tensors into two dimensional arrays. // tensor_in_as_matrix: // depth by (tensor_in_cols * tensor_in_rows * tensor_in_batch) // output_as_matrix: // depth by (out_width * out_height * tensor_in_batch) // // 2. Walks through the set of columns in the flattened tensor_in_as_matrix, // and updates the corresponding column(s) in output_as_matrix with the // max value. auto shard = [&params, &in_mat, &out_mat, &out_arg_max_mat, &input_backprop, &output_arg_max, &out_backprop, include_batch_in_index](int64 start, int64 limit) { const int32 depth = params.depth; const int32 in_rows = params.tensor_in_rows; const int32 in_cols = params.tensor_in_cols; const int32 pad_top = params.pad_top; const int32 pad_left = params.pad_left; const int32 window_rows = params.window_rows; const int32 window_cols = params.window_cols; const int32 row_stride = params.row_stride; const int32 col_stride = params.col_stride; const int32 out_height = params.out_height; const int32 out_width = params.out_width; { // Initializes the output tensor with MIN<T>. const int32 output_image_size = out_height * out_width * depth; EigenMatrixMap out_shard(out_mat.data() + start * output_image_size, 1, (limit - start) * output_image_size); out_shard.setConstant(Eigen::NumTraits<T>::lowest()); EigenIndexMatrixMap out_arg_max_shard( out_arg_max_mat.data() + start * output_image_size, 1, (limit - start) * output_image_size); out_arg_max_shard.setConstant(kInvalidMaxPoolingIndex); } for (int64 b = start; b < limit; ++b) { for (int h = 0; h < in_rows; ++h) { for (int w = 0; w < in_cols; ++w) { // (h_start, h_end) * (w_start, w_end) is the range that the input // vector projects to. const int hpad = h + pad_top; const int wpad = w + pad_left; const int h_start = (hpad < window_rows) ? 0 : (hpad - window_rows) / row_stride + 1; const int h_end = std::min(hpad / row_stride + 1, out_height); const int w_start = (wpad < window_cols) ? 0 : (wpad - window_cols) / col_stride + 1; const int w_end = std::min(wpad / col_stride + 1, out_width); // compute elementwise max const int64 in_index = (b * in_rows + h) * in_cols + w; for (int ph = h_start; ph < h_end; ++ph) { const int64 out_index_base = (b * out_height + ph) * out_width; for (int pw = w_start; pw < w_end; ++pw) { const int64 out_index = out_index_base + pw; /// NOTES(zhengxq): not using the eigen matrix operation for /// now. for (int d = 0; d < depth; ++d) { const T& input_ref = in_mat.coeffRef(d, in_index); T& output_ref = out_mat.coeffRef(d, out_index); Targmax& out_arg_max_ref = out_arg_max_mat.coeffRef(d, out_index); if (output_ref < input_ref || out_arg_max_ref == kInvalidMaxPoolingIndex) { output_ref = input_ref; if (include_batch_in_index) { out_arg_max_ref = in_index * depth + d; } else { out_arg_max_ref = (h * in_cols + w) * depth + d; } } } } } } } } if (input_backprop != nullptr) { auto input_backprop_flat = input_backprop->flat<T>(); auto out_arg_max_flat = output_arg_max->flat<int64>(); auto out_backprop_flat = out_backprop.flat<T>(); // Initialize output to 0. const int64 in_size = in_rows * in_cols * depth; const int64 in_start = start * in_size; const int64 in_end = limit * in_size; EigenMatrixMap in_shard(input_backprop_flat.data() + in_start, 1, in_end - in_start); in_shard.setConstant(T(0)); // Backpropagate. const int out_size = out_height * out_width * depth; const int out_start = start * out_size; const int out_end = limit * out_size; for (int index = out_start; index < out_end; ++index) { int input_backprop_index = out_arg_max_flat(index); // Although this check is in the inner loop, it is worth its value // so we don't end up with memory corruptions. Our benchmark shows that // the performance impact is quite small // CHECK(input_backprop_index >= in_start && input_backprop_index < // in_end) FastBoundsCheck(input_backprop_index - in_start, in_end - in_start); input_backprop_flat(input_backprop_index) += out_backprop_flat(index); } } }; const int64 shard_cost = params.tensor_in_rows * params.tensor_in_cols * params.depth * params.window_rows * params.window_cols; Shard(worker_threads.num_threads, worker_threads.workers, params.tensor_in_batch, shard_cost, shard); }
1
CVE-2021-29579
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
5,856
FFmpeg
b0a8b40294ea212c1938348ff112ef1b9bf16bb3
static int b44_uncompress(EXRContext *s, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { const int8_t *sr = src; int stay_to_uncompress = compressed_size; int nb_b44_block_w, nb_b44_block_h; int index_tl_x, index_tl_y, index_out, index_tmp; uint16_t tmp_buffer[16]; /* B44 use 4x4 half float pixel */ int c, iY, iX, y, x; int target_channel_offset = 0; /* calc B44 block count */ nb_b44_block_w = td->xsize / 4; if ((td->xsize % 4) != 0) nb_b44_block_w++; nb_b44_block_h = td->ysize / 4; if ((td->ysize % 4) != 0) nb_b44_block_h++; for (c = 0; c < s->nb_channels; c++) { if (s->channels[c].pixel_type == EXR_HALF) {/* B44 only compress half float data */ for (iY = 0; iY < nb_b44_block_h; iY++) { for (iX = 0; iX < nb_b44_block_w; iX++) {/* For each B44 block */ if (stay_to_uncompress < 3) { av_log(s, AV_LOG_ERROR, "Not enough data for B44A block: %d", stay_to_uncompress); return AVERROR_INVALIDDATA; } if (src[compressed_size - stay_to_uncompress + 2] == 0xfc) { /* B44A block */ unpack_3(sr, tmp_buffer); sr += 3; stay_to_uncompress -= 3; } else {/* B44 Block */ if (stay_to_uncompress < 14) { av_log(s, AV_LOG_ERROR, "Not enough data for B44 block: %d", stay_to_uncompress); return AVERROR_INVALIDDATA; } unpack_14(sr, tmp_buffer); sr += 14; stay_to_uncompress -= 14; } /* copy data to uncompress buffer (B44 block can exceed target resolution)*/ index_tl_x = iX * 4; index_tl_y = iY * 4; for (y = index_tl_y; y < FFMIN(index_tl_y + 4, td->ysize); y++) { for (x = index_tl_x; x < FFMIN(index_tl_x + 4, td->xsize); x++) { index_out = target_channel_offset * td->xsize + y * td->channel_line_size + 2 * x; index_tmp = (y-index_tl_y) * 4 + (x-index_tl_x); td->uncompressed_data[index_out] = tmp_buffer[index_tmp] & 0xff; td->uncompressed_data[index_out + 1] = tmp_buffer[index_tmp] >> 8; } } } } target_channel_offset += 2; } else {/* Float or UINT 32 channel */ if (stay_to_uncompress < td->ysize * td->xsize * 4) { av_log(s, AV_LOG_ERROR, "Not enough data for uncompress channel: %d", stay_to_uncompress); return AVERROR_INVALIDDATA; } for (y = 0; y < td->ysize; y++) { index_out = target_channel_offset * td->xsize + y * td->channel_line_size; memcpy(&td->uncompressed_data[index_out], sr, td->xsize * 4); sr += td->xsize * 4; } target_channel_offset += 4; stay_to_uncompress -= td->ysize * td->xsize * 4; } } return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,152
gdk-pixbuf
f8569bb13e2aa1584dde61ca545144750f7a7c98
gif_init (GifContext *context) { unsigned char buf[16]; char version[4]; if (!gif_read (context, buf, 6)) { /* Unable to read magic number, * gif_read() should have set error */ return -1; } if (strncmp ((char *) buf, "GIF", 3) != 0) { /* Not a GIF file */ g_set_error_literal (context->error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, _("File does not appear to be a GIF file")); return -2; } strncpy (version, (char *) buf + 3, 3); version[3] = '\0'; if ((strcmp (version, "87a") != 0) && (strcmp (version, "89a") != 0)) { /* bad version number, not '87a' or '89a' */ g_set_error (context->error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, _("Version %s of the GIF file format is not supported"), version); return -2; } /* read the screen descriptor */ if (!gif_read (context, buf, 7)) { /* Failed to read screen descriptor, error set */ return -1; } context->width = LM_to_uint (buf[0], buf[1]); context->height = LM_to_uint (buf[2], buf[3]); /* The 4th byte is * high bit: whether to use the background index * next 3: color resolution * next: whether colormap is sorted by priority of allocation * last 3: size of colormap */ context->global_bit_pixel = 2 << (buf[4] & 0x07); context->global_color_resolution = (((buf[4] & 0x70) >> 3) + 1); context->has_global_cmap = (buf[4] & 0x80) != 0; context->background_index = buf[5]; context->aspect_ratio = buf[6]; /* Use background of transparent black as default, though if * one isn't set explicitly no one should ever use it. */ context->animation->bg_red = 0; context->animation->bg_green = 0; context->animation->bg_blue = 0; context->animation->width = context->width; context->animation->height = context->height; if (context->has_global_cmap) { gif_set_get_colormap (context); } else { context->state = GIF_GET_NEXT_STEP; } #ifdef DUMP_IMAGE_DETAILS g_print (">Image width: %d height: %d global_cmap: %d background: %d\n", context->width, context->height, context->has_global_cmap, context->background_index); #endif return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,380
tcpdump
061e7371a944588f231cb1b66d6fb070b646e376
ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; }
1
CVE-2017-13689
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,543
server
5ba77222e9fe7af8ff403816b5338b18b342053c
free_tmp_table(THD *thd, TABLE *entry) { MEM_ROOT own_root= entry->mem_root; const char *save_proc_info; DBUG_ENTER("free_tmp_table"); DBUG_PRINT("enter",("table: %s alias: %s",entry->s->table_name.str, entry->alias.c_ptr())); save_proc_info=thd->proc_info; THD_STAGE_INFO(thd, stage_removing_tmp_table); if (entry->file && entry->is_created()) { entry->file->ha_index_or_rnd_end(); if (entry->db_stat) entry->file->ha_drop_table(entry->s->path.str); else entry->file->ha_delete_table(entry->s->path.str); delete entry->file; } /* free blobs */ for (Field **ptr=entry->field ; *ptr ; ptr++) (*ptr)->free(); if (entry->temp_pool_slot != MY_BIT_NONE) bitmap_lock_clear_bit(&temp_pool, entry->temp_pool_slot); plugin_unlock(0, entry->s->db_plugin); entry->alias.free(); free_root(&own_root, MYF(0)); /* the table is allocated in its own root */ thd_proc_info(thd, save_proc_info); DBUG_VOID_RETURN; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,409
linux
338f977f4eb441e69bb9a46eaa0ac715c931a67f
ieee80211_tx_h_dynamic_ps(struct ieee80211_tx_data *tx) { struct ieee80211_local *local = tx->local; struct ieee80211_if_managed *ifmgd; /* driver doesn't support power save */ if (!(local->hw.flags & IEEE80211_HW_SUPPORTS_PS)) return TX_CONTINUE; /* hardware does dynamic power save */ if (local->hw.flags & IEEE80211_HW_SUPPORTS_DYNAMIC_PS) return TX_CONTINUE; /* dynamic power save disabled */ if (local->hw.conf.dynamic_ps_timeout <= 0) return TX_CONTINUE; /* we are scanning, don't enable power save */ if (local->scanning) return TX_CONTINUE; if (!local->ps_sdata) return TX_CONTINUE; /* No point if we're going to suspend */ if (local->quiescing) return TX_CONTINUE; /* dynamic ps is supported only in managed mode */ if (tx->sdata->vif.type != NL80211_IFTYPE_STATION) return TX_CONTINUE; ifmgd = &tx->sdata->u.mgd; /* * Don't wakeup from power save if u-apsd is enabled, voip ac has * u-apsd enabled and the frame is in voip class. This effectively * means that even if all access categories have u-apsd enabled, in * practise u-apsd is only used with the voip ac. This is a * workaround for the case when received voip class packets do not * have correct qos tag for some reason, due the network or the * peer application. * * Note: ifmgd->uapsd_queues access is racy here. If the value is * changed via debugfs, user needs to reassociate manually to have * everything in sync. */ if ((ifmgd->flags & IEEE80211_STA_UAPSD_ENABLED) && (ifmgd->uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_VO) && skb_get_queue_mapping(tx->skb) == IEEE80211_AC_VO) return TX_CONTINUE; if (local->hw.conf.flags & IEEE80211_CONF_PS) { ieee80211_stop_queues_by_reason(&local->hw, IEEE80211_MAX_QUEUE_MAP, IEEE80211_QUEUE_STOP_REASON_PS); ifmgd->flags &= ~IEEE80211_STA_NULLFUNC_ACKED; ieee80211_queue_work(&local->hw, &local->dynamic_ps_disable_work); } /* Don't restart the timer if we're not disassociated */ if (!ifmgd->associated) return TX_CONTINUE; mod_timer(&local->dynamic_ps_timer, jiffies + msecs_to_jiffies(local->hw.conf.dynamic_ps_timeout)); return TX_CONTINUE; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,680
Chrome
01e4ee2fda0a5e57a8d0c8cb829022eb84fdff12
PassRefPtr<StylePropertySet> CSSComputedStyleDeclaration::copy() const { return copyPropertiesInSet(computedProperties, numComputedProperties); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,972
php
188c196d4da60bdde9190d2fc532650d17f7af2d
xmlNodePtr get_node_ex(xmlNodePtr node, char *name, char *ns) { while (node!=NULL) { if (node_is_equal_ex(node, name, ns)) { return node; } node = node->next; } return NULL; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,568
gpac
dae9900580a8888969481cd72035408091edb11b
GF_Err gf_isom_write_compressed_box(GF_ISOFile *mov, GF_Box *root_box, u32 repl_type, GF_BitStream *bs, u32 *box_csize) { #ifdef GPAC_DISABLE_ZLIB return GF_NOT_SUPPORTED; #else GF_Err e; GF_BitStream *comp_bs = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE); e = gf_isom_box_write(root_box, comp_bs); if (!e) { u8 *box_data; u32 box_size, comp_size; if (box_csize) *box_csize = (u32) root_box->size; gf_bs_get_content(comp_bs, &box_data, &box_size); gf_gz_compress_payload_ex(&box_data, box_size, &comp_size, 8, GF_TRUE, NULL); if (mov->force_compress || (comp_size + COMP_BOX_COST_BYTES < box_size)) { if (bs) { gf_bs_write_u32(bs, comp_size+8); gf_bs_write_u32(bs, repl_type); gf_bs_write_data(bs, box_data, comp_size); } if (box_csize) *box_csize = comp_size + COMP_BOX_COST_BYTES; } else if (bs) { gf_bs_write_data(bs, box_data, box_size); } gf_free(box_data); } gf_bs_del(comp_bs); return e; #endif /*GPAC_DISABLE_ZLIB*/ }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
20,509
Chrome
b9866ebc631655c593a2ac60a3c7cf7d217ccf5d
void AudioOutputController::EnqueueData(const uint8* data, uint32 size) { AutoLock auto_lock(lock_); pending_request_ = false; if (size) { buffer_.Append(data, size); SubmitOnMoreData_Locked(); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,833
ceph
ba0790a01ba5252db1ebc299db6e12cd758d0ff9
int RGWCopyObj_ObjStore_S3::get_params() { if_mod = s->info.env->get("HTTP_X_AMZ_COPY_IF_MODIFIED_SINCE"); if_unmod = s->info.env->get("HTTP_X_AMZ_COPY_IF_UNMODIFIED_SINCE"); if_match = s->info.env->get("HTTP_X_AMZ_COPY_IF_MATCH"); if_nomatch = s->info.env->get("HTTP_X_AMZ_COPY_IF_NONE_MATCH"); src_tenant_name = s->src_tenant_name; src_bucket_name = s->src_bucket_name; src_object = s->src_object; dest_tenant_name = s->bucket.tenant; dest_bucket_name = s->bucket.name; dest_object = s->object.name; if (s->system_request) { source_zone = s->info.args.get(RGW_SYS_PARAM_PREFIX "source-zone"); s->info.args.get_bool(RGW_SYS_PARAM_PREFIX "copy-if-newer", &copy_if_newer, false); if (!source_zone.empty()) { client_id = s->info.args.get(RGW_SYS_PARAM_PREFIX "client-id"); op_id = s->info.args.get(RGW_SYS_PARAM_PREFIX "op-id"); if (client_id.empty() || op_id.empty()) { ldout(s->cct, 0) << RGW_SYS_PARAM_PREFIX "client-id or " RGW_SYS_PARAM_PREFIX "op-id were not provided, " "required for intra-region copy" << dendl; return -EINVAL; } } } copy_source = s->info.env->get("HTTP_X_AMZ_COPY_SOURCE"); auto tmp_md_d = s->info.env->get("HTTP_X_AMZ_METADATA_DIRECTIVE"); if (tmp_md_d) { if (strcasecmp(tmp_md_d, "COPY") == 0) { attrs_mod = RGWRados::ATTRSMOD_NONE; } else if (strcasecmp(tmp_md_d, "REPLACE") == 0) { attrs_mod = RGWRados::ATTRSMOD_REPLACE; } else if (!source_zone.empty()) { attrs_mod = RGWRados::ATTRSMOD_NONE; // default for intra-zone_group copy } else { s->err.message = "Unknown metadata directive."; ldout(s->cct, 0) << s->err.message << dendl; return -EINVAL; } md_directive = tmp_md_d; } if (source_zone.empty() && (dest_tenant_name.compare(src_tenant_name) == 0) && (dest_bucket_name.compare(src_bucket_name) == 0) && (dest_object.compare(src_object.name) == 0) && src_object.instance.empty() && (attrs_mod != RGWRados::ATTRSMOD_REPLACE)) { /* can only copy object into itself if replacing attrs */ s->err.message = "This copy request is illegal because it is trying to copy " "an object to itself without changing the object's metadata, " "storage class, website redirect location or encryption attributes."; ldout(s->cct, 0) << s->err.message << dendl; return -ERR_INVALID_REQUEST; } return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,273
PDFGen
ee58aff6918b8bbc3be29b9e3089485ea46ff956
static const uint16_t *find_font_widths(const char *font_name) { if (strcmp(font_name, "Helvetica") == 0) return helvetica_widths; if (strcmp(font_name, "Helvetica-Bold") == 0) return helvetica_bold_widths; if (strcmp(font_name, "Helvetica-BoldOblique") == 0) return helvetica_bold_oblique_widths; if (strcmp(font_name, "Helvetica-Oblique") == 0) return helvetica_oblique_widths; if (strcmp(font_name, "Courier") == 0 || strcmp(font_name, "Courier-Bold") == 0 || strcmp(font_name, "Courier-BoldOblique") == 0 || strcmp(font_name, "Courier-Oblique") == 0) return courier_widths; if (strcmp(font_name, "Times-Roman") == 0) return times_widths; if (strcmp(font_name, "Times-Bold") == 0) return times_bold_widths; if (strcmp(font_name, "Times-Italic") == 0) return times_italic_widths; if (strcmp(font_name, "Times-BoldItalic") == 0) return times_bold_italic_widths; if (strcmp(font_name, "Symbol") == 0) return symbol_widths; if (strcmp(font_name, "ZapfDingbats") == 0) return zapfdingbats_widths; return NULL; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,996
Chrome
04aaacb936a08d70862d6d9d7e8354721ae46be8
void SetupMockGroup() { std::unique_ptr<net::HttpResponseInfo> info(MakeMockResponseInfo()); const int kMockInfoSize = GetResponseInfoSize(info.get()); scoped_refptr<AppCacheGroup> group( new AppCacheGroup(service_->storage(), kManifestUrl, kMockGroupId)); scoped_refptr<AppCache> cache( new AppCache(service_->storage(), kMockCacheId)); cache->AddEntry( kManifestUrl, AppCacheEntry(AppCacheEntry::MANIFEST, kMockResponseId, kMockInfoSize + kMockBodySize)); cache->set_complete(true); group->AddCache(cache.get()); mock_storage()->AddStoredGroup(group.get()); mock_storage()->AddStoredCache(cache.get()); }
1
CVE-2019-5837
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
Phase: Architecture and Design Strategy: Separation of Privilege Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area. Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges.
3,160
libtiff
3ca657a8793dd011bf869695d72ad31c779c3cc1
horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32* wp = (uint32*) cp0; tmsize_t wc = cc / 4; assert((cc%(4*stride))==0); if (wc > stride) { wc -= stride; do { REPEAT4(stride, wp[stride] += wp[0]; wp++) wc -= stride; } while (wc > 0); } }
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).
7,577
Android
04839626ed859623901ebd3a5fd483982186b59d
const SeekHead::Entry* SeekHead::GetEntry(int idx) const { if (idx < 0) return 0; if (idx >= m_entry_count) return 0; return m_entries + idx; }
1
CVE-2016-1621
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
5,673
Chrome
3475f5e448ddf5e48888f3d0563245cc46e3c98b
bool LauncherView::IsShowingMenu() const { #if !defined(OS_MACOSX) return (overflow_menu_runner_.get() && overflow_menu_runner_->IsRunning()) || (launcher_menu_runner_.get() && launcher_menu_runner_->IsRunning()); #endif return false; }
1
CVE-2012-2895
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
4,045
Chrome
1dab554a7e795dac34313e2f7dbe4325628d12d4
SessionRestoreImpl(Profile* profile, Browser* browser, bool synchronous, bool clobber_existing_tab, bool always_create_tabbed_browser, const std::vector<GURL>& urls_to_open) : profile_(profile), browser_(browser), synchronous_(synchronous), clobber_existing_tab_(clobber_existing_tab), always_create_tabbed_browser_(always_create_tabbed_browser), urls_to_open_(urls_to_open), restore_started_(base::TimeTicks::Now()), browser_shown_(false) { if (profiles_getting_restored == NULL) profiles_getting_restored = new std::set<const Profile*>(); CHECK(profiles_getting_restored->find(profile) == profiles_getting_restored->end()); profiles_getting_restored->insert(profile); g_browser_process->AddRefModule(); }
1
CVE-2011-3088
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,994
Pillow
5bdf54b5a76b54fb00bd05f2d733e0a4173eefc9
ImagingPcdDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) { int x; int chunk; UINT8* out; UINT8* ptr; ptr = buf; chunk = 3 * state->xsize; for (;;) { /* We need data for two full lines before we can do anything */ if (bytes < chunk) return ptr - buf; /* Unpack first line */ out = state->buffer; for (x = 0; x < state->xsize; x++) { out[0] = ptr[x]; out[1] = ptr[(x+4*state->xsize)/2]; out[2] = ptr[(x+5*state->xsize)/2]; out += 3; } state->shuffle((UINT8*) im->image[state->y], state->buffer, state->xsize); if (++state->y >= state->ysize) return -1; /* This can hardly happen */ /* Unpack second line */ out = state->buffer; for (x = 0; x < state->xsize; x++) { out[0] = ptr[x+state->xsize]; out[1] = ptr[(x+4*state->xsize)/2]; out[2] = ptr[(x+5*state->xsize)/2]; out += 3; } state->shuffle((UINT8*) im->image[state->y], state->buffer, state->xsize); if (++state->y >= state->ysize) return -1; ptr += chunk; bytes -= chunk; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,730
linux
0b760113a3a155269a3fba93a409c640031dd68f
static inline void rpc_set_waitqueue_owner(struct rpc_wait_queue *queue, pid_t pid) { queue->owner = pid; queue->nr = RPC_BATCH_COUNT; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,923
linux
1a51410abe7d0ee4b1d112780f46df87d3621043
static void fill_stats(struct task_struct *tsk, struct taskstats *stats) { memset(stats, 0, sizeof(*stats)); /* * Each accounting subsystem adds calls to its functions to * fill in relevant parts of struct taskstsats as follows * * per-task-foo(stats, tsk); */ delayacct_add_tsk(stats, tsk); /* fill in basic acct fields */ stats->version = TASKSTATS_VERSION; stats->nvcsw = tsk->nvcsw; stats->nivcsw = tsk->nivcsw; bacct_add_tsk(stats, tsk); /* fill in extended acct fields */ xacct_add_tsk(stats, tsk); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,179
linux
84ac7260236a49c79eede91617700174c2c19b0c
packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct packet_sock *po = pkt_sk(sk); int ret; if (level != SOL_PACKET) return -ENOPROTOOPT; switch (optname) { case PACKET_ADD_MEMBERSHIP: case PACKET_DROP_MEMBERSHIP: { struct packet_mreq_max mreq; int len = optlen; memset(&mreq, 0, sizeof(mreq)); if (len < sizeof(struct packet_mreq)) return -EINVAL; if (len > sizeof(mreq)) len = sizeof(mreq); if (copy_from_user(&mreq, optval, len)) return -EFAULT; if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address))) return -EINVAL; if (optname == PACKET_ADD_MEMBERSHIP) ret = packet_mc_add(sk, &mreq); else ret = packet_mc_drop(sk, &mreq); return ret; } case PACKET_RX_RING: case PACKET_TX_RING: { union tpacket_req_u req_u; int len; switch (po->tp_version) { case TPACKET_V1: case TPACKET_V2: len = sizeof(req_u.req); break; case TPACKET_V3: default: len = sizeof(req_u.req3); break; } if (optlen < len) return -EINVAL; if (copy_from_user(&req_u.req, optval, len)) return -EFAULT; return packet_set_ring(sk, &req_u, 0, optname == PACKET_TX_RING); } case PACKET_COPY_THRESH: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; pkt_sk(sk)->copy_thresh = val; return 0; } case PACKET_VERSION: { int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; switch (val) { case TPACKET_V1: case TPACKET_V2: case TPACKET_V3: po->tp_version = val; return 0; default: return -EINVAL; } } case PACKET_RESERVE: { unsigned int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_reserve = val; return 0; } case PACKET_LOSS: { unsigned int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_loss = !!val; return 0; } case PACKET_AUXDATA: { int val; if (optlen < sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->auxdata = !!val; return 0; } case PACKET_ORIGDEV: { int val; if (optlen < sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->origdev = !!val; return 0; } case PACKET_VNET_HDR: { int val; if (sock->type != SOCK_RAW) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (optlen < sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->has_vnet_hdr = !!val; return 0; } case PACKET_TIMESTAMP: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_tstamp = val; return 0; } case PACKET_FANOUT: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; return fanout_add(sk, val & 0xffff, val >> 16); } case PACKET_FANOUT_DATA: { if (!po->fanout) return -EINVAL; return fanout_set_data(po, optval, optlen); } case PACKET_TX_HAS_OFF: { unsigned int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_tx_has_off = !!val; return 0; } case PACKET_QDISC_BYPASS: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->xmit = val ? packet_direct_xmit : dev_queue_xmit; return 0; } default: return -ENOPROTOOPT; } }
1
CVE-2016-8655
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.
2,134
file
27a14bc7ba285a0a5ebfdb55e54001aa11932b08
mconvert(struct magic_set *ms, struct magic *m, int flip) { union VALUETYPE *p = &ms->ms_value; uint8_t type; switch (type = cvt_flip(m->type, flip)) { case FILE_BYTE: cvt_8(p, m); return 1; case FILE_SHORT: cvt_16(p, m); return 1; case FILE_LONG: case FILE_DATE: case FILE_LDATE: cvt_32(p, m); return 1; case FILE_QUAD: case FILE_QDATE: case FILE_QLDATE: case FILE_QWDATE: cvt_64(p, m); return 1; case FILE_STRING: case FILE_BESTRING16: case FILE_LESTRING16: { /* Null terminate and eat *trailing* return */ p->s[sizeof(p->s) - 1] = '\0'; return 1; } case FILE_PSTRING: { char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m); size_t len = file_pstring_get_length(m, ptr1); if (len >= sizeof(p->s)) len = sizeof(p->s) - 1; while (len--) *ptr1++ = *ptr2++; *ptr1 = '\0'; return 1; } case FILE_BESHORT: p->h = (short)((p->hs[0]<<8)|(p->hs[1])); cvt_16(p, m); return 1; case FILE_BELONG: case FILE_BEDATE: case FILE_BELDATE: p->l = (int32_t) ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3])); if (type == FILE_BELONG) cvt_32(p, m); return 1; case FILE_BEQUAD: case FILE_BEQDATE: case FILE_BEQLDATE: case FILE_BEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7])); if (type == FILE_BEQUAD) cvt_64(p, m); return 1; case FILE_LESHORT: p->h = (short)((p->hs[1]<<8)|(p->hs[0])); cvt_16(p, m); return 1; case FILE_LELONG: case FILE_LEDATE: case FILE_LELDATE: p->l = (int32_t) ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0])); if (type == FILE_LELONG) cvt_32(p, m); return 1; case FILE_LEQUAD: case FILE_LEQDATE: case FILE_LEQLDATE: case FILE_LEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0])); if (type == FILE_LEQUAD) cvt_64(p, m); return 1; case FILE_MELONG: case FILE_MEDATE: case FILE_MELDATE: p->l = (int32_t) ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2])); if (type == FILE_MELONG) cvt_32(p, m); return 1; case FILE_FLOAT: cvt_float(p, m); return 1; case FILE_BEFLOAT: p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)| ((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]); cvt_float(p, m); return 1; case FILE_LEFLOAT: p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)| ((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]); cvt_float(p, m); return 1; case FILE_DOUBLE: cvt_double(p, m); return 1; case FILE_BEDOUBLE: p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]); cvt_double(p, m); return 1; case FILE_LEDOUBLE: p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]); cvt_double(p, m); return 1; case FILE_REGEX: case FILE_SEARCH: case FILE_DEFAULT: case FILE_CLEAR: case FILE_NAME: case FILE_USE: return 1; default: file_magerror(ms, "invalid type %d in mconvert()", m->type); return 0; } }
1
CVE-2014-3478
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,371
libav
0ac8ff618c5e6d878c547a8877e714ed728950ce
static double bessel(double x) { double v = 1; double lastv = 0; double t = 1; int i; x = x * x / 4; for (i = 1; v != lastv; i++) { lastv = v; t *= x / (i * i); v += t; } return v; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,233
php
0e6fe3a4c96be2d3e88389a5776f878021b4c59f
ZEND_METHOD(CURLFile, __wakeup) { zend_update_property_string(curl_CURLFile_class, getThis(), "name", sizeof("name")-1, "" TSRMLS_CC); zend_throw_exception(NULL, "Unserialization of CURLFile instances is not allowed", 0 TSRMLS_CC); }
1
CVE-2016-9137
CWE-416
Use After Free
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
Phase: Architecture and Design Strategy: Language Selection Choose a language that provides automatic memory management. Phase: Implementation Strategy: Attack Surface Reduction When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy. Effectiveness: Defense in Depth Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution.
3,936