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
Chrome
fea16c8b60ff3d0756d5eb392394963b647bc41a
ContentSecurityPolicy::~ContentSecurityPolicy() {}
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,386
cbang
1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
string TarFileReader::extract(ostream &out) { if (!hasMore()) THROW("No more tar files"); readFile(out, pri->filter); didReadHeader = false; return getFilename(); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,124
openssl
c175308407858afff3fc8c2e5e085d94d12edc7d
char *BN_bn2hex(const BIGNUM *a) { int i, j, v, z = 0; char *buf; char *p; if (a->neg && BN_is_zero(a)) { /* "-0" == 3 bytes including NULL terminator */ buf = OPENSSL_malloc(3); } else { buf = OPENSSL_malloc(a->top * BN_BYTES * 2 + 2); } if (buf == NULL) { BNerr(BN_F_BN_BN2HEX, ERR_R_MALLOC_FAILURE); goto err; } p = buf; if (a->neg) *(p++) = '-'; if (BN_is_zero(a)) *(p++) = '0'; for (i = a->top - 1; i >= 0; i--) { for (j = BN_BITS2 - 8; j >= 0; j -= 8) { /* strip leading zeros */ v = ((int)(a->d[i] >> (long)j)) & 0xff; if (z || (v != 0)) { *(p++) = Hex[v >> 4]; *(p++) = Hex[v & 0x0f]; z = 1; } } } *p = '\0'; err: return (buf); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,735
jasper
4cd52b5daac62b00a0a328451544807ddecf775f
static jpc_enc_cp_t *cp_create(const char *optstr, jas_image_t *image) { jpc_enc_cp_t *cp; jas_tvparser_t *tvp; int ret; int numilyrrates; double *ilyrrates; int i; int tagid; jpc_enc_tcp_t *tcp; jpc_enc_tccp_t *tccp; jpc_enc_ccp_t *ccp; uint_fast16_t rlvlno; uint_fast16_t prcwidthexpn; uint_fast16_t prcheightexpn; bool enablemct; uint_fast32_t jp2overhead; uint_fast16_t lyrno; uint_fast32_t hsteplcm; uint_fast32_t vsteplcm; bool mctvalid; tvp = 0; cp = 0; ilyrrates = 0; numilyrrates = 0; if (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) { goto error; } prcwidthexpn = 15; prcheightexpn = 15; enablemct = true; jp2overhead = 0; cp->ccps = 0; cp->debug = 0; cp->imgareatlx = UINT_FAST32_MAX; cp->imgareatly = UINT_FAST32_MAX; cp->refgrdwidth = 0; cp->refgrdheight = 0; cp->tilegrdoffx = UINT_FAST32_MAX; cp->tilegrdoffy = UINT_FAST32_MAX; cp->tilewidth = 0; cp->tileheight = 0; cp->numcmpts = jas_image_numcmpts(image); hsteplcm = 1; vsteplcm = 1; for (unsigned cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { if (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <= jas_image_brx(image) || jas_image_cmptbry(image, cmptno) + jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) { jas_eprintf("unsupported image type\n"); goto error; } /* Note: We ought to be calculating the LCMs here. Fix some day. */ hsteplcm *= jas_image_cmpthstep(image, cmptno); vsteplcm *= jas_image_cmptvstep(image, cmptno); } if (!(cp->ccps = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_ccp_t)))) { goto error; } unsigned cmptno; for (cmptno = 0, ccp = cp->ccps; cmptno < cp->numcmpts; ++cmptno, ++ccp) { ccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno); ccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno); /* XXX - this isn't quite correct for more general image */ ccp->sampgrdsubstepx = 0; ccp->sampgrdsubstepx = 0; ccp->prec = jas_image_cmptprec(image, cmptno); ccp->sgnd = jas_image_cmptsgnd(image, cmptno); ccp->numstepsizes = 0; memset(ccp->stepsizes, 0, sizeof(ccp->stepsizes)); } cp->rawsize = jas_image_rawsize(image); if (cp->rawsize == 0) { /* prevent division by zero in cp_create() */ goto error; } cp->totalsize = UINT_FAST32_MAX; tcp = &cp->tcp; tcp->csty = 0; tcp->intmode = true; tcp->prg = JPC_COD_LRCPPRG; tcp->numlyrs = 1; tcp->ilyrrates = 0; tccp = &cp->tccp; tccp->csty = 0; tccp->maxrlvls = 6; tccp->cblkwidthexpn = 6; tccp->cblkheightexpn = 6; tccp->cblksty = 0; tccp->numgbits = 2; if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { goto error; } while (!(ret = jas_tvparser_next(tvp))) { switch (jas_taginfo_nonull(jas_taginfos_lookup(encopts, jas_tvparser_gettag(tvp)))->id) { case OPT_DEBUG: cp->debug = atoi(jas_tvparser_getval(tvp)); break; case OPT_IMGAREAOFFX: cp->imgareatlx = atoi(jas_tvparser_getval(tvp)); break; case OPT_IMGAREAOFFY: cp->imgareatly = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEGRDOFFX: cp->tilegrdoffx = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEGRDOFFY: cp->tilegrdoffy = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEWIDTH: cp->tilewidth = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEHEIGHT: cp->tileheight = atoi(jas_tvparser_getval(tvp)); break; case OPT_PRCWIDTH: prcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_PRCHEIGHT: prcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_CBLKWIDTH: tccp->cblkwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_CBLKHEIGHT: tccp->cblkheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_MODE: if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab, jas_tvparser_getval(tvp)))->id) < 0) { jas_eprintf("ignoring invalid mode %s\n", jas_tvparser_getval(tvp)); } else { tcp->intmode = (tagid == MODE_INT); } break; case OPT_PRG: if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab, jas_tvparser_getval(tvp)))->id) < 0) { jas_eprintf("ignoring invalid progression order %s\n", jas_tvparser_getval(tvp)); } else { tcp->prg = tagid; } break; case OPT_NOMCT: enablemct = false; break; case OPT_MAXRLVLS: tccp->maxrlvls = atoi(jas_tvparser_getval(tvp)); break; case OPT_SOP: cp->tcp.csty |= JPC_COD_SOP; break; case OPT_EPH: cp->tcp.csty |= JPC_COD_EPH; break; case OPT_LAZY: tccp->cblksty |= JPC_COX_LAZY; break; case OPT_TERMALL: tccp->cblksty |= JPC_COX_TERMALL; break; case OPT_SEGSYM: tccp->cblksty |= JPC_COX_SEGSYM; break; case OPT_VCAUSAL: tccp->cblksty |= JPC_COX_VSC; break; case OPT_RESET: tccp->cblksty |= JPC_COX_RESET; break; case OPT_PTERM: tccp->cblksty |= JPC_COX_PTERM; break; case OPT_NUMGBITS: cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp)); break; case OPT_RATE: if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize, &cp->totalsize)) { jas_eprintf("ignoring bad rate specifier %s\n", jas_tvparser_getval(tvp)); } break; case OPT_ILYRRATES: if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates, &ilyrrates)) { jas_eprintf("warning: invalid intermediate layer rates specifier ignored (%s)\n", jas_tvparser_getval(tvp)); } break; case OPT_JP2OVERHEAD: jp2overhead = atoi(jas_tvparser_getval(tvp)); break; default: jas_eprintf("warning: ignoring invalid option %s\n", jas_tvparser_gettag(tvp)); break; } } jas_tvparser_destroy(tvp); tvp = 0; if (cp->totalsize != UINT_FAST32_MAX) { cp->totalsize = (cp->totalsize > jp2overhead) ? (cp->totalsize - jp2overhead) : 0; } if (cp->imgareatlx == UINT_FAST32_MAX) { cp->imgareatlx = 0; } else { if (hsteplcm != 1) { jas_eprintf("warning: overriding imgareatlx value\n"); } cp->imgareatlx *= hsteplcm; } if (cp->imgareatly == UINT_FAST32_MAX) { cp->imgareatly = 0; } else { if (vsteplcm != 1) { jas_eprintf("warning: overriding imgareatly value\n"); } cp->imgareatly *= vsteplcm; } cp->refgrdwidth = cp->imgareatlx + jas_image_width(image); cp->refgrdheight = cp->imgareatly + jas_image_height(image); if (cp->tilegrdoffx == UINT_FAST32_MAX) { cp->tilegrdoffx = cp->imgareatlx; } if (cp->tilegrdoffy == UINT_FAST32_MAX) { cp->tilegrdoffy = cp->imgareatly; } if (!cp->tilewidth) { cp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx; } if (!cp->tileheight) { cp->tileheight = cp->refgrdheight - cp->tilegrdoffy; } if (cp->numcmpts == 3) { mctvalid = true; for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { if (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) || jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) || jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) || jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) { mctvalid = false; } } } else { mctvalid = false; } if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) { jas_eprintf("warning: color space apparently not RGB\n"); } if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) { tcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT); } else { tcp->mctid = JPC_MCT_NONE; } tccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS); for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) { tccp->prcwidthexpns[rlvlno] = prcwidthexpn; tccp->prcheightexpns[rlvlno] = prcheightexpn; } if (prcwidthexpn != 15 || prcheightexpn != 15) { tccp->csty |= JPC_COX_PRT; } /* Ensure that the tile width and height is valid. */ if (!cp->tilewidth) { jas_eprintf("invalid tile width %lu\n", (unsigned long) cp->tilewidth); goto error; } if (!cp->tileheight) { jas_eprintf("invalid tile height %lu\n", (unsigned long) cp->tileheight); goto error; } /* Ensure that the tile grid offset is valid. */ if (cp->tilegrdoffx > cp->imgareatlx || cp->tilegrdoffy > cp->imgareatly || cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx || cp->tilegrdoffy + cp->tileheight < cp->imgareatly) { jas_eprintf("invalid tile grid offset (%lu, %lu)\n", (unsigned long) cp->tilegrdoffx, (unsigned long) cp->tilegrdoffy); goto error; } cp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx, cp->tilewidth); cp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy, cp->tileheight); cp->numtiles = cp->numhtiles * cp->numvtiles; if (ilyrrates && numilyrrates > 0) { tcp->numlyrs = numilyrrates + 1; if (!(tcp->ilyrrates = jas_alloc2((tcp->numlyrs - 1), sizeof(jpc_fix_t)))) { goto error; } for (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) { tcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]); } } /* Ensure that the integer mode is used in the case of lossless coding. */ if (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) { jas_eprintf("cannot use real mode for lossless coding\n"); goto error; } /* Ensure that the precinct width is valid. */ if (prcwidthexpn > 15) { jas_eprintf("invalid precinct width\n"); goto error; } /* Ensure that the precinct height is valid. */ if (prcheightexpn > 15) { jas_eprintf("invalid precinct height\n"); goto error; } /* Ensure that the code block width is valid. */ if (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) { jas_eprintf("invalid code block width %d\n", JPC_POW2(cp->tccp.cblkwidthexpn)); goto error; } /* Ensure that the code block height is valid. */ if (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) { jas_eprintf("invalid code block height %d\n", JPC_POW2(cp->tccp.cblkheightexpn)); goto error; } /* Ensure that the code block size is not too large. */ if (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) { jas_eprintf("code block size too large\n"); goto error; } /* Ensure that the number of layers is valid. */ if (cp->tcp.numlyrs > 16384) { jas_eprintf("too many layers\n"); goto error; } /* There must be at least one resolution level. */ if (cp->tccp.maxrlvls < 1) { jas_eprintf("must be at least one resolution level\n"); goto error; } /* Ensure that the number of guard bits is valid. */ if (cp->tccp.numgbits > 8) { jas_eprintf("invalid number of guard bits\n"); goto error; } /* Ensure that the rate is within the legal range. */ if (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) { jas_eprintf("warning: specified rate is unreasonably large (%lu > %lu)\n", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize); } /* Ensure that the intermediate layer rates are valid. */ if (tcp->numlyrs > 1) { /* The intermediate layers rates must increase monotonically. */ for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) { if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) { jas_eprintf("intermediate layer rates must increase monotonically\n"); goto error; } } /* The intermediate layer rates must be less than the overall rate. */ if (cp->totalsize != UINT_FAST32_MAX) { for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) { if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize) / cp->rawsize) { jas_eprintf("warning: intermediate layer rates must be less than overall rate\n"); goto error; } } } } if (ilyrrates) { jas_free(ilyrrates); } return cp; error: if (ilyrrates) { jas_free(ilyrrates); } if (tvp) { jas_tvparser_destroy(tvp); } if (cp) { jpc_enc_cp_destroy(cp); } return 0; }
1
CVE-2020-27828
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,128
Chrome
9de81f45c73a8f9f215fc234a6adfe087b0eab74
void PasswordAutofillAgent::PasswordValueGatekeeper::ShowValue( blink::WebInputElement* element) { if (!element->isNull() && !element->suggestedValue().isEmpty()) element->setValue(element->suggestedValue(), true); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,745
samba
f36cb71c330a52106e36028b3029d952257baf15
static bool ldb_dn_explode(struct ldb_dn *dn) { char *p, *ex_name = NULL, *ex_value = NULL, *data, *d, *dt, *t; bool trim = true; bool in_extended = true; bool in_ex_name = false; bool in_ex_value = false; bool in_attr = false; bool in_value = false; bool in_quote = false; bool is_oid = false; bool escape = false; unsigned int x; size_t l = 0; int ret; char *parse_dn; bool is_index; if ( ! dn || dn->invalid) return false; if (dn->components) { return true; } if (dn->ext_linearized) { parse_dn = dn->ext_linearized; } else { parse_dn = dn->linearized; } if ( ! parse_dn ) { return false; } is_index = (strncmp(parse_dn, "DN=@INDEX:", 10) == 0); /* Empty DNs */ if (parse_dn[0] == '\0') { return true; } /* Special DNs case */ if (dn->special) { return true; } /* make sure we free this if allocated previously before replacing */ LDB_FREE(dn->components); dn->comp_num = 0; LDB_FREE(dn->ext_components); dn->ext_comp_num = 0; /* in the common case we have 3 or more components */ /* make sure all components are zeroed, other functions depend on it */ dn->components = talloc_zero_array(dn, struct ldb_dn_component, 3); if ( ! dn->components) { return false; } /* Components data space is allocated here once */ data = talloc_array(dn->components, char, strlen(parse_dn) + 1); if (!data) { return false; } p = parse_dn; t = NULL; d = dt = data; while (*p) { if (in_extended) { if (!in_ex_name && !in_ex_value) { if (p[0] == '<') { p++; ex_name = d; in_ex_name = true; continue; } else if (p[0] == '\0') { p++; continue; } else { in_extended = false; in_attr = true; dt = d; continue; } } if (in_ex_name && *p == '=') { *d++ = '\0'; p++; ex_value = d; in_ex_name = false; in_ex_value = true; continue; } if (in_ex_value && *p == '>') { const struct ldb_dn_extended_syntax *ext_syntax; struct ldb_val ex_val = { .data = (uint8_t *)ex_value, .length = d - ex_value }; *d++ = '\0'; p++; in_ex_value = false; /* Process name and ex_value */ dn->ext_components = talloc_realloc(dn, dn->ext_components, struct ldb_dn_ext_component, dn->ext_comp_num + 1); if ( ! dn->ext_components) { /* ouch ! */ goto failed; } ext_syntax = ldb_dn_extended_syntax_by_name(dn->ldb, ex_name); if (!ext_syntax) { /* We don't know about this type of extended DN */ goto failed; } dn->ext_components[dn->ext_comp_num].name = talloc_strdup(dn->ext_components, ex_name); if (!dn->ext_components[dn->ext_comp_num].name) { /* ouch */ goto failed; } ret = ext_syntax->read_fn(dn->ldb, dn->ext_components, &ex_val, &dn->ext_components[dn->ext_comp_num].value); if (ret != LDB_SUCCESS) { ldb_dn_mark_invalid(dn); goto failed; } dn->ext_comp_num++; if (*p == '\0') { /* We have reached the end (extended component only)! */ talloc_free(data); return true; } else if (*p == ';') { p++; continue; } else { ldb_dn_mark_invalid(dn); goto failed; } } *d++ = *p++; continue; } if (in_attr) { if (trim) { if (*p == ' ') { p++; continue; } /* first char */ trim = false; if (!isascii(*p)) { /* attr names must be ascii only */ ldb_dn_mark_invalid(dn); goto failed; } if (isdigit(*p)) { is_oid = true; } else if ( ! isalpha(*p)) { /* not a digit nor an alpha, * invalid attribute name */ ldb_dn_mark_invalid(dn); goto failed; } /* Copy this character across from parse_dn, * now we have trimmed out spaces */ *d++ = *p++; continue; } if (*p == ' ') { p++; /* valid only if we are at the end */ trim = true; continue; } if (trim && (*p != '=')) { /* spaces/tabs are not allowed */ ldb_dn_mark_invalid(dn); goto failed; } if (*p == '=') { /* attribute terminated */ in_attr = false; in_value = true; trim = true; l = 0; /* Terminate this string in d * (which is a copy of parse_dn * with spaces trimmed) */ *d++ = '\0'; dn->components[dn->comp_num].name = talloc_strdup(dn->components, dt); if ( ! dn->components[dn->comp_num].name) { /* ouch */ goto failed; } dt = d; p++; continue; } if (!isascii(*p)) { /* attr names must be ascii only */ ldb_dn_mark_invalid(dn); goto failed; } if (is_oid && ( ! (isdigit(*p) || (*p == '.')))) { /* not a digit nor a dot, * invalid attribute oid */ ldb_dn_mark_invalid(dn); goto failed; } else if ( ! (isalpha(*p) || isdigit(*p) || (*p == '-'))) { /* not ALPHA, DIGIT or HYPHEN */ ldb_dn_mark_invalid(dn); goto failed; } *d++ = *p++; continue; } if (in_value) { if (in_quote) { if (*p == '\"') { if (p[-1] != '\\') { p++; in_quote = false; continue; } } *d++ = *p++; l++; continue; } if (trim) { if (*p == ' ') { p++; continue; } /* first char */ trim = false; if (*p == '\"') { in_quote = true; p++; continue; } } switch (*p) { /* TODO: support ber encoded values case '#': */ case ',': if (escape) { *d++ = *p++; l++; escape = false; continue; } /* ok found value terminator */ if ( t ) { /* trim back */ d -= (p - t); l -= (p - t); } in_attr = true; in_value = false; trim = true; p++; *d++ = '\0'; dn->components[dn->comp_num].value.data = (uint8_t *)talloc_strdup(dn->components, dt); dn->components[dn->comp_num].value.length = l; if ( ! dn->components[dn->comp_num].value.data) { /* ouch ! */ goto failed; } dt = d; dn->components, struct ldb_dn_component, dn->comp_num + 1); if ( ! dn->components) { /* ouch ! */ goto failed; } /* make sure all components are zeroed, other functions depend on this */ memset(&dn->components[dn->comp_num], '\0', sizeof(struct ldb_dn_component)); } continue; case '+': case '=': /* to main compatibility with earlier versions of ldb indexing, we have to accept the base64 encoded binary index values, which contain a '+' or '=' which should normally be escaped */ if (is_index) { if ( t ) t = NULL; *d++ = *p++; l++; break; } /* fall through */ case '\"': case '<': case '>': case ';': /* a string with not escaped specials is invalid (tested) */ if ( ! escape) { ldb_dn_mark_invalid(dn); goto failed; } escape = false; *d++ = *p++; l++; if ( t ) t = NULL; break; case '\\': if ( ! escape) { escape = true; p++; continue; } escape = false; *d++ = *p++; l++; if ( t ) t = NULL; break; default: if (escape) { if (isxdigit(p[0]) && isxdigit(p[1])) { if (sscanf(p, "%02x", &x) != 1) { /* invalid escaping sequence */ ldb_dn_mark_invalid(dn); goto failed; } p += 2; *d++ = (unsigned char)x; } else { *d++ = *p++; } escape = false; l++; if ( t ) t = NULL; break; } if (*p == ' ') { if ( ! t) t = p; } else { if ( t ) t = NULL; } *d++ = *p++; l++; break; } } }
1
CVE-2015-5330
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
Phase: Architecture and Design Strategy: Separation of Privilege Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area. Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges.
4,288
Chrome
ed6f4545a2a345697e07908c887333f5bdcc97a3
void ScriptLoader::executeScript(const ScriptSourceCode& sourceCode) { ASSERT(m_alreadyStarted); if (sourceCode.isEmpty()) return; RefPtr<Document> elementDocument(m_element->document()); RefPtr<Document> contextDocument = elementDocument->contextDocument().get(); if (!contextDocument) return; LocalFrame* frame = contextDocument->frame(); bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script().shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)) || elementDocument->contentSecurityPolicy()->allowScriptHash(sourceCode.source()); if (!m_isExternalScript && (!shouldBypassMainWorldContentSecurityPolicy && !elementDocument->contentSecurityPolicy()->allowInlineScript(elementDocument->url(), m_startLineNumber))) return; if (m_isExternalScript && m_resource && !m_resource->mimeTypeAllowedByNosniff()) { contextDocument->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + m_resource->url().elidedString() + "' because its MIME type ('" + m_resource->mimeType() + "') is not executable, and strict MIME type checking is enabled."); return; } if (frame) { const bool isImportedScript = contextDocument != elementDocument; IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_isExternalScript || isImportedScript ? contextDocument.get() : 0); if (isHTMLScriptLoader(m_element)) contextDocument->pushCurrentScript(toHTMLScriptElement(m_element)); AccessControlStatus corsCheck = NotSharableCrossOrigin; if (sourceCode.resource() && sourceCode.resource()->passesAccessControlCheck(m_element->document().securityOrigin())) corsCheck = SharableCrossOrigin; frame->script().executeScriptInMainWorld(sourceCode, corsCheck); if (isHTMLScriptLoader(m_element)) { ASSERT(contextDocument->currentScript() == m_element); contextDocument->popCurrentScript(); } } }
1
CVE-2013-0893
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The product contains a concurrent code sequence that requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence operating concurrently.
Phase: Architecture and Design In languages that support it, use synchronization primitives. Only wrap these around critical code to minimize the impact on performance. Phase: Architecture and Design Use thread-safe capabilities such as the data access abstraction in Spring. Phase: Architecture and Design Minimize the usage of shared resources in order to remove as much complexity as possible from the control flow and to reduce the likelihood of unexpected conditions occurring. Additionally, this will minimize the amount of synchronization necessary and may even help to reduce the likelihood of a denial of service where an attacker may be able to repeatedly trigger a critical section (CWE-400). Phase: Implementation When using multithreading and operating on shared variables, only use thread-safe functions. Phase: Implementation Use atomic operations on shared variables. Be wary of innocent-looking constructs such as "x++". This may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read, followed by a computation, followed by a write. Phase: Implementation Use a mutex if available, but be sure to avoid related weaknesses such as CWE-412. Phase: Implementation Avoid double-checked locking (CWE-609) and other implementation errors that arise when trying to avoid the overhead of synchronization. Phase: Implementation Disable interrupts or signals over critical parts of the code, but also make sure that the code does not go into a large or infinite loop. Phase: Implementation Use the volatile type modifier for critical variables to avoid unexpected compiler optimization or reordering. This does not necessarily solve the synchronization problem, but it can help. Phases: Architecture and Design; Operation Strategy: Environment Hardening Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations
5,645
linux
9b57da0630c9fd36ed7a20fc0f98dc82cc0777fa
static unsigned int ipv6_defrag(void *priv, struct sk_buff *skb, const struct nf_hook_state *state) { int err; #if IS_ENABLED(CONFIG_NF_CONNTRACK) /* Previously seen (loopback)? */ if (skb->nfct && !nf_ct_is_template((struct nf_conn *)skb->nfct)) return NF_ACCEPT; #endif err = nf_ct_frag6_gather(state->net, skb, nf_ct6_defrag_user(state->hook, skb)); /* queued */ if (err == -EINPROGRESS) return NF_STOLEN; return NF_ACCEPT; }
1
CVE-2016-9755
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
3,310
php-src
feba44546c27b0158f9ac20e72040a224b918c75
gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color) { int lastBorder; /* Seek left */ int leftLimit, rightLimit; int i; leftLimit = (-1); if (border < 0) { /* Refuse to fill to a non-solid border */ return; } for (i = x; (i >= 0); i--) { if (gdImageGetPixel (im, i, y) == border) { break; } gdImageSetPixel (im, i, y, color); leftLimit = i; } if (leftLimit == (-1)) { return; } /* Seek right */ rightLimit = x; for (i = (x + 1); (i < im->sx); i++) { if (gdImageGetPixel (im, i, y) == border) { break; } gdImageSetPixel (im, i, y, color); rightLimit = i; } /* Look at lines above and below and start paints */ /* Above */ if (y > 0) { lastBorder = 1; for (i = leftLimit; (i <= rightLimit); i++) { int c; c = gdImageGetPixel (im, i, y - 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder (im, i, y - 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } /* Below */ if (y < ((im->sy) - 1)) { lastBorder = 1; for (i = leftLimit; (i <= rightLimit); i++) { int c; c = gdImageGetPixel (im, i, y + 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder (im, i, y + 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } }
1
CVE-2015-8874
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
9,348
pacemaker
5fe63f902b35bfed9cee117060a3ba7830d548f5
crm_ipc_connect(crm_ipc_t * client) { client->need_reply = FALSE; client->ipc = qb_ipcc_connect(client->name, client->buf_size); if (client->ipc == NULL) { crm_perror(LOG_INFO, "Could not establish %s connection", client->name); return FALSE; } client->pfd.fd = crm_ipc_get_fd(client); if (client->pfd.fd < 0) { crm_perror(LOG_INFO, "Could not obtain file descriptor for %s connection", client->name); return FALSE; } qb_ipcc_context_set(client->ipc, client); return TRUE; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,550
linux
338c7dbadd2671189cec7faf64c84d01071b3f96
static void kvm_sched_out(struct preempt_notifier *pn, struct task_struct *next) { struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn); if (current->state == TASK_RUNNING) vcpu->preempted = true; kvm_arch_vcpu_put(vcpu); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,090
server
01b39b7b0730102b88d8ea43ec719a75e9316a1e
ulonglong timer_now(void) { return my_interval_timer() / 1000000; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,382
vim
5f25c3855071bd7e26255c68bf458b1b5cf92f39
compile_get_env(char_u **arg, cctx_T *cctx) { char_u *start = *arg; int len; int ret; char_u *name; ++*arg; len = get_env_len(arg); if (len == 0) { semsg(_(e_syntax_error_at_str), start - 1); return FAIL; } // include the '$' in the name, eval_env_var() expects it. name = vim_strnsave(start, len + 1); ret = generate_LOAD(cctx, ISN_LOADENV, 0, name, &t_string); vim_free(name); return ret; }
1
CVE-2022-0158
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,150
raptor
590681e546cd9aa18d57dc2ea1858cb734a3863f
raptor_xml_writer_comment(raptor_xml_writer* xml_writer, const unsigned char *s) { XML_WRITER_FLUSH_CLOSE_BRACKET(xml_writer); raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"<!-- ", 5); raptor_xml_writer_cdata(xml_writer, s); raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)" -->", 4); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,319
Android
a33f6725d7e9f92330f995ce2dcf4faa33f6433f
WORD32 ihevcd_decode(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op) { WORD32 ret = IV_SUCCESS; codec_t *ps_codec = (codec_t *)(ps_codec_obj->pv_codec_handle); ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; WORD32 proc_idx = 0; WORD32 prev_proc_idx = 0; /* Initialize error code */ ps_codec->i4_error_code = 0; ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; //Restore size field } if(ps_codec->i4_init_done != 1) { ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; ps_dec_op->u4_error_code |= IHEVCD_INIT_NOT_DONE; return IV_FAIL; } if(ps_codec->u4_pic_cnt >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; ps_dec_op->u4_error_code |= IHEVCD_NUM_FRAMES_LIMIT_REACHED; return IV_FAIL; } /* If reset flag is set, flush the existing buffers */ if(ps_codec->i4_reset_flag) { ps_codec->i4_flush_mode = 1; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ /* In case the decoder is not in flush mode check for input buffer validity */ if(0 == ps_codec->i4_flush_mode) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= MIN_START_CODE_LEN) { if((WORD32)ps_dec_ip->u4_num_Bytes > 0) ps_dec_op->u4_num_bytes_consumed = ps_dec_ip->u4_num_Bytes; else ps_dec_op->u4_num_bytes_consumed = 0; ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } #ifdef APPLY_CONCEALMENT { WORD32 num_mbs; num_mbs = (ps_codec->i4_wd * ps_codec->i4_ht + 255) >> 8; /* Reset MB Count at the beginning of every process call */ ps_codec->mb_count = 0; memset(ps_codec->mb_map, 0, ((num_mbs + 7) >> 3)); } #endif if(0 == ps_codec->i4_share_disp_buf && ps_codec->i4_header_mode == 0) { UWORD32 i; if(ps_dec_ip->s_out_buffer.u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec_ip->s_out_buffer.u4_num_bufs; i++) { if(ps_dec_ip->s_out_buffer.pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->s_out_buffer.u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } ps_codec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_codec->u4_ts = ps_dec_ip->u4_ts; if(ps_codec->i4_flush_mode) { ps_dec_op->u4_pic_wd = ps_codec->i4_disp_wd; ps_dec_op->u4_pic_ht = ps_codec->i4_disp_ht; ps_dec_op->u4_new_seq = 0; ps_codec->ps_disp_buf = (pic_buf_t *)ihevc_disp_mgr_get( (disp_mgr_t *)ps_codec->pv_disp_buf_mgr, &ps_codec->i4_disp_buf_id); /* In case of non-shared mode, then convert/copy the frame to output buffer */ /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ if((ps_codec->ps_disp_buf) && ((0 == ps_codec->i4_share_disp_buf) || (IV_YUV_420P == ps_codec->e_chroma_fmt))) { process_ctxt_t *ps_proc = &ps_codec->as_process[prev_proc_idx]; if(0 == ps_proc->i4_init_done) { ihevcd_init_proc_ctxt(ps_proc, 0); } /* Set remaining number of rows to be processed */ ret = ihevcd_fmt_conv(ps_codec, &ps_codec->as_process[prev_proc_idx], ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], 0, ps_codec->i4_disp_ht); ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_codec->i4_disp_buf_id, BUF_MGR_DISP); } ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); if(1 == ps_dec_op->u4_output_present) { WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD; WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT; if(ypos < 0) ypos = 0; if(xpos < 0) xpos = 0; INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd, xpos, ypos, ps_codec->e_chroma_fmt, ps_codec->i4_disp_wd, ps_codec->i4_disp_ht); } if(NULL == ps_codec->ps_disp_buf) { /* If in flush mode and there are no more buffers to flush, * check for the reset flag and reset the decoder */ if(ps_codec->i4_reset_flag) { ihevcd_init(ps_codec); } return (IV_FAIL); } return (IV_SUCCESS); } /* In case of shared mode, check if there is a free buffer for reconstruction */ if((0 == ps_codec->i4_header_mode) && (1 == ps_codec->i4_share_disp_buf)) { WORD32 buf_status; buf_status = 1; if(ps_codec->pv_pic_buf_mgr) buf_status = ihevc_buf_mgr_check_free((buf_mgr_t *)ps_codec->pv_pic_buf_mgr); /* If there is no free buffer, then return with an error code */ if(0 == buf_status) { ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return IV_FAIL; } } ps_codec->i4_bytes_remaining = ps_dec_ip->u4_num_Bytes; ps_codec->pu1_inp_bitsbuf = (UWORD8 *)ps_dec_ip->pv_stream_buffer; ps_codec->s_parse.i4_end_of_frame = 0; ps_codec->i4_pic_present = 0; ps_codec->i4_slice_error = 0; ps_codec->ps_disp_buf = NULL; if(ps_codec->i4_num_cores > 1) { ithread_set_affinity(0); } while(MIN_START_CODE_LEN < ps_codec->i4_bytes_remaining) { WORD32 nal_len; WORD32 nal_ofst; WORD32 bits_len; if(ps_codec->i4_slice_error) { slice_header_t *ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)); WORD32 next_slice_addr = ps_slice_hdr_next->i2_ctb_x + ps_slice_hdr_next->i2_ctb_y * ps_codec->s_parse.ps_sps->i2_pic_wd_in_ctb; if(ps_codec->s_parse.i4_next_ctb_indx == next_slice_addr) ps_codec->i4_slice_error = 0; } if(ps_codec->pu1_bitsbuf_dynamic) { ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_dynamic; ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_dynamic; } else { ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_static; ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_static; } nal_ofst = ihevcd_nal_search_start_code(ps_codec->pu1_inp_bitsbuf, ps_codec->i4_bytes_remaining); ps_codec->i4_nal_ofst = nal_ofst; { WORD32 bytes_remaining = ps_codec->i4_bytes_remaining - nal_ofst; bytes_remaining = MIN((UWORD32)bytes_remaining, ps_codec->u4_bitsbuf_size); ihevcd_nal_remv_emuln_bytes(ps_codec->pu1_inp_bitsbuf + nal_ofst, ps_codec->pu1_bitsbuf, bytes_remaining, &nal_len, &bits_len); /* Decoder may read upto 8 extra bytes at the end of frame */ /* These are not used, but still set them to zero to avoid uninitialized reads */ if(bits_len < (WORD32)(ps_codec->u4_bitsbuf_size - 8)) { memset(ps_codec->pu1_bitsbuf + bits_len, 0, 2 * sizeof(UWORD32)); } } /* This may be used to update the offsets for tiles and entropy sync row offsets */ ps_codec->i4_num_emln_bytes = nal_len - bits_len; ps_codec->i4_nal_len = nal_len; ihevcd_bits_init(&ps_codec->s_parse.s_bitstrm, ps_codec->pu1_bitsbuf, bits_len); ret = ihevcd_nal_unit(ps_codec); /* If the frame is incomplete and * the bytes remaining is zero or a header is received, * complete the frame treating it to be in error */ if(ps_codec->i4_pic_present && (ps_codec->s_parse.i4_next_ctb_indx != ps_codec->s_parse.ps_sps->i4_pic_size_in_ctb)) { if((ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN) || (ps_codec->i4_header_in_slice_mode)) { slice_header_t *ps_slice_hdr_next; ps_codec->s_parse.i4_cur_slice_idx--; if(ps_codec->s_parse.i4_cur_slice_idx < 0) ps_codec->s_parse.i4_cur_slice_idx = 0; ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1)); ps_slice_hdr_next->i2_ctb_x = 0; ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb; ps_codec->i4_slice_error = 1; continue; } } if(IHEVCD_IGNORE_SLICE == ret) { ps_codec->s_parse.i4_cur_slice_idx = MAX(0, (ps_codec->s_parse.i4_cur_slice_idx - 1)); ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len); ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len); continue; } if((IVD_RES_CHANGED == ret) || (IHEVCD_UNSUPPORTED_DIMENSIONS == ret)) { break; } /* Update bytes remaining and bytes consumed and input bitstream pointer */ /* Do not consume the NAL in the following cases */ /* Slice header reached during header decode mode */ /* TODO: Next picture's slice reached */ if(ret != IHEVCD_SLICE_IN_HEADER_MODE) { if((0 == ps_codec->i4_slice_error) || (ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN)) { ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len); ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len); } if(ret != IHEVCD_SUCCESS) break; if(ps_codec->s_parse.i4_end_of_frame) break; } else { ret = IHEVCD_SUCCESS; break; } /* Allocate dynamic bitstream buffer once SPS is decoded */ if((ps_codec->u4_allocate_dynamic_done == 0) && ps_codec->i4_sps_done) { WORD32 ret; ret = ihevcd_allocate_dynamic_bufs(ps_codec); if(ret != IV_SUCCESS) { /* Free any dynamic buffers that are allocated */ ihevcd_free_dynamic_bufs(ps_codec); ps_codec->i4_error_code = IVD_MEM_ALLOC_FAILED; ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; ps_dec_op->u4_error_code |= IVD_MEM_ALLOC_FAILED; return IV_FAIL; } } BREAK_AFTER_SLICE_NAL(); } if((ps_codec->u4_pic_cnt == 0) && (ret != IHEVCD_SUCCESS)) { ps_codec->i4_error_code = ret; ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); return IV_FAIL; } if(1 == ps_codec->i4_pic_present) { WORD32 i; sps_t *ps_sps = ps_codec->s_parse.ps_sps; ps_codec->i4_first_pic_done = 1; /*TODO temporary fix: end_of_frame is checked before adding format conversion to job queue */ if(ps_codec->i4_num_cores > 1 && ps_codec->s_parse.i4_end_of_frame) { /* Add job queue for format conversion / frame copy for each ctb row */ /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ process_ctxt_t *ps_proc; /* i4_num_cores - 1 contexts are currently being used by other threads */ ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1]; if((ps_codec->ps_disp_buf) && ((0 == ps_codec->i4_share_disp_buf) || (IV_YUV_420P == ps_codec->e_chroma_fmt))) { /* If format conversion jobs were not issued in pic_init() add them here */ if((0 == ps_codec->u4_enable_fmt_conv_ahead) || (ps_codec->i4_disp_buf_id == ps_proc->i4_cur_pic_buf_id)) for(i = 0; i < ps_sps->i2_pic_ht_in_ctb; i++) { proc_job_t s_job; IHEVCD_ERROR_T ret; s_job.i4_cmd = CMD_FMTCONV; s_job.i2_ctb_cnt = 0; s_job.i2_ctb_x = 0; s_job.i2_ctb_y = i; s_job.i2_slice_idx = 0; s_job.i4_tu_coeff_data_ofst = 0; ret = ihevcd_jobq_queue((jobq_t *)ps_codec->s_parse.pv_proc_jobq, &s_job, sizeof(proc_job_t), 1); if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS) return (WORD32)ret; } } /* Reached end of frame : Signal terminate */ /* The terminate flag is checked only after all the jobs are dequeued */ ret = ihevcd_jobq_terminate((jobq_t *)ps_codec->s_parse.pv_proc_jobq); while(1) { IHEVCD_ERROR_T ret; proc_job_t s_job; process_ctxt_t *ps_proc; /* i4_num_cores - 1 contexts are currently being used by other threads */ ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1]; ret = ihevcd_jobq_dequeue((jobq_t *)ps_proc->pv_proc_jobq, &s_job, sizeof(proc_job_t), 1); if((IHEVCD_ERROR_T)IHEVCD_SUCCESS != ret) break; ps_proc->i4_ctb_cnt = s_job.i2_ctb_cnt; ps_proc->i4_ctb_x = s_job.i2_ctb_x; ps_proc->i4_ctb_y = s_job.i2_ctb_y; ps_proc->i4_cur_slice_idx = s_job.i2_slice_idx; if(CMD_PROCESS == s_job.i4_cmd) { ihevcd_init_proc_ctxt(ps_proc, s_job.i4_tu_coeff_data_ofst); ihevcd_process(ps_proc); } else if(CMD_FMTCONV == s_job.i4_cmd) { sps_t *ps_sps = ps_codec->s_parse.ps_sps; WORD32 num_rows = 1 << ps_sps->i1_log2_ctb_size; if(0 == ps_proc->i4_init_done) { ihevcd_init_proc_ctxt(ps_proc, 0); } num_rows = MIN(num_rows, (ps_codec->i4_disp_ht - (s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size))); if(num_rows < 0) num_rows = 0; ihevcd_fmt_conv(ps_codec, ps_proc, ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size, num_rows); } } } /* In case of non-shared mode and while running in single core mode, then convert/copy the frame to output buffer */ /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ else if((ps_codec->ps_disp_buf) && ((0 == ps_codec->i4_share_disp_buf) || (IV_YUV_420P == ps_codec->e_chroma_fmt)) && (ps_codec->s_parse.i4_end_of_frame)) { process_ctxt_t *ps_proc = &ps_codec->as_process[proc_idx]; /* Set remaining number of rows to be processed */ ps_codec->s_fmt_conv.i4_num_rows = ps_codec->i4_disp_ht - ps_codec->s_fmt_conv.i4_cur_row; if(0 == ps_proc->i4_init_done) { ihevcd_init_proc_ctxt(ps_proc, 0); } if(ps_codec->s_fmt_conv.i4_num_rows < 0) ps_codec->s_fmt_conv.i4_num_rows = 0; ret = ihevcd_fmt_conv(ps_codec, ps_proc, ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->s_fmt_conv.i4_cur_row, ps_codec->s_fmt_conv.i4_num_rows); ps_codec->s_fmt_conv.i4_cur_row += ps_codec->s_fmt_conv.i4_num_rows; } DEBUG_DUMP_MV_MAP(ps_codec); /* Mark MV Buf as needed for reference */ ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, ps_codec->as_process[proc_idx].i4_cur_mv_bank_buf_id, BUF_MGR_REF); /* Mark pic buf as needed for reference */ ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_codec->as_process[proc_idx].i4_cur_pic_buf_id, BUF_MGR_REF); /* Mark pic buf as needed for display */ ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_codec->as_process[proc_idx].i4_cur_pic_buf_id, BUF_MGR_DISP); /* Insert the current picture as short term reference */ ihevc_dpb_mgr_insert_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, ps_codec->as_process[proc_idx].ps_cur_pic, ps_codec->as_process[proc_idx].i4_cur_pic_buf_id); /* If a frame was displayed (in non-shared mode), then release it from display manager */ if((0 == ps_codec->i4_share_disp_buf) && (ps_codec->ps_disp_buf)) ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_codec->i4_disp_buf_id, BUF_MGR_DISP); /* Wait for threads */ for(i = 0; i < (ps_codec->i4_num_cores - 1); i++) { if(ps_codec->ai4_process_thread_created[i]) { ithread_join(ps_codec->apv_process_thread_handle[i], NULL); ps_codec->ai4_process_thread_created[i] = 0; } } DEBUG_VALIDATE_PADDED_REGION(&ps_codec->as_process[proc_idx]); if(ps_codec->u4_pic_cnt > 0) { DEBUG_DUMP_PIC_PU(ps_codec); } DEBUG_DUMP_PIC_BUFFERS(ps_codec); /* Increment the number of pictures decoded */ ps_codec->u4_pic_cnt++; } ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); if(1 == ps_dec_op->u4_output_present) { WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD; WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT; if(ypos < 0) ypos = 0; if(xpos < 0) xpos = 0; INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd, xpos, ypos, ps_codec->e_chroma_fmt, ps_codec->i4_disp_wd, ps_codec->i4_disp_ht); } return ret; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,381
Chrome
784f56a9c97a838448dd23f9bdc7c05fe8e639b3
void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before, size_t after) { Send(new InputMsg_ExtendSelectionAndDelete(routing_id_, before, after)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,082
weechat
efb795c74fe954b9544074aafcebb1be4452b03a
hook_process_child (struct t_hook *hook_process) { char *exec_args[4] = { "sh", "-c", NULL, NULL }; const char *ptr_url; int rc; /* * close stdin, so that process will fail to read stdin (process reading * stdin should not be run inside WeeChat!) */ close (STDIN_FILENO); /* redirect stdout/stderr to pipe (so that father process can read them) */ close (HOOK_PROCESS(hook_process, child_read[HOOK_PROCESS_STDOUT])); close (HOOK_PROCESS(hook_process, child_read[HOOK_PROCESS_STDERR])); if (dup2 (HOOK_PROCESS(hook_process, child_write[HOOK_PROCESS_STDOUT]), STDOUT_FILENO) < 0) { _exit (EXIT_FAILURE); } if (dup2 (HOOK_PROCESS(hook_process, child_write[HOOK_PROCESS_STDERR]), STDERR_FILENO) < 0) { _exit (EXIT_FAILURE); } rc = EXIT_SUCCESS; if (strncmp (HOOK_PROCESS(hook_process, command), "url:", 4) == 0) { /* get URL output (on stdout or file, depending on options) */ ptr_url = HOOK_PROCESS(hook_process, command) + 4; while (ptr_url[0] == ' ') { ptr_url++; } rc = weeurl_download (ptr_url, HOOK_PROCESS(hook_process, options)); if (rc != 0) fprintf (stderr, "Error with URL '%s'\n", ptr_url); } else { /* launch command */ exec_args[2] = HOOK_PROCESS(hook_process, command); execvp (exec_args[0], exec_args); /* should not be executed if execvp was ok */ fprintf (stderr, "Error with command '%s'\n", HOOK_PROCESS(hook_process, command)); rc = EXIT_FAILURE; } fflush (stdout); fflush (stderr); _exit (rc); }
1
CVE-2012-5534
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
4,515
php
b1bd4119bcafab6f9a8f84d92cd65eec3afeface
void php_wddx_serialize_var(wddx_packet *packet, zval *var, char *name, int name_len TSRMLS_DC) { HashTable *ht; if (name) { size_t name_esc_len; char *tmp_buf, *name_esc; name_esc = php_escape_html_entities(name, name_len, &name_esc_len, 0, ENT_QUOTES, NULL TSRMLS_CC); tmp_buf = emalloc(name_esc_len + sizeof(WDDX_VAR_S)); snprintf(tmp_buf, name_esc_len + sizeof(WDDX_VAR_S), WDDX_VAR_S, name_esc); php_wddx_add_chunk(packet, tmp_buf); efree(tmp_buf); efree(name_esc); } switch(Z_TYPE_P(var)) { case IS_STRING: php_wddx_serialize_string(packet, var TSRMLS_CC); break; case IS_LONG: case IS_DOUBLE: php_wddx_serialize_number(packet, var); break; case IS_BOOL: php_wddx_serialize_boolean(packet, var); break; case IS_NULL: php_wddx_serialize_unset(packet); break; case IS_ARRAY: ht = Z_ARRVAL_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_array(packet, var); ht->nApplyCount--; break; case IS_OBJECT: ht = Z_OBJPROP_P(var); if (ht->nApplyCount > 1) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references"); return; } ht->nApplyCount++; php_wddx_serialize_object(packet, var); ht->nApplyCount--; break; } if (name) { php_wddx_add_chunk_static(packet, WDDX_VAR_E); } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,003
tcpdump
e6511cc1a950fe1566b2236329d6b4bd0826cc7a
lldp_network_addr_print(netdissect_options *ndo, const u_char *tptr, u_int len) { uint8_t af; static char buf[BUFSIZE]; const char * (*pfunc)(netdissect_options *, const u_char *); if (len < 1) return NULL; len--; af = *tptr; switch (af) { case AFNUM_INET: if (len < 4) return NULL; /* This cannot be assigned to ipaddr_string(), which is a macro. */ pfunc = getname; break; case AFNUM_INET6: if (len < 16) return NULL; /* This cannot be assigned to ip6addr_string(), which is a macro. */ pfunc = getname6; break; case AFNUM_802: if (len < 6) return NULL; pfunc = etheraddr_string; break; default: pfunc = NULL; break; } if (!pfunc) { snprintf(buf, sizeof(buf), "AFI %s (%u), no AF printer !", tok2str(af_values, "Unknown", af), af); } else { snprintf(buf, sizeof(buf), "AFI %s (%u): %s", tok2str(af_values, "Unknown", af), af, (*pfunc)(ndo, tptr+1)); } return buf; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,164
linux
7b0d0b40cd78cadb525df760ee4cac151533c2b5
static int selinux_bprm_set_creds(struct linux_binprm *bprm) { const struct task_security_struct *old_tsec; struct task_security_struct *new_tsec; struct inode_security_struct *isec; struct common_audit_data ad; struct inode *inode = file_inode(bprm->file); int rc; rc = cap_bprm_set_creds(bprm); if (rc) return rc; /* SELinux context only depends on initial program or script and not * the script interpreter */ if (bprm->cred_prepared) return 0; old_tsec = current_security(); new_tsec = bprm->cred->security; isec = inode->i_security; /* Default to the current task SID. */ new_tsec->sid = old_tsec->sid; new_tsec->osid = old_tsec->sid; /* Reset fs, key, and sock SIDs on execve. */ new_tsec->create_sid = 0; new_tsec->keycreate_sid = 0; new_tsec->sockcreate_sid = 0; if (old_tsec->exec_sid) { new_tsec->sid = old_tsec->exec_sid; /* Reset exec SID on execve. */ new_tsec->exec_sid = 0; /* * Minimize confusion: if no_new_privs or nosuid and a * transition is explicitly requested, then fail the exec. */ if (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS) return -EPERM; if (bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID) return -EACCES; } else { /* Check for a default transition on this program. */ rc = security_transition_sid(old_tsec->sid, isec->sid, SECCLASS_PROCESS, NULL, &new_tsec->sid); if (rc) return rc; } ad.type = LSM_AUDIT_DATA_PATH; ad.u.path = bprm->file->f_path; if ((bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID) || (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS)) new_tsec->sid = old_tsec->sid; if (new_tsec->sid == old_tsec->sid) { rc = avc_has_perm(old_tsec->sid, isec->sid, SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad); if (rc) return rc; } else { /* Check permissions for the transition. */ rc = avc_has_perm(old_tsec->sid, new_tsec->sid, SECCLASS_PROCESS, PROCESS__TRANSITION, &ad); if (rc) return rc; rc = avc_has_perm(new_tsec->sid, isec->sid, SECCLASS_FILE, FILE__ENTRYPOINT, &ad); if (rc) return rc; /* Check for shared state */ if (bprm->unsafe & LSM_UNSAFE_SHARE) { rc = avc_has_perm(old_tsec->sid, new_tsec->sid, SECCLASS_PROCESS, PROCESS__SHARE, NULL); if (rc) return -EPERM; } /* Make sure that anyone attempting to ptrace over a task that * changes its SID has the appropriate permit */ if (bprm->unsafe & (LSM_UNSAFE_PTRACE | LSM_UNSAFE_PTRACE_CAP)) { struct task_struct *tracer; struct task_security_struct *sec; u32 ptsid = 0; rcu_read_lock(); tracer = ptrace_parent(current); if (likely(tracer != NULL)) { sec = __task_cred(tracer)->security; ptsid = sec->sid; } rcu_read_unlock(); if (ptsid != 0) { rc = avc_has_perm(ptsid, new_tsec->sid, SECCLASS_PROCESS, PROCESS__PTRACE, NULL); if (rc) return -EPERM; } } /* Clear any possibly unsafe personality bits on exec: */ bprm->per_clear |= PER_CLEAR_ON_SETID; } return 0; }
1
CVE-2014-3215
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,085
linux
1d1221f375c94ef961ba8574ac4f85c8870ddd51
static int comm_open(struct inode *inode, struct file *filp) { return single_open(filp, comm_show, inode); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,639
atomicparsley
d72ccf06c98259d7261e0f3ac4fd8717778782c1
void APar_Extract_d263_Info(char *uint32_buffer, FILE *isofile, short track_level_atom, TrackInfo *track_info) { uint64_t offset_into_d263 = 8; APar_readX(track_info->encoder_name, isofile, parsedAtoms[track_level_atom].AtomicStart + offset_into_d263, 4); track_info->level = APar_read8(isofile, parsedAtoms[track_level_atom].AtomicStart + offset_into_d263 + 4 + 1); track_info->profile = APar_read8(isofile, parsedAtoms[track_level_atom].AtomicStart + offset_into_d263 + 4 + 2); // possible 'bitr' bitrate box afterwards return; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,344
ImageMagick
078e9692a257e7a8aa36ccc750927f9617923061
static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 #define ThrowRLEException(exception,message) \ { \ if (colormap != (unsigned char *) NULL) \ colormap=(unsigned char *) RelinquishMagickMemory(colormap); \ if (pixel_info != (MemoryInfo *) NULL) \ pixel_info=RelinquishVirtualMemory(pixel_info); \ ThrowReaderException((exception),(message)); \ } char magick[12]; Image *image; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, number_planes_filled, one, pixel_info_length; ssize_t count, offset, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Determine if this a RLE file. */ colormap=(unsigned char *) NULL; pixel_info=(MemoryInfo *) NULL; count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,"\122\314",2) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Read image header. */ image->page.x=(ssize_t) ReadBlobLSBShort(image); image->page.y=(ssize_t) ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 22) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || ((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (image->alpha_trait != UndefinedPixelTrait) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; if ((GetBlobSize(image) == 0) || ((((MagickSizeType) number_pixels* number_planes*bits_per_pixel/8)/GetBlobSize(image)) > 254.0)) ThrowRLEException(CorruptImageError,"InsufficientImageDataInFile") if (((MagickSizeType) number_colormaps*map_length) > GetBlobSize(image)) ThrowRLEException(CorruptImageError,"InsufficientImageDataInFile") if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) { *p++=(unsigned char) ScaleQuantumToChar(ScaleShortToQuantum( ReadBlobLSBShort(image))); if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate RLE pixels. */ number_planes_filled=(number_planes % 2 == 0) ? number_planes : number_planes+1; if ((number_pixels*number_planes_filled) != (size_t) (number_pixels* number_planes_filled)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* MagickMax(number_planes_filled,4)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info_length=image->columns*image->rows* MagickMax(number_planes_filled,4); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,pixel_info_length); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->alpha_trait == UndefinedPixelTrait) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane); operand++; if ((offset < 0) || ((offset+operand*number_planes) > (ssize_t) pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane); operand++; if ((offset < 0) || ((offset+operand*number_planes) > (ssize_t) pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { ValidateColormapValue(image,(ssize_t) (*p & mask),&index,exception); *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { ValidateColormapValue(image,(ssize_t) (x*map_length+ (*p & mask)),&index,exception); *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->alpha_trait == UndefinedPixelTrait) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,(Quantum) *p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) index].red),q); ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) index].green),q); ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) index].blue),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,"\122\314",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,"\122\314",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,721
unixODBC
45ef78e037f578b15fc58938a3a3251655e71d6f#diff-d52750c7ba4e594410438569d8e2963aL24
static int ExecuteSQL( SQLHDBC hDbc, char *szSQL, char cDelimiter, int bColumnNames, int bHTMLTable ) { SQLHSTMT hStmt; SQLTCHAR szSepLine[32001]; SQLTCHAR szUcSQL[32001]; SQLSMALLINT cols; SQLINTEGER ret; SQLLEN nRows = 0; szSepLine[ 0 ] = 0; ansi_to_unicode( szSQL, szUcSQL ); /**************************** * EXECUTE SQL ***************************/ if ( SQLAllocStmt( hDbc, &hStmt ) != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 ); fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocStmt\n" ); return 0; } if ( buseED ) { ret = SQLExecDirect( hStmt, szUcSQL, SQL_NTS ); if ( ret == SQL_NO_DATA ) { fprintf( stderr, "[ISQL]INFO: SQLExecDirect returned SQL_NO_DATA\n" ); } else if ( ret == SQL_SUCCESS_WITH_INFO ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]INFO: SQLExecDirect returned SQL_SUCCESS_WITH_INFO\n" ); } else if ( ret != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLExecDirect\n" ); SQLFreeStmt( hStmt, SQL_DROP ); free(szSepLine); return 0; } } else { if ( SQLPrepare( hStmt, szUcSQL, SQL_NTS ) != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLPrepare\n" ); SQLFreeStmt( hStmt, SQL_DROP ); return 0; } ret = SQLExecute( hStmt ); if ( ret == SQL_NO_DATA ) { fprintf( stderr, "[ISQL]INFO: SQLExecute returned SQL_NO_DATA\n" ); } else if ( ret == SQL_SUCCESS_WITH_INFO ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]INFO: SQLExecute returned SQL_SUCCESS_WITH_INFO\n" ); } else if ( ret != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLExecute\n" ); SQLFreeStmt( hStmt, SQL_DROP ); return 0; } } do { /* * check to see if it has generated a result set */ if ( SQLNumResultCols( hStmt, &cols ) != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLNumResultCols\n" ); SQLFreeStmt( hStmt, SQL_DROP ); return 0; } if ( cols > 0 ) { /**************************** * WRITE HEADER ***************************/ if ( bHTMLTable ) WriteHeaderHTMLTable( hStmt ); else if ( cDelimiter == 0 ) UWriteHeaderNormal( hStmt, szSepLine ); else if ( cDelimiter && bColumnNames ) WriteHeaderDelimited( hStmt, cDelimiter ); /**************************** * WRITE BODY ***************************/ if ( bHTMLTable ) WriteBodyHTMLTable( hStmt ); else if ( cDelimiter == 0 ) nRows = WriteBodyNormal( hStmt ); else WriteBodyDelimited( hStmt, cDelimiter ); } /**************************** * WRITE FOOTER ***************************/ if ( bHTMLTable ) WriteFooterHTMLTable( hStmt ); else if ( cDelimiter == 0 ) UWriteFooterNormal( hStmt, szSepLine, nRows ); } while ( SQL_SUCCEEDED( SQLMoreResults( hStmt ))); /**************************** * CLEANUP ***************************/ SQLFreeStmt( hStmt, SQL_DROP ); return 1; }
1
CVE-2018-7485
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).
712
abrt
d6e2f6f128cef4c21cb80941ae674c9842681aa7
int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Because of #1211835 and #1126850 */ #if 0 /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } #endif /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s'", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size); } return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,468
linux
28d76df18f0ad5bcf5fa48510b225f0ed262a99b
mptctl_probe(struct pci_dev *pdev, const struct pci_device_id *id) { MPT_ADAPTER *ioc = pci_get_drvdata(pdev); mutex_init(&ioc->ioctl_cmds.mutex); init_completion(&ioc->ioctl_cmds.done); return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,156
openjpeg
b2072402b7e14d22bba6fb8cde2a1e9996e9a919
opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params) { png_structp png = NULL; png_infop info = NULL; double gamma; int bit_depth, interlace_type, compression_type, filter_type; OPJ_UINT32 i; png_uint_32 width, height = 0U; int color_type; FILE *reader = NULL; OPJ_BYTE** rows = NULL; OPJ_INT32* row32s = NULL; /* j2k: */ opj_image_t *image = NULL; opj_image_cmptparm_t cmptparm[4]; OPJ_UINT32 nr_comp; OPJ_BYTE sigbuf[8]; convert_XXx32s_C1R cvtXXTo32s = NULL; convert_32s_CXPX cvtCxToPx = NULL; OPJ_INT32* planes[4]; if ((reader = fopen(read_idf, "rb")) == NULL) { fprintf(stderr, "pngtoimage: can not open %s\n", read_idf); return NULL; } if (fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0) { fprintf(stderr, "pngtoimage: %s is no valid PNG file\n", read_idf); goto fin; } if ((png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)) == NULL) { goto fin; } if ((info = png_create_info_struct(png)) == NULL) { goto fin; } if (setjmp(png_jmpbuf(png))) { goto fin; } png_init_io(png, reader); png_set_sig_bytes(png, MAGIC_SIZE); png_read_info(png, info); if (png_get_IHDR(png, info, &width, &height, &bit_depth, &color_type, &interlace_type, &compression_type, &filter_type) == 0) { goto fin; } /* png_set_expand(): * expand paletted images to RGB, expand grayscale images of * less than 8-bit depth to 8-bit depth, and expand tRNS chunks * to alpha channels. */ if (color_type == PNG_COLOR_TYPE_PALETTE) { png_set_expand(png); } if (png_get_valid(png, info, PNG_INFO_tRNS)) { png_set_expand(png); } /* We might wan't to expand background */ /* if(png_get_valid(png, info, PNG_INFO_bKGD)) { png_color_16p bgnd; png_get_bKGD(png, info, &bgnd); png_set_background(png, bgnd, PNG_BACKGROUND_GAMMA_FILE, 1, 1.0); } */ if (!png_get_gAMA(png, info, &gamma)) { gamma = 1.0; } /* we're not displaying but converting, screen gamma == 1.0 */ png_set_gamma(png, 1.0, gamma); png_read_update_info(png, info); color_type = png_get_color_type(png, info); switch (color_type) { case PNG_COLOR_TYPE_GRAY: nr_comp = 1; break; case PNG_COLOR_TYPE_GRAY_ALPHA: nr_comp = 2; break; case PNG_COLOR_TYPE_RGB: nr_comp = 3; break; case PNG_COLOR_TYPE_RGB_ALPHA: nr_comp = 4; break; default: fprintf(stderr, "pngtoimage: colortype %d is not supported\n", color_type); goto fin; } cvtCxToPx = convert_32s_CXPX_LUT[nr_comp]; bit_depth = png_get_bit_depth(png, info); switch (bit_depth) { case 1: case 2: case 4: case 8: cvtXXTo32s = convert_XXu32s_C1R_LUT[bit_depth]; break; case 16: /* 16 bpp is specific to PNG */ cvtXXTo32s = convert_16u32s_C1R; break; default: fprintf(stderr, "pngtoimage: bit depth %d is not supported\n", bit_depth); goto fin; } rows = (OPJ_BYTE**)calloc(height + 1, sizeof(OPJ_BYTE*)); if (rows == NULL) { fprintf(stderr, "pngtoimage: memory out\n"); goto fin; } for (i = 0; i < height; ++i) { rows[i] = (OPJ_BYTE*)malloc(png_get_rowbytes(png, info)); if (rows[i] == NULL) { fprintf(stderr, "pngtoimage: memory out\n"); goto fin; } } png_read_image(png, rows); /* Create image */ memset(cmptparm, 0, sizeof(cmptparm)); for (i = 0; i < nr_comp; ++i) { cmptparm[i].prec = (OPJ_UINT32)bit_depth; /* bits_per_pixel: 8 or 16 */ cmptparm[i].bpp = (OPJ_UINT32)bit_depth; cmptparm[i].sgnd = 0; cmptparm[i].dx = (OPJ_UINT32)params->subsampling_dx; cmptparm[i].dy = (OPJ_UINT32)params->subsampling_dy; cmptparm[i].w = (OPJ_UINT32)width; cmptparm[i].h = (OPJ_UINT32)height; } image = opj_image_create(nr_comp, &cmptparm[0], (nr_comp > 2U) ? OPJ_CLRSPC_SRGB : OPJ_CLRSPC_GRAY); if (image == NULL) { goto fin; } image->x0 = (OPJ_UINT32)params->image_offset_x0; image->y0 = (OPJ_UINT32)params->image_offset_y0; image->x1 = (OPJ_UINT32)(image->x0 + (width - 1) * (OPJ_UINT32) params->subsampling_dx + 1 + image->x0); image->y1 = (OPJ_UINT32)(image->y0 + (height - 1) * (OPJ_UINT32) params->subsampling_dy + 1 + image->y0); row32s = (OPJ_INT32 *)malloc((size_t)width * nr_comp * sizeof(OPJ_INT32)); if (row32s == NULL) { goto fin; } /* Set alpha channel */ image->comps[nr_comp - 1U].alpha = 1U - (nr_comp & 1U); for (i = 0; i < nr_comp; i++) { planes[i] = image->comps[i].data; } for (i = 0; i < height; ++i) { cvtXXTo32s(rows[i], row32s, (OPJ_SIZE_T)width * nr_comp); cvtCxToPx(row32s, planes, width); planes[0] += width; planes[1] += width; planes[2] += width; planes[3] += width; } fin: if (rows) { for (i = 0; i < height; ++i) if (rows[i]) { free(rows[i]); } free(rows); } if (row32s) { free(row32s); } if (png) { png_destroy_read_struct(&png, &info, NULL); } fclose(reader); return image; }/* pngtoimage() */
1
CVE-2020-27823
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).
2,012
virglrenderer
93761787b29f37fa627dea9082cdfc1a1ec608d6
int vrend_create_vertex_elements_state(struct vrend_context *ctx, uint32_t handle, unsigned num_elements, const struct pipe_vertex_element *elements) { struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array); const struct util_format_description *desc; GLenum type; int i; uint32_t ret_handle; if (!v) return ENOMEM; if (num_elements > PIPE_MAX_ATTRIBS) return EINVAL; v->count = num_elements; for (i = 0; i < num_elements; i++) { memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element)); desc = util_format_description(elements[i].src_format); if (!desc) { FREE(v); return EINVAL; } type = GL_FALSE; if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) { if (desc->channel[0].size == 32) type = GL_FLOAT; else if (desc->channel[0].size == 64) type = GL_DOUBLE; else if (desc->channel[0].size == 16) type = GL_HALF_FLOAT; } else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 8) type = GL_UNSIGNED_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 8) type = GL_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 16) type = GL_UNSIGNED_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 16) type = GL_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 32) type = GL_UNSIGNED_INT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 32) type = GL_INT; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM) type = GL_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM) type = GL_UNSIGNED_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) type = GL_UNSIGNED_INT_10F_11F_11F_REV; if (type == GL_FALSE) { report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format); FREE(v); return EINVAL; } v->elements[i].type = type; if (desc->channel[0].normalized) v->elements[i].norm = GL_TRUE; if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z) v->elements[i].nr_chan = GL_BGRA; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) v->elements[i].nr_chan = 3; else v->elements[i].nr_chan = desc->nr_channels; } if (vrend_state.have_vertex_attrib_binding) { glGenVertexArrays(1, &v->id); glBindVertexArray(v->id); for (i = 0; i < num_elements; i++) { struct vrend_vertex_element *ve = &v->elements[i]; if (util_format_is_pure_integer(ve->base.src_format)) glVertexAttribIFormat(i, ve->nr_chan, ve->type, ve->base.src_offset); else glVertexAttribFormat(i, ve->nr_chan, ve->type, ve->norm, ve->base.src_offset); glVertexAttribBinding(i, ve->base.vertex_buffer_index); glVertexBindingDivisor(i, ve->base.instance_divisor); glEnableVertexAttribArray(i); } } ret_handle = vrend_renderer_object_insert(ctx, v, sizeof(struct vrend_vertex_element), handle, VIRGL_OBJECT_VERTEX_ELEMENTS); if (!ret_handle) { FREE(v); return ENOMEM; } return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,458
Espruino
ce1924193862d58cb43d3d4d9dada710a8361b89
bool jsvIsSimpleInt(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_INTEGER; } // is just a very basic integer value
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,438
linux-2.6
16175a796d061833aacfbd9672235f2d2725df65
static void vmx_fpu_activate(struct kvm_vcpu *vcpu) { if (vcpu->fpu_active) return; vcpu->fpu_active = 1; vmcs_clear_bits(GUEST_CR0, X86_CR0_TS); if (vcpu->arch.cr0 & X86_CR0_TS) vmcs_set_bits(GUEST_CR0, X86_CR0_TS); update_exception_bitmap(vcpu); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,886
Chrome
c9450503817e3575a8acb049371b592863e6d555
void MetalayerMode::OnDisable() { CommonPaletteTool::OnDisable(); Shell::Get()->highlighter_controller()->SetEnabled(false); activated_via_button_ = false; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,240
linux
13bf9fbff0e5e099e2b6f003a0ab8ae145436309
nfs3svc_decode_writeargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_writeargs *args) { unsigned int len, v, hdr, dlen; u32 max_blocksize = svc_max_payload(rqstp); struct kvec *head = rqstp->rq_arg.head; struct kvec *tail = rqstp->rq_arg.tail; p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->offset); args->count = ntohl(*p++); args->stable = ntohl(*p++); len = args->len = ntohl(*p++); /* * The count must equal the amount of data passed. */ if (args->count != args->len) return 0; /* * Check to make sure that we got the right number of * bytes. */ hdr = (void*)p - head->iov_base; dlen = head->iov_len + rqstp->rq_arg.page_len + tail->iov_len - hdr; /* * Round the length of the data which was specified up to * the next multiple of XDR units and then compare that * against the length which was actually received. * Note that when RPCSEC/GSS (for example) is used, the * data buffer can be padded so dlen might be larger * than required. It must never be smaller. */ if (dlen < XDR_QUADLEN(len)*4) return 0; if (args->count > max_blocksize) { args->count = max_blocksize; len = args->len = max_blocksize; } rqstp->rq_vec[0].iov_base = (void*)p; rqstp->rq_vec[0].iov_len = head->iov_len - hdr; v = 0; while (len > rqstp->rq_vec[v].iov_len) { len -= rqstp->rq_vec[v].iov_len; v++; rqstp->rq_vec[v].iov_base = page_address(rqstp->rq_pages[v]); rqstp->rq_vec[v].iov_len = PAGE_SIZE; } rqstp->rq_vec[v].iov_len = len; args->vlen = v + 1; return 1; }
1
CVE-2017-7895
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333] Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
6,217
linux
0143fc5e9f6f5aad4764801015bc8d4b4a278200
static struct dentry *udf_fh_to_parent(struct super_block *sb, struct fid *fid, int fh_len, int fh_type) { if (fh_len != 5 || fh_type != FILEID_UDF_WITH_PARENT) return NULL; return udf_nfs_get_inode(sb, fid->udf.parent_block, fid->udf.parent_partref, fid->udf.parent_generation); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,304
php-src
7245bff300d3fa8bacbef7897ff080a6f1c23eba?w=1
SPL_METHOD(SplFileObject, fread) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) { return; } if (length <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(length + 1); Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; }
1
CVE-2016-5770
CWE-190
Integer Overflow or Wraparound
The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number.
Phase: Requirements Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol. Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. If possible, choose a language or compiler that performs automatic bounds checking. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Use libraries or frameworks that make it easier to handle numbers without unexpected consequences. Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106] Phase: Implementation Strategy: Input Validation Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range. Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values. Phase: Implementation Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7] Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation. Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Phase: Implementation Strategy: Compilation or Build Hardening Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system.
139
ImageMagick6
9eda4b36a8695e4a0cd27bea28b9c173c68a01ec
static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=(size_t) ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) { DestroyJNG(NULL,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError,"CorruptImage"); } p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) { DestroyJNG(NULL,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } for ( ; i < (ssize_t) length; i++) chunk[i]='\0'; p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(png_uint_32)mng_get_long(p); jng_height=(png_uint_32)mng_get_long(&p[4]); if ((jng_width == 0) || (jng_height == 0)) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); } jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (jng_width > 65535 || jng_height > 65535 || (long) jng_width > GetMagickResourceLimit(WidthResource) || (long) jng_height > GetMagickResourceLimit(HeightResource)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width or height too large: (%lu x %lu)", (long) jng_width, (long) jng_height); DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) { DestroyJNG(NULL,NULL,NULL,&alpha_image,&alpha_image_info); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { jng_image=DestroyImageList(jng_image); DestroyJNG(NULL,NULL,NULL,&alpha_image,&alpha_image_info); InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if ((s == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; (void) memcpy(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if ((s == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange-GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,764
php-src
28a6ed9f9a36b9c517e4a8a429baf4dd382fc5d5?w=1
SPL_METHOD(SplDoublyLinkedList, prev) { spl_dllist_object *intern = Z_SPLDLLIST_P(getThis()); if (zend_parse_parameters_none() == FAILURE) { return; } spl_dllist_it_helper_move_forward(&intern->traverse_pointer, &intern->traverse_position, intern->llist, intern->flags ^ SPL_DLLIST_IT_LIFO); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,449
Android
37c88107679d36c419572732b4af6e18bb2f7dce
const bt_interface_t* bluetooth__get_bluetooth_interface () { /* fixme -- add property to disable bt interface ? */ return &bluetoothInterface; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,280
Chrome
c995d4fe5e96f4d6d4a88b7867279b08e72d2579
bool ChromeContentBrowserClient::IsDataSaverEnabled( content::BrowserContext* browser_context) { data_reduction_proxy::DataReductionProxySettings* data_reduction_proxy_settings = DataReductionProxyChromeSettingsFactory::GetForBrowserContext( browser_context); return data_reduction_proxy_settings && data_reduction_proxy_settings->IsDataSaverEnabledByUser(); }
1
CVE-2016-5199
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,095
linux
49d31c2f389acfe83417083e1208422b4091cd9e
int __fsnotify_parent(const struct path *path, struct dentry *dentry, __u32 mask) { struct dentry *parent; struct inode *p_inode; int ret = 0; if (!dentry) dentry = path->dentry; if (!(dentry->d_flags & DCACHE_FSNOTIFY_PARENT_WATCHED)) return 0; parent = dget_parent(dentry); p_inode = parent->d_inode; if (unlikely(!fsnotify_inode_watches_children(p_inode))) __fsnotify_update_child_dentry_flags(p_inode); else if (p_inode->i_fsnotify_mask & mask) { /* we are notifying a parent so come up with the new mask which * specifies these are events which came from a child. */ mask |= FS_EVENT_ON_CHILD; if (path) ret = fsnotify(p_inode, mask, path, FSNOTIFY_EVENT_PATH, dentry->d_name.name, 0); else ret = fsnotify(p_inode, mask, dentry->d_inode, FSNOTIFY_EVENT_INODE, dentry->d_name.name, 0); } dput(parent); return ret; }
1
CVE-2017-7533
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The product contains a concurrent code sequence that requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence operating concurrently.
Phase: Architecture and Design In languages that support it, use synchronization primitives. Only wrap these around critical code to minimize the impact on performance. Phase: Architecture and Design Use thread-safe capabilities such as the data access abstraction in Spring. Phase: Architecture and Design Minimize the usage of shared resources in order to remove as much complexity as possible from the control flow and to reduce the likelihood of unexpected conditions occurring. Additionally, this will minimize the amount of synchronization necessary and may even help to reduce the likelihood of a denial of service where an attacker may be able to repeatedly trigger a critical section (CWE-400). Phase: Implementation When using multithreading and operating on shared variables, only use thread-safe functions. Phase: Implementation Use atomic operations on shared variables. Be wary of innocent-looking constructs such as "x++". This may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read, followed by a computation, followed by a write. Phase: Implementation Use a mutex if available, but be sure to avoid related weaknesses such as CWE-412. Phase: Implementation Avoid double-checked locking (CWE-609) and other implementation errors that arise when trying to avoid the overhead of synchronization. Phase: Implementation Disable interrupts or signals over critical parts of the code, but also make sure that the code does not go into a large or infinite loop. Phase: Implementation Use the volatile type modifier for critical variables to avoid unexpected compiler optimization or reordering. This does not necessarily solve the synchronization problem, but it can help. Phases: Architecture and Design; Operation Strategy: Environment Hardening Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations
3,433
linux
ab676b7d6fbf4b294bf198fb27ade5b0e865c7ce
static void show_smap_vma_flags(struct seq_file *m, struct vm_area_struct *vma) { /* * Don't forget to update Documentation/ on changes. */ static const char mnemonics[BITS_PER_LONG][2] = { /* * In case if we meet a flag we don't know about. */ [0 ... (BITS_PER_LONG-1)] = "??", [ilog2(VM_READ)] = "rd", [ilog2(VM_WRITE)] = "wr", [ilog2(VM_EXEC)] = "ex", [ilog2(VM_SHARED)] = "sh", [ilog2(VM_MAYREAD)] = "mr", [ilog2(VM_MAYWRITE)] = "mw", [ilog2(VM_MAYEXEC)] = "me", [ilog2(VM_MAYSHARE)] = "ms", [ilog2(VM_GROWSDOWN)] = "gd", [ilog2(VM_PFNMAP)] = "pf", [ilog2(VM_DENYWRITE)] = "dw", #ifdef CONFIG_X86_INTEL_MPX [ilog2(VM_MPX)] = "mp", #endif [ilog2(VM_LOCKED)] = "lo", [ilog2(VM_IO)] = "io", [ilog2(VM_SEQ_READ)] = "sr", [ilog2(VM_RAND_READ)] = "rr", [ilog2(VM_DONTCOPY)] = "dc", [ilog2(VM_DONTEXPAND)] = "de", [ilog2(VM_ACCOUNT)] = "ac", [ilog2(VM_NORESERVE)] = "nr", [ilog2(VM_HUGETLB)] = "ht", [ilog2(VM_ARCH_1)] = "ar", [ilog2(VM_DONTDUMP)] = "dd", #ifdef CONFIG_MEM_SOFT_DIRTY [ilog2(VM_SOFTDIRTY)] = "sd", #endif [ilog2(VM_MIXEDMAP)] = "mm", [ilog2(VM_HUGEPAGE)] = "hg", [ilog2(VM_NOHUGEPAGE)] = "nh", [ilog2(VM_MERGEABLE)] = "mg", }; size_t i; seq_puts(m, "VmFlags: "); for (i = 0; i < BITS_PER_LONG; i++) { if (vma->vm_flags & (1UL << i)) { seq_printf(m, "%c%c ", mnemonics[i][0], mnemonics[i][1]); } } seq_putc(m, '\n'); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,170
samba
9427806f7298d71bd7edfbdda7506ec63f15dda1
static int ldb_wildcard_compare(struct ldb_context *ldb, const struct ldb_parse_tree *tree, const struct ldb_val value, bool *matched) { const struct ldb_schema_attribute *a; struct ldb_val val; struct ldb_val cnk; struct ldb_val *chunk; uint8_t *save_p = NULL; unsigned int c = 0; a = ldb_schema_attribute_by_name(ldb, tree->u.substring.attr); if (!a) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } if (tree->u.substring.chunks == NULL) { *matched = false; return LDB_SUCCESS; } if (a->syntax->canonicalise_fn(ldb, ldb, &value, &val) != 0) { return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX; } save_p = val.data; cnk.data = NULL; if ( ! tree->u.substring.start_with_wildcard ) { chunk = tree->u.substring.chunks[c]; if (a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* This deals with wildcard prefix searches on binary attributes (eg objectGUID) */ if (cnk.length > val.length) { goto mismatch; } /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } if (memcmp((char *)val.data, (char *)cnk.data, cnk.length) != 0) goto mismatch; val.length -= cnk.length; val.data += cnk.length; c++; talloc_free(cnk.data); cnk.data = NULL; } while (tree->u.substring.chunks[c]) { uint8_t *p; chunk = tree->u.substring.chunks[c]; if(a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch; /* * Empty strings are returned as length 0. Ensure * we can cope with this. */ if (cnk.length == 0) { goto mismatch; } /* * Values might be binary blobs. Don't use string * search, but memory search instead. */ p = memmem((const void *)val.data,val.length, (const void *)cnk.data, cnk.length); if (p == NULL) goto mismatch; /* * At this point we know cnk.length <= val.length as * otherwise there could be no match */ if ( (! tree->u.substring.chunks[c + 1]) && (! tree->u.substring.end_with_wildcard) ) { uint8_t *g; uint8_t *end = val.data + val.length; do { /* greedy */ /* * haystack is a valid pointer in val * because the memmem() can only * succeed if the needle (cnk.length) * is <= haystacklen * * p will be a pointer at least * cnk.length from the end of haystack */ uint8_t *haystack = p + cnk.length; size_t haystacklen = end - (haystack); g = memmem(haystack, haystacklen, (const uint8_t *)cnk.data, cnk.length); if (g) p = g; } while(g); } val.length = val.length - (p - (uint8_t *)(val.data)) - cnk.length; val.data = (uint8_t *)(p + cnk.length); c++; talloc_free(cnk.data); cnk.data = NULL; } /* last chunk may not have reached end of string */ if ( (! tree->u.substring.end_with_wildcard) && (*(val.data) != 0) ) goto mismatch; talloc_free(save_p); *matched = true; return LDB_SUCCESS; mismatch: *matched = false; talloc_free(save_p); talloc_free(cnk.data); return LDB_SUCCESS; }
1
CVE-2019-3824
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,743
linux
717adfdaf14704fd3ec7fa2c04520c0723247eac
static ssize_t hid_debug_events_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos) { struct hid_debug_list *list = file->private_data; int ret = 0, len; DECLARE_WAITQUEUE(wait, current); mutex_lock(&list->read_mutex); while (ret == 0) { if (list->head == list->tail) { add_wait_queue(&list->hdev->debug_wait, &wait); set_current_state(TASK_INTERRUPTIBLE); while (list->head == list->tail) { if (file->f_flags & O_NONBLOCK) { ret = -EAGAIN; break; } if (signal_pending(current)) { ret = -ERESTARTSYS; break; } if (!list->hdev || !list->hdev->debug) { ret = -EIO; set_current_state(TASK_RUNNING); goto out; } /* allow O_NONBLOCK from other threads */ mutex_unlock(&list->read_mutex); schedule(); mutex_lock(&list->read_mutex); set_current_state(TASK_INTERRUPTIBLE); } set_current_state(TASK_RUNNING); remove_wait_queue(&list->hdev->debug_wait, &wait); } if (ret) goto out; /* pass the ringbuffer contents to userspace */ copy_rest: if (list->tail == list->head) goto out; if (list->tail > list->head) { len = list->tail - list->head; if (copy_to_user(buffer + ret, &list->hid_debug_buf[list->head], len)) { ret = -EFAULT; goto out; } ret += len; list->head += len; } else { len = HID_DEBUG_BUFSIZE - list->head; if (copy_to_user(buffer, &list->hid_debug_buf[list->head], len)) { ret = -EFAULT; goto out; } list->head = 0; ret += len; goto copy_rest; } } out: mutex_unlock(&list->read_mutex); return ret; }
1
CVE-2018-9516
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
9,932
linux
c919a3069c775c1c876bec55e00b2305d5125caa
static int gs_can_open(struct net_device *netdev) { struct gs_can *dev = netdev_priv(netdev); struct gs_usb *parent = dev->parent; int rc, i; struct gs_device_mode *dm; u32 ctrlmode; rc = open_candev(netdev); if (rc) return rc; if (atomic_add_return(1, &parent->active_channels) == 1) { for (i = 0; i < GS_MAX_RX_URBS; i++) { struct urb *urb; u8 *buf; /* alloc rx urb */ urb = usb_alloc_urb(0, GFP_KERNEL); if (!urb) return -ENOMEM; /* alloc rx buffer */ buf = usb_alloc_coherent(dev->udev, sizeof(struct gs_host_frame), GFP_KERNEL, &urb->transfer_dma); if (!buf) { netdev_err(netdev, "No memory left for USB buffer\n"); usb_free_urb(urb); return -ENOMEM; } /* fill, anchor, and submit rx urb */ usb_fill_bulk_urb(urb, dev->udev, usb_rcvbulkpipe(dev->udev, GSUSB_ENDPOINT_IN), buf, sizeof(struct gs_host_frame), gs_usb_receive_bulk_callback, parent); urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; usb_anchor_urb(urb, &parent->rx_submitted); rc = usb_submit_urb(urb, GFP_KERNEL); if (rc) { if (rc == -ENODEV) netif_device_detach(dev->netdev); netdev_err(netdev, "usb_submit failed (err=%d)\n", rc); usb_unanchor_urb(urb); break; } /* Drop reference, * USB core will take care of freeing it */ usb_free_urb(urb); } } dm = kmalloc(sizeof(*dm), GFP_KERNEL); if (!dm) return -ENOMEM; /* flags */ ctrlmode = dev->can.ctrlmode; dm->flags = 0; if (ctrlmode & CAN_CTRLMODE_LOOPBACK) dm->flags |= GS_CAN_MODE_LOOP_BACK; else if (ctrlmode & CAN_CTRLMODE_LISTENONLY) dm->flags |= GS_CAN_MODE_LISTEN_ONLY; /* Controller is not allowed to retry TX * this mode is unavailable on atmels uc3c hardware */ if (ctrlmode & CAN_CTRLMODE_ONE_SHOT) dm->flags |= GS_CAN_MODE_ONE_SHOT; if (ctrlmode & CAN_CTRLMODE_3_SAMPLES) dm->flags |= GS_CAN_MODE_TRIPLE_SAMPLE; /* finally start device */ dm->mode = GS_CAN_MODE_START; rc = usb_control_msg(interface_to_usbdev(dev->iface), usb_sndctrlpipe(interface_to_usbdev(dev->iface), 0), GS_USB_BREQ_MODE, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE, dev->channel, 0, dm, sizeof(*dm), 1000); if (rc < 0) { netdev_err(netdev, "Couldn't start device (err=%d)\n", rc); kfree(dm); return rc; } kfree(dm); dev->can.state = CAN_STATE_ERROR_ACTIVE; if (!(dev->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)) netif_start_queue(netdev); return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,516
linux
48fb6f4db940e92cfb16cd878cddd59ea6120d06
get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, int rw) { unsigned long address = (unsigned long)uaddr; struct mm_struct *mm = current->mm; struct page *page, *tail; struct address_space *mapping; int err, ro = 0; /* * The futex address must be "naturally" aligned. */ key->both.offset = address % PAGE_SIZE; if (unlikely((address % sizeof(u32)) != 0)) return -EINVAL; address -= key->both.offset; if (unlikely(!access_ok(rw, uaddr, sizeof(u32)))) return -EFAULT; if (unlikely(should_fail_futex(fshared))) return -EFAULT; /* * PROCESS_PRIVATE futexes are fast. * As the mm cannot disappear under us and the 'key' only needs * virtual address, we dont even have to find the underlying vma. * Note : We do have to check 'uaddr' is a valid user address, * but access_ok() should be faster than find_vma() */ if (!fshared) { key->private.mm = mm; key->private.address = address; get_futex_key_refs(key); /* implies smp_mb(); (B) */ return 0; } again: /* Ignore any VERIFY_READ mapping (futex common case) */ if (unlikely(should_fail_futex(fshared))) return -EFAULT; err = get_user_pages_fast(address, 1, 1, &page); /* * If write access is not required (eg. FUTEX_WAIT), try * and get read-only access. */ if (err == -EFAULT && rw == VERIFY_READ) { err = get_user_pages_fast(address, 1, 0, &page); ro = 1; } if (err < 0) return err; else err = 0; /* * The treatment of mapping from this point on is critical. The page * lock protects many things but in this context the page lock * stabilizes mapping, prevents inode freeing in the shared * file-backed region case and guards against movement to swap cache. * * Strictly speaking the page lock is not needed in all cases being * considered here and page lock forces unnecessarily serialization * From this point on, mapping will be re-verified if necessary and * page lock will be acquired only if it is unavoidable * * Mapping checks require the head page for any compound page so the * head page and mapping is looked up now. For anonymous pages, it * does not matter if the page splits in the future as the key is * based on the address. For filesystem-backed pages, the tail is * required as the index of the page determines the key. For * base pages, there is no tail page and tail == page. */ tail = page; page = compound_head(page); mapping = READ_ONCE(page->mapping); /* * If page->mapping is NULL, then it cannot be a PageAnon * page; but it might be the ZERO_PAGE or in the gate area or * in a special mapping (all cases which we are happy to fail); * or it may have been a good file page when get_user_pages_fast * found it, but truncated or holepunched or subjected to * invalidate_complete_page2 before we got the page lock (also * cases which we are happy to fail). And we hold a reference, * so refcount care in invalidate_complete_page's remove_mapping * prevents drop_caches from setting mapping to NULL beneath us. * * The case we do have to guard against is when memory pressure made * shmem_writepage move it from filecache to swapcache beneath us: * an unlikely race, but we do need to retry for page->mapping. */ if (unlikely(!mapping)) { int shmem_swizzled; /* * Page lock is required to identify which special case above * applies. If this is really a shmem page then the page lock * will prevent unexpected transitions. */ lock_page(page); shmem_swizzled = PageSwapCache(page) || page->mapping; unlock_page(page); put_page(page); if (shmem_swizzled) goto again; return -EFAULT; } /* * Private mappings are handled in a simple way. * * If the futex key is stored on an anonymous page, then the associated * object is the mm which is implicitly pinned by the calling process. * * NOTE: When userspace waits on a MAP_SHARED mapping, even if * it's a read-only handle, it's expected that futexes attach to * the object not the particular process. */ if (PageAnon(page)) { /* * A RO anonymous page will never change and thus doesn't make * sense for futex operations. */ if (unlikely(should_fail_futex(fshared)) || ro) { err = -EFAULT; goto out; } key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */ key->private.mm = mm; key->private.address = address; get_futex_key_refs(key); /* implies smp_mb(); (B) */ } else { struct inode *inode; /* * The associated futex object in this case is the inode and * the page->mapping must be traversed. Ordinarily this should * be stabilised under page lock but it's not strictly * necessary in this case as we just want to pin the inode, not * update the radix tree or anything like that. * * The RCU read lock is taken as the inode is finally freed * under RCU. If the mapping still matches expectations then the * mapping->host can be safely accessed as being a valid inode. */ rcu_read_lock(); if (READ_ONCE(page->mapping) != mapping) { rcu_read_unlock(); put_page(page); goto again; } inode = READ_ONCE(mapping->host); if (!inode) { rcu_read_unlock(); put_page(page); goto again; } /* * Take a reference unless it is about to be freed. Previously * this reference was taken by ihold under the page lock * pinning the inode in place so i_lock was unnecessary. The * only way for this check to fail is if the inode was * truncated in parallel so warn for now if this happens. * * We are not calling into get_futex_key_refs() in file-backed * cases, therefore a successful atomic_inc return below will * guarantee that get_futex_key() will still imply smp_mb(); (B). */ if (WARN_ON_ONCE(!atomic_inc_not_zero(&inode->i_count))) { rcu_read_unlock(); put_page(page); goto again; } /* Should be impossible but lets be paranoid for now */ if (WARN_ON_ONCE(inode->i_mapping != mapping)) { err = -EFAULT; rcu_read_unlock(); iput(inode); goto out; } key->both.offset |= FUT_OFF_INODE; /* inode-based key */ key->shared.inode = inode; key->shared.pgoff = basepage_index(tail); rcu_read_unlock(); } out: put_page(page); return err; }
1
CVE-2018-9422
CWE-416
Use After Free
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
Phase: Architecture and Design Strategy: Language Selection Choose a language that provides automatic memory management. Phase: Implementation Strategy: Attack Surface Reduction When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy. Effectiveness: Defense in Depth Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution.
8,783
libavif
0a8e7244d494ae98e9756355dfbfb6697ded2ff9
static avifBool avifParseCleanApertureBoxProperty(avifProperty * prop, const uint8_t * raw, size_t rawLen) { BEGIN_STREAM(s, raw, rawLen); avifCleanApertureBox * clap = &prop->u.clap; CHECK(avifROStreamReadU32(&s, &clap->widthN)); // unsigned int(32) cleanApertureWidthN; CHECK(avifROStreamReadU32(&s, &clap->widthD)); // unsigned int(32) cleanApertureWidthD; CHECK(avifROStreamReadU32(&s, &clap->heightN)); // unsigned int(32) cleanApertureHeightN; CHECK(avifROStreamReadU32(&s, &clap->heightD)); // unsigned int(32) cleanApertureHeightD; CHECK(avifROStreamReadU32(&s, &clap->horizOffN)); // unsigned int(32) horizOffN; CHECK(avifROStreamReadU32(&s, &clap->horizOffD)); // unsigned int(32) horizOffD; CHECK(avifROStreamReadU32(&s, &clap->vertOffN)); // unsigned int(32) vertOffN; CHECK(avifROStreamReadU32(&s, &clap->vertOffD)); // unsigned int(32) vertOffD; return AVIF_TRUE; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,622
krb5
d1f707024f1d0af6e54a18885322d70fa15ec4d3
krb5_ldap_create_password_policy(krb5_context context, osa_policy_ent_t policy) { krb5_error_code st=0; LDAP *ld=NULL; LDAPMod **mods={NULL}; kdb5_dal_handle *dal_handle=NULL; krb5_ldap_context *ldap_context=NULL; krb5_ldap_server_handle *ldap_server_handle=NULL; char *strval[2]={NULL}, *policy_dn=NULL; /* Clear the global error string */ krb5_clear_error_message(context); /* validate the input parameters */ if (policy == NULL || policy->name == NULL) return EINVAL; SETUP_CONTEXT(); GET_HANDLE(); st = krb5_ldap_name_to_policydn (context, policy->name, &policy_dn); if (st != 0) goto cleanup; strval[0] = policy->name; if ((st=krb5_add_str_mem_ldap_mod(&mods, "cn", LDAP_MOD_ADD, strval)) != 0) goto cleanup; strval[0] = "krbPwdPolicy"; if ((st=krb5_add_str_mem_ldap_mod(&mods, "objectclass", LDAP_MOD_ADD, strval)) != 0) goto cleanup; st = add_policy_mods(context, &mods, policy, LDAP_MOD_ADD); if (st) goto cleanup; /* password policy object creation */ if ((st=ldap_add_ext_s(ld, policy_dn, mods, NULL, NULL)) != LDAP_SUCCESS) { st = set_ldap_error (context, st, OP_ADD); goto cleanup; } cleanup: free(policy_dn); ldap_mods_free(mods, 1); krb5_ldap_put_handle_to_pool(ldap_context, ldap_server_handle); return(st); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,838
libreport
257578a23d1537a2d235aaa2b1488ee4f818e360
static void on_page_prepare(GtkNotebook *assistant, GtkWidget *page, gpointer user_data) { /* This suppresses [Last] button: assistant thinks that * we never have this page ready unless we are on it * -> therefore there is at least one non-ready page * -> therefore it won't show [Last] */ /* If processing is finished and if it was terminated because of an error * the event progress page is selected. So, it does not make sense to show * the next step button and we MUST NOT clear warnings. */ if (!is_processing_finished()) { /* some pages hide it, so restore it to it's default */ show_next_step_button(); clear_warnings(); } gtk_widget_hide(g_btn_detail); gtk_widget_hide(g_btn_onfail); if (!g_expert_mode) gtk_widget_hide(g_btn_repeat); /* Save text fields if changed */ /* Must be called before any GUI operation because the following two * functions causes recreating of the text items tabs, thus all updates to * these tabs will be lost */ save_items_from_notepad(); save_text_from_text_view(g_tv_comment, FILENAME_COMMENT); if (pages[PAGENO_SUMMARY].page_widget == page) { if (!g_expert_mode) { /* Skip intro screen */ int n = select_next_page_no(pages[PAGENO_SUMMARY].page_no, NULL); log_info("switching to page_no:%d", n); gtk_notebook_set_current_page(assistant, n); return; } } if (pages[PAGENO_EDIT_ELEMENTS].page_widget == page) { if (highlight_forbidden()) { add_sensitive_data_warning(); show_warnings(); gtk_expander_set_expanded(g_exp_search, TRUE); } else gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g_rb_custom_search), TRUE); show_warnings(); } if (pages[PAGENO_REVIEW_DATA].page_widget == page) { update_ls_details_checkboxes(g_event_selected); gtk_widget_set_sensitive(g_btn_next, gtk_toggle_button_get_active(g_tb_approve_bt)); } if (pages[PAGENO_EDIT_COMMENT].page_widget == page) { gtk_widget_show(g_btn_detail); gtk_widget_set_sensitive(g_btn_next, false); on_comment_changed(gtk_text_view_get_buffer(g_tv_comment), NULL); } if (pages[PAGENO_EVENT_PROGRESS].page_widget == page) { log_info("g_event_selected:'%s'", g_event_selected); if (g_event_selected && g_event_selected[0] ) { clear_warnings(); start_event_run(g_event_selected); } } if(pages[PAGENO_EVENT_SELECTOR].page_widget == page) { if (!g_expert_mode && !g_auto_event_list) hide_next_step_button(); } }
1
CVE-2015-5302
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,985
curl
1b71bc532bde8621fd3260843f8197182a467ff2
static CURLcode file_disconnect(struct connectdata *conn, bool dead_connection) { struct FILEPROTO *file = conn->data->req.protop; (void)dead_connection; /* not used */ if(file) { Curl_safefree(file->freepath); file->path = NULL; if(file->fd != -1) close(file->fd); file->fd = -1; } return CURLE_OK; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,367
Chrome
3298d3abf47b3a7a10e44c07d821c68a5c8aa935
void WebGLRenderingContextBase::TexImageHelperHTMLVideoElement( const SecurityOrigin* security_origin, TexImageFunctionID function_id, GLenum target, GLint level, GLint internalformat, GLenum format, GLenum type, GLint xoffset, GLint yoffset, GLint zoffset, HTMLVideoElement* video, const IntRect& source_image_rect, GLsizei depth, GLint unpack_image_height, ExceptionState& exception_state) { const char* func_name = GetTexImageFunctionName(function_id); if (isContextLost()) return; if (!ValidateHTMLVideoElement(security_origin, func_name, video, exception_state)) return; WebGLTexture* texture = ValidateTexImageBinding(func_name, function_id, target); if (!texture) return; TexImageFunctionType function_type; if (function_id == kTexImage2D || function_id == kTexImage3D) function_type = kTexImage; else function_type = kTexSubImage; if (!ValidateTexFunc(func_name, function_type, kSourceHTMLVideoElement, target, level, internalformat, video->videoWidth(), video->videoHeight(), 1, 0, format, type, xoffset, yoffset, zoffset)) return; WebMediaPlayer::VideoFrameUploadMetadata frame_metadata = {}; int already_uploaded_id = -1; WebMediaPlayer::VideoFrameUploadMetadata* frame_metadata_ptr = nullptr; if (RuntimeEnabledFeatures::ExperimentalCanvasFeaturesEnabled()) { already_uploaded_id = texture->GetLastUploadedVideoFrameId(); frame_metadata_ptr = &frame_metadata; } bool source_image_rect_is_default = source_image_rect == SentinelEmptyRect() || source_image_rect == IntRect(0, 0, video->videoWidth(), video->videoHeight()); const bool use_copyTextureCHROMIUM = function_id == kTexImage2D && source_image_rect_is_default && depth == 1 && GL_TEXTURE_2D == target && CanUseTexImageByGPU(format, type); if (use_copyTextureCHROMIUM) { DCHECK_EQ(xoffset, 0); DCHECK_EQ(yoffset, 0); DCHECK_EQ(zoffset, 0); if (video->CopyVideoTextureToPlatformTexture( ContextGL(), target, texture->Object(), internalformat, format, type, level, unpack_premultiply_alpha_, unpack_flip_y_, already_uploaded_id, frame_metadata_ptr)) { texture->UpdateLastUploadedFrame(frame_metadata); return; } } if (source_image_rect_is_default) { ScopedUnpackParametersResetRestore( this, unpack_flip_y_ || unpack_premultiply_alpha_); if (video->TexImageImpl( static_cast<WebMediaPlayer::TexImageFunctionID>(function_id), target, ContextGL(), texture->Object(), level, ConvertTexInternalFormat(internalformat, type), format, type, xoffset, yoffset, zoffset, unpack_flip_y_, unpack_premultiply_alpha_ && unpack_colorspace_conversion_ == GL_NONE)) { texture->ClearLastUploadedFrame(); return; } } if (use_copyTextureCHROMIUM) { std::unique_ptr<ImageBufferSurface> surface = WTF::WrapUnique(new AcceleratedImageBufferSurface( IntSize(video->videoWidth(), video->videoHeight()))); if (surface->IsValid()) { std::unique_ptr<ImageBuffer> image_buffer( ImageBuffer::Create(std::move(surface))); if (image_buffer) { video->PaintCurrentFrame( image_buffer->Canvas(), IntRect(0, 0, video->videoWidth(), video->videoHeight()), nullptr, already_uploaded_id, frame_metadata_ptr); TexImage2DBase(target, level, internalformat, video->videoWidth(), video->videoHeight(), 0, format, type, nullptr); if (image_buffer->CopyToPlatformTexture( FunctionIDToSnapshotReason(function_id), ContextGL(), target, texture->Object(), unpack_premultiply_alpha_, unpack_flip_y_, IntPoint(0, 0), IntRect(0, 0, video->videoWidth(), video->videoHeight()))) { texture->UpdateLastUploadedFrame(frame_metadata); return; } } } } scoped_refptr<Image> image = VideoFrameToImage(video, already_uploaded_id, frame_metadata_ptr); if (!image) return; TexImageImpl(function_id, target, level, internalformat, xoffset, yoffset, zoffset, format, type, image.get(), WebGLImageConversion::kHtmlDomVideo, unpack_flip_y_, unpack_premultiply_alpha_, source_image_rect, depth, unpack_image_height); texture->UpdateLastUploadedFrame(frame_metadata); }
1
CVE-2018-6034
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,445
heimdal
04171147948d0a3636bc6374181926f0fb2ec83a
tgs_build_reply(astgs_request_t priv, hdb_entry_ex *krbtgt, krb5_enctype krbtgt_etype, const krb5_keyblock *replykey, int rk_is_subkey, krb5_ticket *ticket, const char **e_text, AuthorizationData **auth_data, const struct sockaddr *from_addr) { krb5_context context = priv->context; krb5_kdc_configuration *config = priv->config; KDC_REQ *req = &priv->req; KDC_REQ_BODY *b = &priv->req.req_body; const char *from = priv->from; krb5_error_code ret, ret2; krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL; krb5_principal krbtgt_out_principal = NULL; char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL; hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL; HDB *clientdb, *s4u2self_impersonated_clientdb; krb5_realm ref_realm = NULL; EncTicketPart *tgt = &ticket->ticket; krb5_principals spp = NULL; const EncryptionKey *ekey; krb5_keyblock sessionkey; krb5_kvno kvno; krb5_data rspac; const char *tgt_realm = /* Realm of TGT issuer */ krb5_principal_get_realm(context, krbtgt->entry.principal); const char *our_realm = /* Realm of this KDC */ krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1); char **capath = NULL; size_t num_capath = 0; hdb_entry_ex *krbtgt_out = NULL; METHOD_DATA enc_pa_data; PrincipalName *s; Realm r; EncTicketPart adtkt; char opt_str[128]; int signedpath = 0; Key *tkey_check; Key *tkey_sign; int flags = HDB_F_FOR_TGS_REQ; memset(&sessionkey, 0, sizeof(sessionkey)); memset(&adtkt, 0, sizeof(adtkt)); krb5_data_zero(&rspac); memset(&enc_pa_data, 0, sizeof(enc_pa_data)); s = b->sname; r = b->realm; /* * The canonicalize KDC option is passed as a hint to the backend, but * can typically be ignored. Per RFC 6806, names are not canonicalized * in response to a TGS request (although we make an exception, see * force-canonicalize below). */ if (b->kdc_options.canonicalize) flags |= HDB_F_CANON; if(b->kdc_options.enc_tkt_in_skey){ Ticket *t; hdb_entry_ex *uu; krb5_principal p; Key *uukey; krb5uint32 second_kvno = 0; krb5uint32 *kvno_ptr = NULL; if(b->additional_tickets == NULL || b->additional_tickets->len == 0){ ret = KRB5KDC_ERR_BADOPTION; /* ? */ kdc_log(context, config, 4, "No second ticket present in user-to-user request"); _kdc_audit_addreason((kdc_request_t)priv, "No second ticket present in user-to-user request"); goto out; } t = &b->additional_tickets->val[0]; if(!get_krbtgt_realm(&t->sname)){ kdc_log(context, config, 4, "Additional ticket is not a ticket-granting ticket"); _kdc_audit_addreason((kdc_request_t)priv, "Additional ticket is not a ticket-granting ticket"); ret = KRB5KDC_ERR_POLICY; goto out; } _krb5_principalname2krb5_principal(context, &p, t->sname, t->realm); ret = krb5_unparse_name(context, p, &tpn); if (ret) goto out; if(t->enc_part.kvno){ second_kvno = *t->enc_part.kvno; kvno_ptr = &second_kvno; } ret = _kdc_db_fetch(context, config, p, HDB_F_GET_KRBTGT, kvno_ptr, NULL, &uu); krb5_free_principal(context, p); if(ret){ if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; _kdc_audit_addreason((kdc_request_t)priv, "User-to-user service principal (TGS) unknown"); goto out; } ret = hdb_enctype2key(context, &uu->entry, NULL, t->enc_part.etype, &uukey); if(ret){ _kdc_free_ent(context, uu); ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */ _kdc_audit_addreason((kdc_request_t)priv, "User-to-user enctype not supported"); goto out; } ret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0); _kdc_free_ent(context, uu); if(ret) { _kdc_audit_addreason((kdc_request_t)priv, "User-to-user TGT decrypt failure"); goto out; } ret = verify_flags(context, config, &adtkt, tpn); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "User-to-user TGT expired or invalid"); goto out; } s = &adtkt.cname; r = adtkt.crealm; } else if (s == NULL) { ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; _kdc_set_e_text(r, "No server in request"); goto out; } _krb5_principalname2krb5_principal(context, &sp, *s, r); ret = krb5_unparse_name(context, sp, &priv->sname); if (ret) goto out; spn = priv->sname; _krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm); ret = krb5_unparse_name(context, cp, &priv->cname); if (ret) goto out; cpn = priv->cname; unparse_flags (KDCOptions2int(b->kdc_options), asn1_KDCOptions_units(), opt_str, sizeof(opt_str)); if(*opt_str) kdc_log(context, config, 4, "TGS-REQ %s from %s for %s [%s]", cpn, from, spn, opt_str); else kdc_log(context, config, 4, "TGS-REQ %s from %s for %s", cpn, from, spn); /* * Fetch server */ server_lookup: ret = _kdc_db_fetch(context, config, sp, HDB_F_GET_SERVER | HDB_F_DELAY_NEW_KEYS | flags, NULL, NULL, &server); priv->server = server; if (ret == HDB_ERR_NOT_FOUND_HERE) { kdc_log(context, config, 5, "target %s does not have secrets at this KDC, need to proxy", spn); _kdc_audit_addreason((kdc_request_t)priv, "Target not found here"); goto out; } else if (ret == HDB_ERR_WRONG_REALM) { free(ref_realm); ref_realm = strdup(server->entry.principal->realm); if (ref_realm == NULL) { ret = krb5_enomem(context); goto out; } kdc_log(context, config, 4, "Returning a referral to realm %s for " "server %s.", ref_realm, spn); krb5_free_principal(context, sp); sp = NULL; ret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, ref_realm, NULL); if (ret) goto out; free(priv->sname); priv->sname = NULL; ret = krb5_unparse_name(context, sp, &priv->sname); if (ret) goto out; spn = priv->sname; goto server_lookup; } else if (ret) { const char *new_rlm, *msg; Realm req_rlm; krb5_realm *realms; if ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) { if (capath == NULL) { /* With referalls, hierarchical capaths are always enabled */ ret2 = _krb5_find_capath(context, tgt->crealm, our_realm, req_rlm, TRUE, &capath, &num_capath); if (ret2) { ret = ret2; _kdc_audit_addreason((kdc_request_t)priv, "No trusted path from client realm to ours"); goto out; } } new_rlm = num_capath > 0 ? capath[--num_capath] : NULL; if (new_rlm) { kdc_log(context, config, 5, "krbtgt from %s via %s for " "realm %s not found, trying %s", tgt->crealm, our_realm, req_rlm, new_rlm); free(ref_realm); ref_realm = strdup(new_rlm); if (ref_realm == NULL) { ret = krb5_enomem(context); goto out; } krb5_free_principal(context, sp); sp = NULL; krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, ref_realm, NULL); free(priv->sname); priv->sname = NULL; ret = krb5_unparse_name(context, sp, &priv->sname); if (ret) goto out; spn = priv->sname; goto server_lookup; } } else if (need_referral(context, config, &b->kdc_options, sp, &realms)) { if (strcmp(realms[0], sp->realm) != 0) { kdc_log(context, config, 4, "Returning a referral to realm %s for " "server %s that was not found", realms[0], spn); krb5_free_principal(context, sp); sp = NULL; krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, realms[0], NULL); free(priv->sname); priv->sname = NULL; ret = krb5_unparse_name(context, sp, &priv->sname); if (ret) { krb5_free_host_realm(context, realms); goto out; } spn = priv->sname; free(ref_realm); ref_realm = strdup(realms[0]); krb5_free_host_realm(context, realms); goto server_lookup; } krb5_free_host_realm(context, realms); } msg = krb5_get_error_message(context, ret); kdc_log(context, config, 3, "Server not found in database: %s: %s", spn, msg); krb5_free_error_message(context, msg); if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; _kdc_audit_addreason((kdc_request_t)priv, "Service principal unknown"); goto out; } /* * RFC 6806 notes that names MUST NOT be changed in the response to * a TGS request. Hence we ignore the setting of the canonicalize * KDC option. However, for legacy interoperability we do allow the * backend to override this by setting the force-canonicalize HDB * flag in the server entry. */ if (server->entry.flags.force_canonicalize) rsp = server->entry.principal; else rsp = sp; /* * Select enctype, return key and kvno. */ { krb5_enctype etype; if(b->kdc_options.enc_tkt_in_skey) { size_t i; ekey = &adtkt.key; for(i = 0; i < b->etype.len; i++) if (b->etype.val[i] == adtkt.key.keytype) break; if(i == b->etype.len) { kdc_log(context, config, 4, "Addition ticket have not matching etypes"); krb5_clear_error_message(context); ret = KRB5KDC_ERR_ETYPE_NOSUPP; _kdc_audit_addreason((kdc_request_t)priv, "No matching enctypes for 2nd ticket"); goto out; } etype = b->etype.val[i]; kvno = 0; } else { Key *skey; ret = _kdc_find_etype(priv, krb5_principal_is_krbtgt(context, sp) ? KFE_IS_TGS : 0, b->etype.val, b->etype.len, &etype, NULL, NULL); if(ret) { kdc_log(context, config, 4, "Server (%s) has no support for etypes", spn); _kdc_audit_addreason((kdc_request_t)priv, "Enctype not supported"); goto out; } ret = _kdc_get_preferred_key(context, config, server, spn, NULL, &skey); if(ret) { kdc_log(context, config, 4, "Server (%s) has no supported etypes", spn); _kdc_audit_addreason((kdc_request_t)priv, "Enctype not supported"); goto out; } ekey = &skey->key; kvno = server->entry.kvno; } ret = krb5_generate_random_keyblock(context, etype, &sessionkey); if (ret) goto out; } /* * Check that service is in the same realm as the krbtgt. If it's * not the same, it's someone that is using a uni-directional trust * backward. */ /* * Validate authorization data */ ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */ krbtgt_etype, &tkey_check); if(ret) { kdc_log(context, config, 4, "Failed to find key for krbtgt PAC check"); _kdc_audit_addreason((kdc_request_t)priv, "No key for krbtgt PAC check"); goto out; } /* * Now refetch the primary krbtgt, and get the current kvno (the * sign check may have been on an old kvno, and the server may * have been an incoming trust) */ ret = krb5_make_principal(context, &krbtgt_out_principal, our_realm, KRB5_TGS_NAME, our_realm, NULL); if (ret) { kdc_log(context, config, 4, "Failed to make krbtgt principal name object for " "authz-data signatures"); goto out; } ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n); if (ret) { kdc_log(context, config, 4, "Failed to make krbtgt principal name object for " "authz-data signatures"); goto out; } ret = _kdc_db_fetch(context, config, krbtgt_out_principal, HDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out); if (ret) { char *ktpn = NULL; ret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn); kdc_log(context, config, 4, "No such principal %s (needed for authz-data signature keys) " "while processing TGS-REQ for service %s with krbtg %s", krbtgt_out_n, spn, (ret == 0) ? ktpn : "<unknown>"); free(ktpn); ret = KRB5KRB_AP_ERR_NOT_US; goto out; } /* * The first realm is the realm of the service, the second is * krbtgt/<this>/@REALM component of the krbtgt DN the request was * encrypted to. The redirection via the krbtgt_out entry allows * the DB to possibly correct the case of the realm (Samba4 does * this) before the strcmp() */ if (strcmp(krb5_principal_get_realm(context, server->entry.principal), krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) { char *ktpn; ret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn); kdc_log(context, config, 4, "Request with wrong krbtgt: %s", (ret == 0) ? ktpn : "<unknown>"); if(ret == 0) free(ktpn); ret = KRB5KRB_AP_ERR_NOT_US; _kdc_audit_addreason((kdc_request_t)priv, "Request with wrong TGT"); goto out; } ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n, NULL, &tkey_sign); if (ret) { kdc_log(context, config, 4, "Failed to find key for krbtgt PAC signature"); _kdc_audit_addreason((kdc_request_t)priv, "Failed to find key for krbtgt PAC signature"); goto out; } ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL, tkey_sign->key.keytype, &tkey_sign); if(ret) { kdc_log(context, config, 4, "Failed to find key for krbtgt PAC signature"); _kdc_audit_addreason((kdc_request_t)priv, "Failed to find key for krbtgt PAC signature"); goto out; } { krb5_data verified_cas; /* * If the client doesn't exist in the HDB but has a TGT and it's * obtained with PKINIT then we assume it's a synthetic client -- that * is, a client whose name was vouched for by a CA using a PKINIT SAN, * but which doesn't exist in the HDB proper. We'll allow such a * client to do TGT requests even though normally we'd reject all * clients that don't exist in the HDB. */ ret = krb5_ticket_get_authorization_data_type(context, ticket, KRB5_AUTHDATA_INITIAL_VERIFIED_CAS, &verified_cas); if (ret == 0) { krb5_data_free(&verified_cas); flags |= HDB_F_SYNTHETIC_OK; } } ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags, NULL, &clientdb, &client); flags &= ~HDB_F_SYNTHETIC_OK; priv->client = client; if(ret == HDB_ERR_NOT_FOUND_HERE) { /* This is OK, we are just trying to find out if they have * been disabled or deleted in the meantime, missing secrets * is OK */ } else if(ret){ const char *krbtgt_realm, *msg; /* * If the client belongs to the same realm as our krbtgt, it * should exist in the local database. * */ krbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal); if(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) { if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; kdc_log(context, config, 4, "Client no longer in database: %s", cpn); _kdc_audit_addreason((kdc_request_t)priv, "Client no longer in HDB"); goto out; } msg = krb5_get_error_message(context, ret); kdc_log(context, config, 4, "Client not found in database: %s", msg); _kdc_audit_addreason((kdc_request_t)priv, "Client does not exist"); krb5_free_error_message(context, msg); } else if (ret == 0 && (client->entry.flags.invalid || !client->entry.flags.client)) { _kdc_audit_addreason((kdc_request_t)priv, "Client has invalid bit set"); kdc_log(context, config, 4, "Client has invalid bit set"); ret = KRB5KDC_ERR_POLICY; goto out; } ret = check_PAC(context, config, cp, NULL, client, server, krbtgt, &tkey_check->key, ekey, &tkey_sign->key, tgt, &rspac, &signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); _kdc_audit_addreason((kdc_request_t)priv, "PAC check failed"); kdc_log(context, config, 4, "Verify PAC failed for %s (%s) from %s with %s", spn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* also check the krbtgt for signature */ ret = check_KRB5SignedPath(context, config, krbtgt, cp, tgt, &spp, &signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); _kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath check failed"); kdc_log(context, config, 4, "KRB5SignedPath check failed for %s (%s) from %s with %s", spn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* * Process request */ /* by default the tgt principal matches the client principal */ tp = cp; tpn = cpn; if (client) { const PA_DATA *sdata; int i = 0; sdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER); if (sdata) { struct astgs_request_desc imp_req; krb5_crypto crypto; krb5_data datack; PA_S4U2Self self; const char *str; ret = decode_PA_S4U2Self(sdata->padata_value.data, sdata->padata_value.length, &self, NULL); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Failed to decode PA-S4U2Self"); kdc_log(context, config, 4, "Failed to decode PA-S4U2Self"); goto out; } if (!krb5_checksum_is_keyed(context, self.cksum.cksumtype)) { free_PA_S4U2Self(&self); _kdc_audit_addreason((kdc_request_t)priv, "PA-S4U2Self with unkeyed checksum"); kdc_log(context, config, 4, "Reject PA-S4U2Self with unkeyed checksum"); ret = KRB5KRB_AP_ERR_INAPP_CKSUM; goto out; } ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack); if (ret) goto out; ret = krb5_crypto_init(context, &tgt->key, 0, &crypto); if (ret) { const char *msg = krb5_get_error_message(context, ret); free_PA_S4U2Self(&self); krb5_data_free(&datack); kdc_log(context, config, 4, "krb5_crypto_init failed: %s", msg); krb5_free_error_message(context, msg); goto out; } /* Allow HMAC_MD5 checksum with any key type */ if (self.cksum.cksumtype == CKSUMTYPE_HMAC_MD5) { struct krb5_crypto_iov iov; unsigned char csdata[16]; Checksum cs; cs.checksum.length = sizeof(csdata); cs.checksum.data = &csdata; iov.data.data = datack.data; iov.data.length = datack.length; iov.flags = KRB5_CRYPTO_TYPE_DATA; ret = _krb5_HMAC_MD5_checksum(context, NULL, &crypto->key, KRB5_KU_OTHER_CKSUM, &iov, 1, &cs); if (ret == 0 && krb5_data_ct_cmp(&cs.checksum, &self.cksum.checksum) != 0) ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; } else { ret = krb5_verify_checksum(context, crypto, KRB5_KU_OTHER_CKSUM, datack.data, datack.length, &self.cksum); } krb5_data_free(&datack); krb5_crypto_destroy(context, crypto); if (ret) { const char *msg = krb5_get_error_message(context, ret); free_PA_S4U2Self(&self); _kdc_audit_addreason((kdc_request_t)priv, "S4U2Self checksum failed"); kdc_log(context, config, 4, "krb5_verify_checksum failed for S4U2Self: %s", msg); krb5_free_error_message(context, msg); goto out; } ret = _krb5_principalname2krb5_principal(context, &tp, self.name, self.realm); free_PA_S4U2Self(&self); if (ret) goto out; ret = krb5_unparse_name(context, tp, &tpn); if (ret) goto out; /* * Note no HDB_F_SYNTHETIC_OK -- impersonating non-existent clients * is probably not desirable! */ ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags, NULL, &s4u2self_impersonated_clientdb, &s4u2self_impersonated_client); if (ret) { const char *msg; /* * If the client belongs to the same realm as our krbtgt, it * should exist in the local database. * */ if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; msg = krb5_get_error_message(context, ret); _kdc_audit_addreason((kdc_request_t)priv, "S4U2Self principal to impersonate not found"); kdc_log(context, config, 2, "S4U2Self principal to impersonate %s not found in database: %s", tpn, msg); krb5_free_error_message(context, msg); goto out; } /* Ignore require_pwchange and pw_end attributes (as Windows does), * since S4U2Self is not password authentication. */ s4u2self_impersonated_client->entry.flags.require_pwchange = FALSE; free(s4u2self_impersonated_client->entry.pw_end); s4u2self_impersonated_client->entry.pw_end = NULL; imp_req = *priv; imp_req.client = s4u2self_impersonated_client; imp_req.client_princ = tp; ret = kdc_check_flags(&imp_req, FALSE); if (ret) goto out; /* kdc_check_flags() calls _kdc_audit_addreason() */ /* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */ if(rspac.data) { krb5_pac p = NULL; krb5_data_free(&rspac); ret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath missing"); kdc_log(context, config, 4, "PAC generation failed for -- %s", tpn); goto out; } if (p != NULL) { ret = _krb5_pac_sign(context, p, ticket->ticket.authtime, s4u2self_impersonated_client->entry.principal, ekey, &tkey_sign->key, &rspac); krb5_pac_free(context, p); if (ret) { kdc_log(context, config, 4, "PAC signing failed for -- %s", tpn); goto out; } } } /* * Check that service doing the impersonating is * requesting a ticket to it-self. */ ret = check_s4u2self(context, config, clientdb, client, sp); if (ret) { kdc_log(context, config, 4, "S4U2Self: %s is not allowed " "to impersonate to service " "(tried for user %s to service %s)", cpn, tpn, spn); goto out; } /* * If the service isn't trusted for authentication to * delegation or if the impersonate client is disallowed * forwardable, remove the forwardable flag. */ if (client->entry.flags.trusted_for_delegation && s4u2self_impersonated_client->entry.flags.forwardable) { str = "[forwardable]"; } else { b->kdc_options.forwardable = 0; str = ""; } kdc_log(context, config, 4, "s4u2self %s impersonating %s to " "service %s %s", cpn, tpn, spn, str); } } /* * Constrained delegation */ if (client != NULL && b->additional_tickets != NULL && b->additional_tickets->len != 0 && b->kdc_options.cname_in_addl_tkt && b->kdc_options.enc_tkt_in_skey == 0) { int ad_signedpath = 0; Key *clientkey; Ticket *t; /* * Require that the KDC have issued the service's krbtgt (not * self-issued ticket with kimpersonate(1). */ if (!signedpath) { ret = KRB5KDC_ERR_BADOPTION; _kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath missing"); kdc_log(context, config, 4, "Constrained delegation done on service ticket %s/%s", cpn, spn); goto out; } t = &b->additional_tickets->val[0]; ret = hdb_enctype2key(context, &client->entry, hdb_kvno2keys(context, &client->entry, t->enc_part.kvno ? * t->enc_part.kvno : 0), t->enc_part.etype, &clientkey); if(ret){ ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */ goto out; } ret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Failed to decrypt constrained delegation ticket"); kdc_log(context, config, 4, "failed to decrypt ticket for " "constrained delegation from %s to %s ", cpn, spn); goto out; } ret = _krb5_principalname2krb5_principal(context, &tp, adtkt.cname, adtkt.crealm); if (ret) goto out; ret = krb5_unparse_name(context, tp, &tpn); if (ret) goto out; _kdc_audit_addkv((kdc_request_t)priv, 0, "impersonatee", "%s", tpn); ret = _krb5_principalname2krb5_principal(context, &dp, t->sname, t->realm); if (ret) goto out; ret = krb5_unparse_name(context, dp, &dpn); if (ret) goto out; /* check that ticket is valid */ if (adtkt.flags.forwardable == 0) { _kdc_audit_addreason((kdc_request_t)priv, "Missing forwardable flag on ticket for constrained delegation"); kdc_log(context, config, 4, "Missing forwardable flag on ticket for " "constrained delegation from %s (%s) as %s to %s ", cpn, dpn, tpn, spn); ret = KRB5KDC_ERR_BADOPTION; goto out; } ret = check_constrained_delegation(context, config, clientdb, client, server, sp); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Constrained delegation not allowed"); kdc_log(context, config, 4, "constrained delegation from %s (%s) as %s to %s not allowed", cpn, dpn, tpn, spn); goto out; } ret = verify_flags(context, config, &adtkt, tpn); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Constrained delegation ticket expired or invalid"); goto out; } krb5_data_free(&rspac); /* * generate the PAC for the user. * * TODO: pass in t->sname and t->realm and build * a S4U_DELEGATION_INFO blob to the PAC. */ ret = check_PAC(context, config, tp, dp, client, server, krbtgt, &clientkey->key, ekey, &tkey_sign->key, &adtkt, &rspac, &ad_signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); _kdc_audit_addreason((kdc_request_t)priv, "Constrained delegation ticket PAC check failed"); kdc_log(context, config, 4, "Verify delegated PAC failed to %s for client" "%s (%s) as %s from %s with %s", spn, cpn, dpn, tpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* * Check that the KDC issued the user's ticket. */ ret = check_KRB5SignedPath(context, config, krbtgt, cp, &adtkt, NULL, &ad_signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 4, "KRB5SignedPath check from service %s failed " "for delegation to %s for client %s (%s)" "from %s failed with %s", spn, tpn, dpn, cpn, from, msg); krb5_free_error_message(context, msg); _kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath check failed"); goto out; } if (!ad_signedpath) { ret = KRB5KDC_ERR_BADOPTION; kdc_log(context, config, 4, "Ticket not signed with PAC nor SignedPath service %s failed " "for delegation to %s for client %s (%s)" "from %s", spn, tpn, dpn, cpn, from); _kdc_audit_addreason((kdc_request_t)priv, "Constrained delegation ticket not signed"); goto out; } kdc_log(context, config, 4, "constrained delegation for %s " "from %s (%s) to %s", tpn, cpn, dpn, spn); } /* * Check flags */ ret = kdc_check_flags(priv, FALSE); if(ret) goto out; if((b->kdc_options.validate || b->kdc_options.renew) && !krb5_principal_compare(context, krbtgt->entry.principal, server->entry.principal)){ _kdc_audit_addreason((kdc_request_t)priv, "Inconsistent request"); kdc_log(context, config, 4, "Inconsistent request."); ret = KRB5KDC_ERR_SERVER_NOMATCH; goto out; } /* check for valid set of addresses */ if (!_kdc_check_addresses(priv, tgt->caddr, from_addr)) { if (config->check_ticket_addresses) { ret = KRB5KRB_AP_ERR_BADADDR; _kdc_audit_addkv((kdc_request_t)priv, 0, "wrongaddr", "yes"); kdc_log(context, config, 4, "Request from wrong address"); _kdc_audit_addreason((kdc_request_t)priv, "Request from wrong address"); goto out; } else if (config->warn_ticket_addresses) { _kdc_audit_addkv((kdc_request_t)priv, 0, "wrongaddr", "yes"); } } /* check local and per-principal anonymous ticket issuance policy */ if (is_anon_tgs_request_p(b, tgt)) { ret = _kdc_check_anon_policy(priv); if (ret) goto out; } /* * If this is an referral, add server referral data to the * auth_data reply . */ if (ref_realm) { PA_DATA pa; krb5_crypto crypto; kdc_log(context, config, 3, "Adding server referral to %s", ref_realm); ret = krb5_crypto_init(context, &sessionkey, 0, &crypto); if (ret) goto out; ret = build_server_referral(context, config, crypto, ref_realm, NULL, s, &pa.padata_value); krb5_crypto_destroy(context, crypto); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Referral build failed"); kdc_log(context, config, 4, "Failed building server referral"); goto out; } pa.padata_type = KRB5_PADATA_SERVER_REFERRAL; ret = add_METHOD_DATA(&enc_pa_data, &pa); krb5_data_free(&pa.padata_value); if (ret) { kdc_log(context, config, 4, "Add server referral METHOD-DATA failed"); goto out; } } /* * */ ret = tgs_make_reply(priv, tp, tgt, replykey, rk_is_subkey, ekey, &sessionkey, kvno, *auth_data, server, rsp, client, cp, tgt_realm, krbtgt_out, tkey_sign->key.keytype, spp, &rspac, &enc_pa_data); out: if (tpn != cpn) free(tpn); free(dpn); free(krbtgt_out_n); _krb5_free_capath(context, capath); krb5_data_free(&rspac); krb5_free_keyblock_contents(context, &sessionkey); if(krbtgt_out) _kdc_free_ent(context, krbtgt_out); if(server) _kdc_free_ent(context, server); if(client) _kdc_free_ent(context, client); if(s4u2self_impersonated_client) _kdc_free_ent(context, s4u2self_impersonated_client); if (tp && tp != cp) krb5_free_principal(context, tp); krb5_free_principal(context, cp); krb5_free_principal(context, dp); krb5_free_principal(context, sp); krb5_free_principal(context, krbtgt_out_principal); free(ref_realm); free_METHOD_DATA(&enc_pa_data); free_EncTicketPart(&adtkt); return ret; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,151
vim
2a585c85013be22f59f184d49612074fd9b115d7
ex_display(exarg_T *eap) { int i, n; long j; char_u *p; yankreg_T *yb; int name; int attr; char_u *arg = eap->arg; int clen; int type; if (arg != NULL && *arg == NUL) arg = NULL; attr = HL_ATTR(HLF_8); // Highlight title msg_puts_title(_("\nType Name Content")); for (i = -1; i < NUM_REGISTERS && !got_int; ++i) { name = get_register_name(i); switch (get_reg_type(name, NULL)) { case MLINE: type = 'l'; break; case MCHAR: type = 'c'; break; default: type = 'b'; break; } if (arg != NULL && vim_strchr(arg, name) == NULL #ifdef ONE_CLIPBOARD // Star register and plus register contain the same thing. && (name != '*' || vim_strchr(arg, '+') == NULL) #endif ) continue; // did not ask for this register #ifdef FEAT_CLIPBOARD // Adjust register name for "unnamed" in 'clipboard'. // When it's a clipboard register, fill it with the current contents // of the clipboard. adjust_clip_reg(&name); (void)may_get_selection(name); #endif if (i == -1) { if (y_previous != NULL) yb = y_previous; else yb = &(y_regs[0]); } else yb = &(y_regs[i]); #ifdef FEAT_EVAL if (name == MB_TOLOWER(redir_reg) || (redir_reg == '"' && yb == y_previous)) continue; // do not list register being written to, the // pointer can be freed #endif if (yb->y_array != NULL) { int do_show = FALSE; for (j = 0; !do_show && j < yb->y_size; ++j) do_show = !message_filtered(yb->y_array[j]); if (do_show || yb->y_size == 0) { msg_putchar('\n'); msg_puts(" "); msg_putchar(type); msg_puts(" "); msg_putchar('"'); msg_putchar(name); msg_puts(" "); n = (int)Columns - 11; for (j = 0; j < yb->y_size && n > 1; ++j) { if (j) { msg_puts_attr("^J", attr); n -= 2; } for (p = yb->y_array[j]; *p != NUL && (n -= ptr2cells(p)) >= 0; ++p) { clen = (*mb_ptr2len)(p); msg_outtrans_len(p, clen); p += clen - 1; } } if (n > 1 && yb->y_type == MLINE) msg_puts_attr("^J", attr); out_flush(); // show one line at a time } ui_breakcheck(); } } // display last inserted text if ((p = get_last_insert()) != NULL && (arg == NULL || vim_strchr(arg, '.') != NULL) && !got_int && !message_filtered(p)) { msg_puts("\n c \". "); dis_msg(p, TRUE); } // display last command line if (last_cmdline != NULL && (arg == NULL || vim_strchr(arg, ':') != NULL) && !got_int && !message_filtered(last_cmdline)) { msg_puts("\n c \": "); dis_msg(last_cmdline, FALSE); } // display current file name if (curbuf->b_fname != NULL && (arg == NULL || vim_strchr(arg, '%') != NULL) && !got_int && !message_filtered(curbuf->b_fname)) { msg_puts("\n c \"% "); dis_msg(curbuf->b_fname, FALSE); } // display alternate file name if ((arg == NULL || vim_strchr(arg, '%') != NULL) && !got_int) { char_u *fname; linenr_T dummy; if (buflist_name_nr(0, &fname, &dummy) != FAIL && !message_filtered(fname)) { msg_puts("\n c \"# "); dis_msg(fname, FALSE); } } // display last search pattern if (last_search_pat() != NULL && (arg == NULL || vim_strchr(arg, '/') != NULL) && !got_int && !message_filtered(last_search_pat())) { msg_puts("\n c \"/ "); dis_msg(last_search_pat(), FALSE); } #ifdef FEAT_EVAL // display last used expression if (expr_line != NULL && (arg == NULL || vim_strchr(arg, '=') != NULL) && !got_int && !message_filtered(expr_line)) { msg_puts("\n c \"= "); dis_msg(expr_line, FALSE); } #endif }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,777
Android
1f4b49e64adf4623eefda503bca61e253597b9bf
status_t Parcel::readByteVector(std::unique_ptr<std::vector<uint8_t>>* val) const { return readByteVectorInternalPtr(this, val); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,562
Chrome
673ce95d481ea9368c4d4d43ac756ba1d6d9e608
void CallCompositorWithSuccess(mojom::PdfCompositorPtr ptr) { auto handle = CreateMSKPInSharedMemory(); ASSERT_TRUE(handle.IsValid()); mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle(handle, handle.GetSize(), true); ASSERT_TRUE(buffer_handle->is_valid()); EXPECT_CALL(*this, CallbackOnSuccess(testing::_)).Times(1); ptr->CompositePdf(std::move(buffer_handle), base::BindOnce(&PdfCompositorServiceTest::OnCallback, base::Unretained(this))); run_loop_->Run(); }
1
CVE-2018-6063
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Phase: Requirements Strategy: Language Selection Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe. Phase: Architecture and Design Strategy: Libraries or Frameworks Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions. Note: This is not a complete solution, since many buffer overflows are not related to strings. Phases: Operation; Build and Compilation Strategy: Environment Hardening Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail. Effectiveness: Defense in Depth Note: This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application. Phase: Implementation Consider adhering to the following rules when allocating and managing an application's memory: Double check that the buffer is as large as specified. When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string. Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space. If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions. Phases: Operation; Build and Compilation Strategy: Environment Hardening Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking. For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335]. Effectiveness: Defense in Depth Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]. Phase: Operation Strategy: Environment Hardening Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment. For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336]. Effectiveness: Defense in Depth Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application. Phase: Implementation Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available. Effectiveness: Moderate Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).
2,045
php-src
da3886de6dc8edab3da14331227816d6ca8e9b96
PHP_MINIT_FUNCTION(filter) { ZEND_INIT_MODULE_GLOBALS(filter, php_filter_init_globals, NULL); REGISTER_INI_ENTRIES(); REGISTER_LONG_CONSTANT("INPUT_POST", PARSE_POST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_GET", PARSE_GET, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_COOKIE", PARSE_COOKIE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_ENV", PARSE_ENV, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_SERVER", PARSE_SERVER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_SESSION", PARSE_SESSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_REQUEST", PARSE_REQUEST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_NONE", FILTER_FLAG_NONE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_REQUIRE_SCALAR", FILTER_REQUIRE_SCALAR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_REQUIRE_ARRAY", FILTER_REQUIRE_ARRAY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FORCE_ARRAY", FILTER_FORCE_ARRAY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_NULL_ON_FAILURE", FILTER_NULL_ON_FAILURE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_INT", FILTER_VALIDATE_INT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_BOOLEAN", FILTER_VALIDATE_BOOLEAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_FLOAT", FILTER_VALIDATE_FLOAT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_REGEXP", FILTER_VALIDATE_REGEXP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_URL", FILTER_VALIDATE_URL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_EMAIL", FILTER_VALIDATE_EMAIL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_IP", FILTER_VALIDATE_IP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_DEFAULT", FILTER_DEFAULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_UNSAFE_RAW", FILTER_UNSAFE_RAW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_STRING", FILTER_SANITIZE_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_STRIPPED", FILTER_SANITIZE_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_ENCODED", FILTER_SANITIZE_ENCODED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_SPECIAL_CHARS", FILTER_SANITIZE_SPECIAL_CHARS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_FULL_SPECIAL_CHARS", FILTER_SANITIZE_SPECIAL_CHARS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_EMAIL", FILTER_SANITIZE_EMAIL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_URL", FILTER_SANITIZE_URL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_NUMBER_INT", FILTER_SANITIZE_NUMBER_INT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_NUMBER_FLOAT", FILTER_SANITIZE_NUMBER_FLOAT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_MAGIC_QUOTES", FILTER_SANITIZE_MAGIC_QUOTES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_CALLBACK", FILTER_CALLBACK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_OCTAL", FILTER_FLAG_ALLOW_OCTAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_HEX", FILTER_FLAG_ALLOW_HEX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_LOW", FILTER_FLAG_STRIP_LOW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_HIGH", FILTER_FLAG_STRIP_HIGH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_BACKTICK", FILTER_FLAG_STRIP_BACKTICK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_LOW", FILTER_FLAG_ENCODE_LOW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_HIGH", FILTER_FLAG_ENCODE_HIGH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_AMP", FILTER_FLAG_ENCODE_AMP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_ENCODE_QUOTES", FILTER_FLAG_NO_ENCODE_QUOTES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_EMPTY_STRING_NULL", FILTER_FLAG_EMPTY_STRING_NULL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_FRACTION", FILTER_FLAG_ALLOW_FRACTION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_THOUSAND", FILTER_FLAG_ALLOW_THOUSAND, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_SCIENTIFIC", FILTER_FLAG_ALLOW_SCIENTIFIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_SCHEME_REQUIRED", FILTER_FLAG_SCHEME_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_HOST_REQUIRED", FILTER_FLAG_HOST_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_PATH_REQUIRED", FILTER_FLAG_PATH_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_QUERY_REQUIRED", FILTER_FLAG_QUERY_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_IPV4", FILTER_FLAG_IPV4, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_IPV6", FILTER_FLAG_IPV6, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_RES_RANGE", FILTER_FLAG_NO_RES_RANGE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_PRIV_RANGE", FILTER_FLAG_NO_PRIV_RANGE, CONST_CS | CONST_PERSISTENT); sapi_register_input_filter(php_sapi_filter, php_sapi_filter_init TSRMLS_CC); return SUCCESS; }
1
CVE-2016-5095
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,409
Chrome
4c19b042ea31bd393d2265656f94339d1c3d82ff
virtual void RunWork() { if (!base::TouchPlatformFile(file_, last_access_time_, last_modified_time_)) set_error_code(base::PLATFORM_FILE_ERROR_FAILED); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,755
tcpdump
24182d959f661327525a20d9a94c98a8ec016778
name_len(netdissect_options *ndo, const unsigned char *s, const unsigned char *maxbuf) { const unsigned char *s0 = s; unsigned char c; if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); c = *s; if ((c & 0xC0) == 0xC0) return(2); while (*s) { if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); s += (*s) + 1; ND_TCHECK2(*s, 1); } return(PTR_DIFF(s, s0) + 1); trunc: return(-1); /* name goes past the end of the buffer */ }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,295
tensorflow
965b97e4a9650495cda5a8c210ef6684b4b9eceb
void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override { // Create a new SparseTensorSliceDatasetOp::Dataset, insert it in // the step container, and return it as the output. const Tensor* indices; OP_REQUIRES_OK(ctx, ctx->input("indices", &indices)); const Tensor* values; OP_REQUIRES_OK(ctx, ctx->input("values", &values)); const Tensor* dense_shape; OP_REQUIRES_OK(ctx, ctx->input("dense_shape", &dense_shape)); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(indices->shape()), errors::InvalidArgument( "Input indices should be a matrix but received shape ", indices->shape().DebugString())); const auto num_indices = indices->NumElements(); const auto num_values = values->NumElements(); if (num_indices == 0 || num_values == 0) { OP_REQUIRES(ctx, num_indices == num_values, errors::InvalidArgument( "If indices or values are empty, the other one must also " "be. Got indices of shape ", indices->shape().DebugString(), " and values of shape ", values->shape().DebugString())); } OP_REQUIRES(ctx, TensorShapeUtils::IsVector(values->shape()), errors::InvalidArgument( "Input values should be a vector but received shape ", indices->shape().DebugString())); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(dense_shape->shape()), errors::InvalidArgument( "Input shape should be a vector but received shape ", dense_shape->shape().DebugString())); // We currently ensure that `sparse_tensor` is ordered in the // batch dimension. // TODO(mrry): Investigate ways to avoid this unconditional check // if we can be sure that the sparse tensor was produced in an // appropriate order (e.g. by `tf.parse_example()` or a Dataset // that batches elements into rows of a SparseTensor). int64_t previous_batch_index = -1; for (int64_t i = 0; i < indices->dim_size(0); ++i) { int64_t next_batch_index = indices->matrix<int64_t>()(i, 0); OP_REQUIRES( ctx, next_batch_index >= previous_batch_index, errors::Unimplemented("The SparseTensor must be ordered in the batch " "dimension; handling arbitrarily ordered input " "is not currently supported.")); previous_batch_index = next_batch_index; } gtl::InlinedVector<int64_t, 8> std_order(dense_shape->NumElements(), 0); sparse::SparseTensor tensor; OP_REQUIRES_OK( ctx, sparse::SparseTensor::Create( *indices, *values, TensorShape(dense_shape->vec<int64_t>()), std_order, &tensor)); *output = new Dataset<T>(ctx, std::move(tensor)); }
1
CVE-2022-21736
CWE-476
NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Phase: Implementation If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented. Phase: Requirements Select a programming language that is not susceptible to these issues. Phase: Implementation Check the results of all functions that return a value and verify that the value is non-null before acting upon it. Effectiveness: Moderate Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665). Phase: Architecture and Design Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values. Phase: Implementation Explicitly initialize all variables and other data stores, either during declaration or just before the first usage.
3,676
Android
5a9753fca56f0eeb9f61e342b2fccffc364f9426
static void TearDownTestCase() { vpx_free(source_data_); source_data_ = NULL; vpx_free(reference_data_); reference_data_ = NULL; }
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).
15
openssl
00d965474b22b54e4275232bc71ee0c699c5cd21
static int aes_wrap_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_WRAP_CTX *wctx = EVP_C_DATA(EVP_AES_WRAP_CTX,ctx); if (!iv && !key) return 1; if (key) { if (EVP_CIPHER_CTX_encrypting(ctx)) AES_set_encrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &wctx->ks.ks); else AES_set_decrypt_key(key, EVP_CIPHER_CTX_key_length(ctx) * 8, &wctx->ks.ks); if (!iv) wctx->iv = NULL; } if (iv) { memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, EVP_CIPHER_CTX_iv_length(ctx)); wctx->iv = EVP_CIPHER_CTX_iv_noconst(ctx); } return 1; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,426
linux
57bc3d3ae8c14df3ceb4e17d26ddf9eeab304581
static int ax88179_led_setting(struct usbnet *dev) { u8 ledfd, value = 0; u16 tmp, ledact, ledlink, ledvalue = 0, delay = HZ / 10; unsigned long jtimeout; /* Check AX88179 version. UA1 or UA2*/ ax88179_read_cmd(dev, AX_ACCESS_MAC, GENERAL_STATUS, 1, 1, &value); if (!(value & AX_SECLD)) { /* UA1 */ value = AX_GPIO_CTRL_GPIO3EN | AX_GPIO_CTRL_GPIO2EN | AX_GPIO_CTRL_GPIO1EN; if (ax88179_write_cmd(dev, AX_ACCESS_MAC, AX_GPIO_CTRL, 1, 1, &value) < 0) return -EINVAL; } /* Check EEPROM */ if (!ax88179_check_eeprom(dev)) { value = 0x42; if (ax88179_write_cmd(dev, AX_ACCESS_MAC, AX_SROM_ADDR, 1, 1, &value) < 0) return -EINVAL; value = EEP_RD; if (ax88179_write_cmd(dev, AX_ACCESS_MAC, AX_SROM_CMD, 1, 1, &value) < 0) return -EINVAL; jtimeout = jiffies + delay; do { ax88179_read_cmd(dev, AX_ACCESS_MAC, AX_SROM_CMD, 1, 1, &value); if (time_after(jiffies, jtimeout)) return -EINVAL; } while (value & EEP_BUSY); ax88179_read_cmd(dev, AX_ACCESS_MAC, AX_SROM_DATA_HIGH, 1, 1, &value); ledvalue = (value << 8); ax88179_read_cmd(dev, AX_ACCESS_MAC, AX_SROM_DATA_LOW, 1, 1, &value); ledvalue |= value; /* load internal ROM for defaule setting */ if ((ledvalue == 0xFFFF) || ((ledvalue & LED_VALID) == 0)) ax88179_convert_old_led(dev, &ledvalue); } else if (!ax88179_check_efuse(dev, &ledvalue)) { if ((ledvalue == 0xFFFF) || ((ledvalue & LED_VALID) == 0)) ax88179_convert_old_led(dev, &ledvalue); } else { ax88179_convert_old_led(dev, &ledvalue); } tmp = GMII_PHY_PGSEL_EXT; ax88179_write_cmd(dev, AX_ACCESS_PHY, AX88179_PHY_ID, GMII_PHY_PAGE_SELECT, 2, &tmp); tmp = 0x2c; ax88179_write_cmd(dev, AX_ACCESS_PHY, AX88179_PHY_ID, GMII_PHYPAGE, 2, &tmp); ax88179_read_cmd(dev, AX_ACCESS_PHY, AX88179_PHY_ID, GMII_LED_ACT, 2, &ledact); ax88179_read_cmd(dev, AX_ACCESS_PHY, AX88179_PHY_ID, GMII_LED_LINK, 2, &ledlink); ledact &= GMII_LED_ACTIVE_MASK; ledlink &= GMII_LED_LINK_MASK; if (ledvalue & LED0_ACTIVE) ledact |= GMII_LED0_ACTIVE; if (ledvalue & LED1_ACTIVE) ledact |= GMII_LED1_ACTIVE; if (ledvalue & LED2_ACTIVE) ledact |= GMII_LED2_ACTIVE; if (ledvalue & LED0_LINK_10) ledlink |= GMII_LED0_LINK_10; if (ledvalue & LED1_LINK_10) ledlink |= GMII_LED1_LINK_10; if (ledvalue & LED2_LINK_10) ledlink |= GMII_LED2_LINK_10; if (ledvalue & LED0_LINK_100) ledlink |= GMII_LED0_LINK_100; if (ledvalue & LED1_LINK_100) ledlink |= GMII_LED1_LINK_100; if (ledvalue & LED2_LINK_100) ledlink |= GMII_LED2_LINK_100; if (ledvalue & LED0_LINK_1000) ledlink |= GMII_LED0_LINK_1000; if (ledvalue & LED1_LINK_1000) ledlink |= GMII_LED1_LINK_1000; if (ledvalue & LED2_LINK_1000) ledlink |= GMII_LED2_LINK_1000; tmp = ledact; ax88179_write_cmd(dev, AX_ACCESS_PHY, AX88179_PHY_ID, GMII_LED_ACT, 2, &tmp); tmp = ledlink; ax88179_write_cmd(dev, AX_ACCESS_PHY, AX88179_PHY_ID, GMII_LED_LINK, 2, &tmp); tmp = GMII_PHY_PGSEL_PAGE0; ax88179_write_cmd(dev, AX_ACCESS_PHY, AX88179_PHY_ID, GMII_PHY_PAGE_SELECT, 2, &tmp); /* LED full duplex setting */ ledfd = 0; if (ledvalue & LED0_FD) ledfd |= 0x01; else if ((ledvalue & LED0_USB3_MASK) == 0) ledfd |= 0x02; if (ledvalue & LED1_FD) ledfd |= 0x04; else if ((ledvalue & LED1_USB3_MASK) == 0) ledfd |= 0x08; if (ledvalue & LED2_FD) ledfd |= 0x10; else if ((ledvalue & LED2_USB3_MASK) == 0) ledfd |= 0x20; ax88179_write_cmd(dev, AX_ACCESS_MAC, AX_LEDCTRL, 1, 1, &ledfd); return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
17,754
linux
12d6e7538e2d418c08f082b1b44ffa5fb7270ed8
bool kvm_largepages_enabled(void) { return largepages_enabled; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,851
file
4a284c89d6ef11aca34da65da7d673050a5ea320
string_modifier_check(struct magic_set *ms, struct magic *m) { if ((ms->flags & MAGIC_CHECK) == 0) return 0; if (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0) { file_magwarn(ms, "'/BHhLl' modifiers are only allowed for pascal strings\n"); return -1; } switch (m->type) { case FILE_BESTRING16: case FILE_LESTRING16: if (m->str_flags != 0) { file_magwarn(ms, "no modifiers allowed for 16-bit strings\n"); return -1; } break; case FILE_STRING: case FILE_PSTRING: if ((m->str_flags & REGEX_OFFSET_START) != 0) { file_magwarn(ms, "'/%c' only allowed on regex and search\n", CHAR_REGEX_OFFSET_START); return -1; } break; case FILE_SEARCH: if (m->str_range == 0) { file_magwarn(ms, "missing range; defaulting to %d\n", STRING_DEFAULT_RANGE); m->str_range = STRING_DEFAULT_RANGE; return -1; } break; case FILE_REGEX: if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) { file_magwarn(ms, "'/%c' not allowed on regex\n", CHAR_COMPACT_WHITESPACE); return -1; } if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) { file_magwarn(ms, "'/%c' not allowed on regex\n", CHAR_COMPACT_OPTIONAL_WHITESPACE); return -1; } break; default: file_magwarn(ms, "coding error: m->type=%d\n", m->type); return -1; } return 0; }
1
CVE-2014-3538
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
8,169
linux
ac64115a66c18c01745bbd3c47a36b124e5fd8c0
int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext) { int r; /* Assume we're using HV mode when the HV module is loaded */ int hv_enabled = kvmppc_hv_ops ? 1 : 0; if (kvm) { /* * Hooray - we know which VM type we're running on. Depend on * that rather than the guess above. */ hv_enabled = is_kvmppc_hv_enabled(kvm); } switch (ext) { #ifdef CONFIG_BOOKE case KVM_CAP_PPC_BOOKE_SREGS: case KVM_CAP_PPC_BOOKE_WATCHDOG: case KVM_CAP_PPC_EPR: #else case KVM_CAP_PPC_SEGSTATE: case KVM_CAP_PPC_HIOR: case KVM_CAP_PPC_PAPR: #endif case KVM_CAP_PPC_UNSET_IRQ: case KVM_CAP_PPC_IRQ_LEVEL: case KVM_CAP_ENABLE_CAP: case KVM_CAP_ENABLE_CAP_VM: case KVM_CAP_ONE_REG: case KVM_CAP_IOEVENTFD: case KVM_CAP_DEVICE_CTRL: case KVM_CAP_IMMEDIATE_EXIT: r = 1; break; case KVM_CAP_PPC_PAIRED_SINGLES: case KVM_CAP_PPC_OSI: case KVM_CAP_PPC_GET_PVINFO: #if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC) case KVM_CAP_SW_TLB: #endif /* We support this only for PR */ r = !hv_enabled; break; #ifdef CONFIG_KVM_MPIC case KVM_CAP_IRQ_MPIC: r = 1; break; #endif #ifdef CONFIG_PPC_BOOK3S_64 case KVM_CAP_SPAPR_TCE: case KVM_CAP_SPAPR_TCE_64: /* fallthrough */ case KVM_CAP_SPAPR_TCE_VFIO: case KVM_CAP_PPC_RTAS: case KVM_CAP_PPC_FIXUP_HCALL: case KVM_CAP_PPC_ENABLE_HCALL: #ifdef CONFIG_KVM_XICS case KVM_CAP_IRQ_XICS: #endif r = 1; break; case KVM_CAP_PPC_ALLOC_HTAB: r = hv_enabled; break; #endif /* CONFIG_PPC_BOOK3S_64 */ #ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE case KVM_CAP_PPC_SMT: r = 0; if (kvm) { if (kvm->arch.emul_smt_mode > 1) r = kvm->arch.emul_smt_mode; else r = kvm->arch.smt_mode; } else if (hv_enabled) { if (cpu_has_feature(CPU_FTR_ARCH_300)) r = 1; else r = threads_per_subcore; } break; case KVM_CAP_PPC_SMT_POSSIBLE: r = 1; if (hv_enabled) { if (!cpu_has_feature(CPU_FTR_ARCH_300)) r = ((threads_per_subcore << 1) - 1); else /* P9 can emulate dbells, so allow any mode */ r = 8 | 4 | 2 | 1; } break; case KVM_CAP_PPC_RMA: r = 0; break; case KVM_CAP_PPC_HWRNG: r = kvmppc_hwrng_present(); break; case KVM_CAP_PPC_MMU_RADIX: r = !!(hv_enabled && radix_enabled()); break; case KVM_CAP_PPC_MMU_HASH_V3: r = !!(hv_enabled && !radix_enabled() && cpu_has_feature(CPU_FTR_ARCH_300)); break; #endif case KVM_CAP_SYNC_MMU: #ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE r = hv_enabled; #elif defined(KVM_ARCH_WANT_MMU_NOTIFIER) r = 1; #else r = 0; #endif break; #ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE case KVM_CAP_PPC_HTAB_FD: r = hv_enabled; break; #endif case KVM_CAP_NR_VCPUS: /* * Recommending a number of CPUs is somewhat arbitrary; we * return the number of present CPUs for -HV (since a host * will have secondary threads "offline"), and for other KVM * implementations just count online CPUs. */ if (hv_enabled) r = num_present_cpus(); else r = num_online_cpus(); break; case KVM_CAP_NR_MEMSLOTS: r = KVM_USER_MEM_SLOTS; break; case KVM_CAP_MAX_VCPUS: r = KVM_MAX_VCPUS; break; #ifdef CONFIG_PPC_BOOK3S_64 case KVM_CAP_PPC_GET_SMMU_INFO: r = 1; break; case KVM_CAP_SPAPR_MULTITCE: r = 1; break; case KVM_CAP_SPAPR_RESIZE_HPT: /* Disable this on POWER9 until code handles new HPTE format */ r = !!hv_enabled && !cpu_has_feature(CPU_FTR_ARCH_300); break; #endif #ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE case KVM_CAP_PPC_FWNMI: r = hv_enabled; break; #endif case KVM_CAP_PPC_HTM: r = cpu_has_feature(CPU_FTR_TM_COMP) && is_kvmppc_hv_enabled(kvm); break; default: r = 0; break; } return r; }
1
CVE-2017-15306
CWE-476
NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Phase: Implementation If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented. Phase: Requirements Select a programming language that is not susceptible to these issues. Phase: Implementation Check the results of all functions that return a value and verify that the value is non-null before acting upon it. Effectiveness: Moderate Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665). Phase: Architecture and Design Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values. Phase: Implementation Explicitly initialize all variables and other data stores, either during declaration or just before the first usage.
388
linux
f84598bd7c851f8b0bf8cd0d7c3be0d73c432ff4
save_microcode(struct mc_saved_data *mc_saved_data, struct microcode_intel **mc_saved_src, unsigned int mc_saved_count) { int i, j; struct microcode_intel **mc_saved_p; int ret; if (!mc_saved_count) return -EINVAL; /* * Copy new microcode data. */ mc_saved_p = kmalloc(mc_saved_count*sizeof(struct microcode_intel *), GFP_KERNEL); if (!mc_saved_p) return -ENOMEM; for (i = 0; i < mc_saved_count; i++) { struct microcode_intel *mc = mc_saved_src[i]; struct microcode_header_intel *mc_header = &mc->hdr; unsigned long mc_size = get_totalsize(mc_header); mc_saved_p[i] = kmalloc(mc_size, GFP_KERNEL); if (!mc_saved_p[i]) { ret = -ENOMEM; goto err; } if (!mc_saved_src[i]) { ret = -EINVAL; goto err; } memcpy(mc_saved_p[i], mc, mc_size); } /* * Point to newly saved microcode. */ mc_saved_data->mc_saved = mc_saved_p; mc_saved_data->mc_saved_count = mc_saved_count; return 0; err: for (j = 0; j <= i; j++) kfree(mc_saved_p[j]); kfree(mc_saved_p); return ret; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,978
linux
273ec51dd7ceaa76e038875d85061ec856d8905e
static int ppp_release(struct inode *unused, struct file *file) { struct ppp_file *pf = file->private_data; struct ppp *ppp; if (pf) { file->private_data = NULL; if (pf->kind == INTERFACE) { ppp = PF_TO_PPP(pf); if (file == ppp->owner) ppp_shutdown_interface(ppp); } if (atomic_dec_and_test(&pf->refcnt)) { switch (pf->kind) { case INTERFACE: ppp_destroy_interface(PF_TO_PPP(pf)); break; case CHANNEL: ppp_destroy_channel(PF_TO_CHANNEL(pf)); break; } } } return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,481
linux
0a54917c3fc295cb61f3fb52373c173fd3b69f48
static int orinoco_ioctl_getfreq(struct net_device *dev, struct iw_request_info *info, struct iw_freq *frq, char *extra) { struct orinoco_private *priv = ndev_priv(dev); int tmp; /* Locking done in there */ tmp = orinoco_hw_get_freq(priv); if (tmp < 0) return tmp; frq->m = tmp * 100000; frq->e = 1; return 0; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,547
winscp
49d876f2c5fc00bcedaa986a7cf6dedd6bf16f54
bool __fastcall TSCPFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/) { return false; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,957
xserver
215f894965df5fb0bb45b107d84524e700d2073c
ProcSendEvent(ClientPtr client) { WindowPtr pWin; WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */ DeviceIntPtr dev = PickPointer(client); DeviceIntPtr keybd = GetMaster(dev, MASTER_KEYBOARD); SpritePtr pSprite = dev->spriteInfo->sprite; REQUEST(xSendEventReq); REQUEST_SIZE_MATCH(xSendEventReq); /* libXext and other extension libraries may set the bit indicating * that this event came from a SendEvent request so remove it * since otherwise the event type may fail the range checks * and cause an invalid BadValue error to be returned. * * This is safe to do since we later add the SendEvent bit (0x80) * back in once we send the event to the client */ stuff->event.u.u.type &= ~(SEND_EVENT_BIT); /* The client's event type must be a core event type or one defined by an extension. */ if (!((stuff->event.u.u.type > X_Reply && stuff->event.u.u.type < LASTEvent) || (stuff->event.u.u.type >= EXTENSION_EVENT_BASE && stuff->event.u.u.type < (unsigned) lastEvent))) { client->errorValue = stuff->event.u.u.type; return BadValue; } if (stuff->event.u.u.type == ClientMessage && stuff->event.u.u.detail != 8 && stuff->event.u.u.detail != 16 && stuff->event.u.u.detail != 32) { } if (stuff->destination == PointerWindow) pWin = pSprite->win; else if (stuff->destination == InputFocus) { WindowPtr inputFocus = (keybd) ? keybd->focus->win : NoneWin; if (inputFocus == NoneWin) return Success; /* If the input focus is PointerRootWin, send the event to where the pointer is if possible, then perhaps propogate up to root. */ if (inputFocus == PointerRootWin) inputFocus = GetCurrentRootWindow(dev); if (IsParent(inputFocus, pSprite->win)) { effectiveFocus = inputFocus; pWin = pSprite->win; } else effectiveFocus = pWin = inputFocus; } else dixLookupWindow(&pWin, stuff->destination, client, DixSendAccess); if (!pWin) return BadWindow; if ((stuff->propagate != xFalse) && (stuff->propagate != xTrue)) { client->errorValue = stuff->propagate; return BadValue; } stuff->event.u.u.type |= SEND_EVENT_BIT; if (stuff->propagate) { for (; pWin; pWin = pWin->parent) { if (XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) return Success; if (DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab)) return Success; if (pWin == effectiveFocus) return Success; stuff->eventMask &= ~wDontPropagateMask(pWin); if (!stuff->eventMask) break; } } else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab); return Success; }
1
CVE-2017-10971
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,609
sysstat
fbc691eaaa10d0bcea6741d5a223dc3906106548
char *sccsid(void) { return (SCCSID); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,166
Chrome
fb83de09f2c986ee91741f3a2776feea0e18e3f6
views::View* OverlayWindowViews::controls_parent_view_for_testing() const { return controls_parent_view_.get(); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,337
linux
07f4d9d74a04aa7c72c5dae0ef97565f28f17b92
static long snd_disconnect_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { return -ENODEV; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,755
linux-stable
0c461cb727d146c9ef2d3e86214f498b78b7d125
static int ioctl_has_perm(const struct cred *cred, struct file *file, u32 requested, u16 cmd) { struct common_audit_data ad; struct file_security_struct *fsec = file->f_security; struct inode *inode = file_inode(file); struct inode_security_struct *isec; struct lsm_ioctlop_audit ioctl; u32 ssid = cred_sid(cred); int rc; u8 driver = cmd >> 8; u8 xperm = cmd & 0xff; ad.type = LSM_AUDIT_DATA_IOCTL_OP; ad.u.op = &ioctl; ad.u.op->cmd = cmd; ad.u.op->path = file->f_path; if (ssid != fsec->sid) { rc = avc_has_perm(ssid, fsec->sid, SECCLASS_FD, FD__USE, &ad); if (rc) goto out; } if (unlikely(IS_PRIVATE(inode))) return 0; isec = inode_security(inode); rc = avc_has_extended_perms(ssid, isec->sid, isec->sclass, requested, driver, xperm, &ad); out: return rc; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
10,991
Chrome
828eab2216a765dea92575c290421c115b8ad028
DailyDataSavingUpdate( const char* pref_original, const char* pref_received, PrefService* pref_service) : pref_original_(pref_original), pref_received_(pref_received), original_update_(pref_service, pref_original_), received_update_(pref_service, pref_received_) { }
1
CVE-2013-2858
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.
5,032
w3m
a088e0263c48ba406a7ae0932a1ae64a25be7acd
shiftAnchorPosition(AnchorList *al, HmarkerList *hl, int line, int pos, int shift) { Anchor *a; size_t b, e, s = 0; int cmp; if (al == NULL || al->nanchor == 0) return; s = al->nanchor / 2; for (b = 0, e = al->nanchor - 1; b <= e; s = (b + e + 1) / 2) { a = &al->anchors[s]; cmp = onAnchor(a, line, pos); if (cmp == 0) break; else if (cmp > 0) b = s + 1; else if (s == 0) break; else e = s - 1; } for (; s < al->nanchor; s++) { a = &al->anchors[s]; if (a->start.line > line) break; if (a->start.pos > pos) { a->start.pos += shift; if (hl && hl->marks && hl->marks[a->hseq].line == line) hl->marks[a->hseq].pos = a->start.pos; } if (a->end.pos >= pos) a->end.pos += shift; } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,533
ImageMagick
14e606db148d6ebcaae20f1e1d6d71903ca4a556
static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception) { char format[MagickPathExtent], keyword[MagickPathExtent], tag[MagickPathExtent], value[MagickPathExtent]; double gamma; Image *image; int c; MagickBooleanType status, value_expected; register Quantum *q; register ssize_t i, x; register unsigned char *p; ssize_t count, y; unsigned char *end, pixel[4], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Decode image header. */ image->columns=0; image->rows=0; *format='\0'; c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } while (isgraph(c) && (image->columns == 0) && (image->rows == 0)) { if (c == (int) '#') { char *comment; register char *p; size_t length; /* Read comment-- any text between # and end-of-line. */ length=MagickPathExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if ((c == EOF) || (c == (int) '\n')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MagickPathExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) == MagickFalse) c=ReadBlobByte(image); else { register char *p; /* Determine a keyword and its value. */ p=keyword; do { if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c) || (c == '_')); *p='\0'; value_expected=MagickFalse; while ((isspace((int) ((unsigned char) c)) != 0) || (c == '=')) { if (c == '=') value_expected=MagickTrue; c=ReadBlobByte(image); } if (LocaleCompare(keyword,"Y") == 0) value_expected=MagickTrue; if (value_expected == MagickFalse) continue; p=value; while ((c != '\n') && (c != '\0') && (c != EOF)) { if ((size_t) (p-value) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"format") == 0) { (void) CopyMagickString(format,value,MagickPathExtent); break; } (void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(value,(char **) NULL); break; } (void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"primaries") == 0) { float chromaticity[6], white_point[2]; int count; count=sscanf(value,"%g %g %g %g %g %g %g %g",&chromaticity[0], &chromaticity[1],&chromaticity[2],&chromaticity[3], &chromaticity[4],&chromaticity[5],&white_point[0], &white_point[1]); if (count == 8) { image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; image->chromaticity.white_point.x=white_point[0], image->chromaticity.white_point.y=white_point[1]; } break; } (void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'Y': case 'y': { char target[] = "Y"; if (strcmp(keyword,target) == 0) { int height, width; if (sscanf(value,"%d +X %d",&height,&width) == 2) { image->columns=(size_t) width; image->rows=(size_t) height; } break; } (void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } default: { (void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } } } if ((image->columns == 0) && (image->rows == 0)) while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } if ((LocaleCompare(format,"32-bit_rle_rgbe") != 0) && (LocaleCompare(format,"32-bit_rle_xyze") != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); (void) SetImageColorspace(image,RGBColorspace,exception); if (LocaleCompare(format,"32-bit_rle_xyze") == 0) (void) SetImageColorspace(image,XYZColorspace,exception); image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ? NoCompression : RLECompression; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Read RGBE (red+green+blue+exponent) pixels. */ pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { if (image->compression != RLECompression) { count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels); if (count != (ssize_t) (4*image->columns*sizeof(*pixels))) break; } else { count=ReadBlob(image,4*sizeof(*pixel),pixel); if (count != 4) break; if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns) { (void) memcpy(pixels,pixel,4*sizeof(*pixel)); count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4); image->compression=NoCompression; } else { p=pixels; for (i=0; i < 4; i++) { end=&pixels[(i+1)*image->columns]; while (p < end) { count=ReadBlob(image,2*sizeof(*pixel),pixel); if (count < 1) break; if (pixel[0] > 128) { count=(ssize_t) pixel[0]-128; if ((count == 0) || (count > (ssize_t) (end-p))) break; while (count-- > 0) *p++=pixel[1]; } else { count=(ssize_t) pixel[0]; if ((count == 0) || (count > (ssize_t) (end-p))) break; *p++=pixel[1]; if (--count > 0) { count=ReadBlob(image,(size_t) count*sizeof(*p),p); if (count < 1) break; p+=count; } } } } } } q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; i=0; for (x=0; x < (ssize_t) image->columns; x++) { if (image->compression == RLECompression) { pixel[0]=pixels[x]; pixel[1]=pixels[x+image->columns]; pixel[2]=pixels[x+2*image->columns]; pixel[3]=pixels[x+3*image->columns]; } else { pixel[0]=pixels[i++]; pixel[1]=pixels[i++]; pixel[2]=pixels[i++]; pixel[3]=pixels[i++]; } SetPixelRed(image,0,q); SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); if (pixel[3] != 0) { gamma=pow(2.0,pixel[3]-(128.0+8.0)); SetPixelRed(image,ClampToQuantum(QuantumRange*gamma*pixel[0]),q); SetPixelGreen(image,ClampToQuantum(QuantumRange*gamma*pixel[1]),q); SetPixelBlue(image,ClampToQuantum(QuantumRange*gamma*pixel[2]),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,109
rsync
c8255147b06b74dad940d32f9cef5fbe17595239
static void build_hash_table(struct sum_struct *s) { static uint32 alloc_size; int32 i; /* Dynamically calculate the hash table size so that the hash load * for big files is about 80%. A number greater than the traditional * size must be odd or s2 will not be able to span the entire set. */ tablesize = (uint32)(s->count/8) * 10 + 11; if (tablesize < TRADITIONAL_TABLESIZE) tablesize = TRADITIONAL_TABLESIZE; if (tablesize > alloc_size || tablesize < alloc_size - 16*1024) { if (hash_table) free(hash_table); hash_table = new_array(int32, tablesize); if (!hash_table) out_of_memory("build_hash_table"); alloc_size = tablesize; } memset(hash_table, 0xFF, tablesize * sizeof hash_table[0]); if (tablesize == TRADITIONAL_TABLESIZE) { for (i = 0; i < s->count; i++) { uint32 t = SUM2HASH(s->sums[i].sum1); s->sums[i].chain = hash_table[t]; hash_table[t] = i; } } else { for (i = 0; i < s->count; i++) { uint32 t = BIG_SUM2HASH(s->sums[i].sum1); s->sums[i].chain = hash_table[t]; hash_table[t] = i; } } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,795
linux
ded89912156b1a47d940a0c954c43afbabd0c42c
brcmf_cfg80211_start_ap(struct wiphy *wiphy, struct net_device *ndev, struct cfg80211_ap_settings *settings) { s32 ie_offset; struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy); struct brcmf_if *ifp = netdev_priv(ndev); const struct brcmf_tlv *ssid_ie; const struct brcmf_tlv *country_ie; struct brcmf_ssid_le ssid_le; s32 err = -EPERM; const struct brcmf_tlv *rsn_ie; const struct brcmf_vs_tlv *wpa_ie; struct brcmf_join_params join_params; enum nl80211_iftype dev_role; struct brcmf_fil_bss_enable_le bss_enable; u16 chanspec = chandef_to_chanspec(&cfg->d11inf, &settings->chandef); bool mbss; int is_11d; brcmf_dbg(TRACE, "ctrlchn=%d, center=%d, bw=%d, beacon_interval=%d, dtim_period=%d,\n", settings->chandef.chan->hw_value, settings->chandef.center_freq1, settings->chandef.width, settings->beacon_interval, settings->dtim_period); brcmf_dbg(TRACE, "ssid=%s(%zu), auth_type=%d, inactivity_timeout=%d\n", settings->ssid, settings->ssid_len, settings->auth_type, settings->inactivity_timeout); dev_role = ifp->vif->wdev.iftype; mbss = ifp->vif->mbss; /* store current 11d setting */ brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_REGULATORY, &ifp->vif->is_11d); country_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail, settings->beacon.tail_len, WLAN_EID_COUNTRY); is_11d = country_ie ? 1 : 0; memset(&ssid_le, 0, sizeof(ssid_le)); if (settings->ssid == NULL || settings->ssid_len == 0) { ie_offset = DOT11_MGMT_HDR_LEN + DOT11_BCN_PRB_FIXED_LEN; ssid_ie = brcmf_parse_tlvs( (u8 *)&settings->beacon.head[ie_offset], settings->beacon.head_len - ie_offset, WLAN_EID_SSID); if (!ssid_ie) return -EINVAL; memcpy(ssid_le.SSID, ssid_ie->data, ssid_ie->len); ssid_le.SSID_len = cpu_to_le32(ssid_ie->len); brcmf_dbg(TRACE, "SSID is (%s) in Head\n", ssid_le.SSID); } else { memcpy(ssid_le.SSID, settings->ssid, settings->ssid_len); ssid_le.SSID_len = cpu_to_le32((u32)settings->ssid_len); } if (!mbss) { brcmf_set_mpc(ifp, 0); brcmf_configure_arp_nd_offload(ifp, false); } /* find the RSN_IE */ rsn_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail, settings->beacon.tail_len, WLAN_EID_RSN); /* find the WPA_IE */ wpa_ie = brcmf_find_wpaie((u8 *)settings->beacon.tail, settings->beacon.tail_len); if ((wpa_ie != NULL || rsn_ie != NULL)) { brcmf_dbg(TRACE, "WPA(2) IE is found\n"); if (wpa_ie != NULL) { /* WPA IE */ err = brcmf_configure_wpaie(ifp, wpa_ie, false); if (err < 0) goto exit; } else { struct brcmf_vs_tlv *tmp_ie; tmp_ie = (struct brcmf_vs_tlv *)rsn_ie; /* RSN IE */ err = brcmf_configure_wpaie(ifp, tmp_ie, true); if (err < 0) goto exit; } } else { brcmf_dbg(TRACE, "No WPA(2) IEs found\n"); brcmf_configure_opensecurity(ifp); } brcmf_config_ap_mgmt_ie(ifp->vif, &settings->beacon); /* Parameters shared by all radio interfaces */ if (!mbss) { if (is_11d != ifp->vif->is_11d) { err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_REGULATORY, is_11d); if (err < 0) { brcmf_err("Regulatory Set Error, %d\n", err); goto exit; } } if (settings->beacon_interval) { err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_BCNPRD, settings->beacon_interval); if (err < 0) { brcmf_err("Beacon Interval Set Error, %d\n", err); goto exit; } } if (settings->dtim_period) { err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_DTIMPRD, settings->dtim_period); if (err < 0) { brcmf_err("DTIM Interval Set Error, %d\n", err); goto exit; } } if ((dev_role == NL80211_IFTYPE_AP) && ((ifp->ifidx == 0) || !brcmf_feat_is_enabled(ifp, BRCMF_FEAT_RSDB))) { err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1); if (err < 0) { brcmf_err("BRCMF_C_DOWN error %d\n", err); goto exit; } brcmf_fil_iovar_int_set(ifp, "apsta", 0); } err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_INFRA, 1); if (err < 0) { brcmf_err("SET INFRA error %d\n", err); goto exit; } } else if (WARN_ON(is_11d != ifp->vif->is_11d)) { /* Multiple-BSS should use same 11d configuration */ err = -EINVAL; goto exit; } /* Interface specific setup */ if (dev_role == NL80211_IFTYPE_AP) { if ((brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MBSS)) && (!mbss)) brcmf_fil_iovar_int_set(ifp, "mbss", 1); err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_AP, 1); if (err < 0) { brcmf_err("setting AP mode failed %d\n", err); goto exit; } if (!mbss) { /* Firmware 10.x requires setting channel after enabling * AP and before bringing interface up. */ err = brcmf_fil_iovar_int_set(ifp, "chanspec", chanspec); if (err < 0) { brcmf_err("Set Channel failed: chspec=%d, %d\n", chanspec, err); goto exit; } } err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 1); if (err < 0) { brcmf_err("BRCMF_C_UP error (%d)\n", err); goto exit; } /* On DOWN the firmware removes the WEP keys, reconfigure * them if they were set. */ brcmf_cfg80211_reconfigure_wep(ifp); memset(&join_params, 0, sizeof(join_params)); /* join parameters starts with ssid */ memcpy(&join_params.ssid_le, &ssid_le, sizeof(ssid_le)); /* create softap */ err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID, &join_params, sizeof(join_params)); if (err < 0) { brcmf_err("SET SSID error (%d)\n", err); goto exit; } if (settings->hidden_ssid) { err = brcmf_fil_iovar_int_set(ifp, "closednet", 1); if (err) { brcmf_err("closednet error (%d)\n", err); goto exit; } } brcmf_dbg(TRACE, "AP mode configuration complete\n"); } else if (dev_role == NL80211_IFTYPE_P2P_GO) { err = brcmf_fil_iovar_int_set(ifp, "chanspec", chanspec); if (err < 0) { brcmf_err("Set Channel failed: chspec=%d, %d\n", chanspec, err); goto exit; } err = brcmf_fil_bsscfg_data_set(ifp, "ssid", &ssid_le, sizeof(ssid_le)); if (err < 0) { brcmf_err("setting ssid failed %d\n", err); goto exit; } bss_enable.bsscfgidx = cpu_to_le32(ifp->bsscfgidx); bss_enable.enable = cpu_to_le32(1); err = brcmf_fil_iovar_data_set(ifp, "bss", &bss_enable, sizeof(bss_enable)); if (err < 0) { brcmf_err("bss_enable config failed %d\n", err); goto exit; } brcmf_dbg(TRACE, "GO mode configuration complete\n"); } else { WARN_ON(1); } set_bit(BRCMF_VIF_STATUS_AP_CREATED, &ifp->vif->sme_state); brcmf_net_setcarrier(ifp, true); exit: if ((err) && (!mbss)) { brcmf_set_mpc(ifp, 1); brcmf_configure_arp_nd_offload(ifp, true); } return err; }
1
CVE-2016-8658
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,047
linux
a4780adeefd042482f624f5e0d577bf9cdcbb760
long arch_ptrace(struct task_struct *child, long request, unsigned long addr, unsigned long data) { int ret; unsigned long __user *datap = (unsigned long __user *) data; switch (request) { case PTRACE_PEEKUSR: ret = ptrace_read_user(child, addr, datap); break; case PTRACE_POKEUSR: ret = ptrace_write_user(child, addr, data); break; case PTRACE_GETREGS: ret = copy_regset_to_user(child, &user_arm_view, REGSET_GPR, 0, sizeof(struct pt_regs), datap); break; case PTRACE_SETREGS: ret = copy_regset_from_user(child, &user_arm_view, REGSET_GPR, 0, sizeof(struct pt_regs), datap); break; case PTRACE_GETFPREGS: ret = copy_regset_to_user(child, &user_arm_view, REGSET_FPR, 0, sizeof(union fp_state), datap); break; case PTRACE_SETFPREGS: ret = copy_regset_from_user(child, &user_arm_view, REGSET_FPR, 0, sizeof(union fp_state), datap); break; #ifdef CONFIG_IWMMXT case PTRACE_GETWMMXREGS: ret = ptrace_getwmmxregs(child, datap); break; case PTRACE_SETWMMXREGS: ret = ptrace_setwmmxregs(child, datap); break; #endif case PTRACE_GET_THREAD_AREA: ret = put_user(task_thread_info(child)->tp_value, datap); break; case PTRACE_SET_SYSCALL: task_thread_info(child)->syscall = data; ret = 0; break; #ifdef CONFIG_CRUNCH case PTRACE_GETCRUNCHREGS: ret = ptrace_getcrunchregs(child, datap); break; case PTRACE_SETCRUNCHREGS: ret = ptrace_setcrunchregs(child, datap); break; #endif #ifdef CONFIG_VFP case PTRACE_GETVFPREGS: ret = copy_regset_to_user(child, &user_arm_view, REGSET_VFP, 0, ARM_VFPREGS_SIZE, datap); break; case PTRACE_SETVFPREGS: ret = copy_regset_from_user(child, &user_arm_view, REGSET_VFP, 0, ARM_VFPREGS_SIZE, datap); break; #endif #ifdef CONFIG_HAVE_HW_BREAKPOINT case PTRACE_GETHBPREGS: if (ptrace_get_breakpoints(child) < 0) return -ESRCH; ret = ptrace_gethbpregs(child, addr, (unsigned long __user *)data); ptrace_put_breakpoints(child); break; case PTRACE_SETHBPREGS: if (ptrace_get_breakpoints(child) < 0) return -ESRCH; ret = ptrace_sethbpregs(child, addr, (unsigned long __user *)data); ptrace_put_breakpoints(child); break; #endif default: ret = ptrace_request(child, request, addr, data); break; } return ret; }
1
CVE-2014-9870
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
Not Found in CWE Page
3,408
ImageMagick
6f1879d498bcc5cce12fe0c5decb8dbc0f608e5d
static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); if (channels == 1 || type == -2) SetPixelGray(image,pixel,q); if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); if (image->depth == 1) { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPixelIndex(image,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : 255,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) GetPixelIndex(image,q),q); q+=GetPixelChannels(image); x++; } x--; continue; } } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelGreen(image,pixel,q); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(image,pixel,q); else SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } default: break; } q+=GetPixelChannels(image); } return(SyncAuthenticPixels(image,exception)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,151
exim
88a5ee399db9c15c2a94cd95aae6f364afab3249
find_variable(uschar *name, BOOL exists_only, BOOL skipping, int *newsize) { var_entry * vp; uschar *s, *domain; uschar **ss; void * val; /* Handle ACL variables, whose names are of the form acl_cxxx or acl_mxxx. Originally, xxx had to be a number in the range 0-9 (later 0-19), but from release 4.64 onwards arbitrary names are permitted, as long as the first 5 characters are acl_c or acl_m and the sixth is either a digit or an underscore (this gave backwards compatibility at the changeover). There may be built-in variables whose names start acl_ but they should never start in this way. This slightly messy specification is a consequence of the history, needless to say. If an ACL variable does not exist, treat it as empty, unless strict_acl_vars is set, in which case give an error. */ if ((Ustrncmp(name, "acl_c", 5) == 0 || Ustrncmp(name, "acl_m", 5) == 0) && !isalpha(name[5])) { tree_node *node = tree_search((name[4] == 'c')? acl_var_c : acl_var_m, name + 4); return (node == NULL)? (strict_acl_vars? NULL : US"") : node->data.ptr; } /* Handle $auth<n> variables. */ if (Ustrncmp(name, "auth", 4) == 0) { uschar *endptr; int n = Ustrtoul(name + 4, &endptr, 10); if (*endptr == 0 && n != 0 && n <= AUTH_VARS) return (auth_vars[n-1] == NULL)? US"" : auth_vars[n-1]; } /* For all other variables, search the table */ if (!(vp = find_var_ent(name))) return NULL; /* Unknown variable name */ /* Found an existing variable. If in skipping state, the value isn't needed, and we want to avoid processing (such as looking up the host name). */ if (skipping) return US""; val = vp->value; switch (vp->type) { case vtype_filter_int: if (!filter_running) return NULL; /* Fall through */ /* VVVVVVVVVVVV */ case vtype_int: sprintf(CS var_buffer, "%d", *(int *)(val)); /* Integer */ return var_buffer; case vtype_ino: sprintf(CS var_buffer, "%ld", (long int)(*(ino_t *)(val))); /* Inode */ return var_buffer; case vtype_gid: sprintf(CS var_buffer, "%ld", (long int)(*(gid_t *)(val))); /* gid */ return var_buffer; case vtype_uid: sprintf(CS var_buffer, "%ld", (long int)(*(uid_t *)(val))); /* uid */ return var_buffer; case vtype_bool: sprintf(CS var_buffer, "%s", *(BOOL *)(val) ? "yes" : "no"); /* bool */ return var_buffer; case vtype_stringptr: /* Pointer to string */ s = *((uschar **)(val)); return (s == NULL)? US"" : s; case vtype_pid: sprintf(CS var_buffer, "%d", (int)getpid()); /* pid */ return var_buffer; case vtype_load_avg: sprintf(CS var_buffer, "%d", OS_GETLOADAVG()); /* load_average */ return var_buffer; case vtype_host_lookup: /* Lookup if not done so */ if (sender_host_name == NULL && sender_host_address != NULL && !host_lookup_failed && host_name_lookup() == OK) host_build_sender_fullhost(); return (sender_host_name == NULL)? US"" : sender_host_name; case vtype_localpart: /* Get local part from address */ s = *((uschar **)(val)); if (s == NULL) return US""; domain = Ustrrchr(s, '@'); if (domain == NULL) return s; if (domain - s > sizeof(var_buffer) - 1) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "local part longer than " SIZE_T_FMT " in string expansion", sizeof(var_buffer)); Ustrncpy(var_buffer, s, domain - s); var_buffer[domain - s] = 0; return var_buffer; case vtype_domain: /* Get domain from address */ s = *((uschar **)(val)); if (s == NULL) return US""; domain = Ustrrchr(s, '@'); return (domain == NULL)? US"" : domain + 1; case vtype_msgheaders: return find_header(NULL, exists_only, newsize, FALSE, NULL); case vtype_msgheaders_raw: return find_header(NULL, exists_only, newsize, TRUE, NULL); case vtype_msgbody: /* Pointer to msgbody string */ case vtype_msgbody_end: /* Ditto, the end of the msg */ ss = (uschar **)(val); if (*ss == NULL && deliver_datafile >= 0) /* Read body when needed */ { uschar *body; off_t start_offset = SPOOL_DATA_START_OFFSET; int len = message_body_visible; if (len > message_size) len = message_size; *ss = body = store_malloc(len+1); body[0] = 0; if (vp->type == vtype_msgbody_end) { struct stat statbuf; if (fstat(deliver_datafile, &statbuf) == 0) { start_offset = statbuf.st_size - len; if (start_offset < SPOOL_DATA_START_OFFSET) start_offset = SPOOL_DATA_START_OFFSET; } } lseek(deliver_datafile, start_offset, SEEK_SET); len = read(deliver_datafile, body, len); if (len > 0) { body[len] = 0; if (message_body_newlines) /* Separate loops for efficiency */ { while (len > 0) { if (body[--len] == 0) body[len] = ' '; } } else { while (len > 0) { if (body[--len] == '\n' || body[len] == 0) body[len] = ' '; } } } } return (*ss == NULL)? US"" : *ss; case vtype_todbsdin: /* BSD inbox time of day */ return tod_stamp(tod_bsdin); case vtype_tode: /* Unix epoch time of day */ return tod_stamp(tod_epoch); case vtype_todel: /* Unix epoch/usec time of day */ return tod_stamp(tod_epoch_l); case vtype_todf: /* Full time of day */ return tod_stamp(tod_full); case vtype_todl: /* Log format time of day */ return tod_stamp(tod_log_bare); /* (without timezone) */ case vtype_todzone: /* Time zone offset only */ return tod_stamp(tod_zone); case vtype_todzulu: /* Zulu time */ return tod_stamp(tod_zulu); case vtype_todlf: /* Log file datestamp tod */ return tod_stamp(tod_log_datestamp_daily); case vtype_reply: /* Get reply address */ s = find_header(US"reply-to:", exists_only, newsize, TRUE, headers_charset); if (s != NULL) while (isspace(*s)) s++; if (s == NULL || *s == 0) { *newsize = 0; /* For the *s==0 case */ s = find_header(US"from:", exists_only, newsize, TRUE, headers_charset); } if (s != NULL) { uschar *t; while (isspace(*s)) s++; for (t = s; *t != 0; t++) if (*t == '\n') *t = ' '; while (t > s && isspace(t[-1])) t--; *t = 0; } return (s == NULL)? US"" : s; case vtype_string_func: { uschar * (*fn)() = val; return fn(); } case vtype_pspace: { int inodes; sprintf(CS var_buffer, "%d", receive_statvfs(val == (void *)TRUE, &inodes)); } return var_buffer; case vtype_pinodes: { int inodes; (void) receive_statvfs(val == (void *)TRUE, &inodes); sprintf(CS var_buffer, "%d", inodes); } return var_buffer; case vtype_cert: return *(void **)val ? US"<cert>" : US""; #ifndef DISABLE_DKIM case vtype_dkim: return dkim_exim_expand_query((int)(long)val); #endif } }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,744
ImageMagick
edc7d3035883ddca8413e4fe7689aa2e579ef04a
static void *DestroyLocaleNode(void *locale_info) { register LocaleInfo *p; p=(LocaleInfo *) locale_info; if (p->path != (char *) NULL) p->path=DestroyString(p->path); if (p->tag != (char *) NULL) p->tag=DestroyString(p->tag); if (p->message != (char *) NULL) p->message=DestroyString(p->message); return(RelinquishMagickMemory(p)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,647
taglib
ab8a0ee8937256311e649a88e8ddd7c7f870ad59
void Ogg::XiphComment::parse(const ByteVector &data) { // The first thing in the comment data is the vendor ID length, followed by a // UTF8 string with the vendor ID. uint pos = 0; int vendorLength = data.mid(0, 4).toUInt(false); pos += 4; d->vendorID = String(data.mid(pos, vendorLength), String::UTF8); pos += vendorLength; // Next the number of fields in the comment vector. uint commentFields = data.mid(pos, 4).toUInt(false); pos += 4; if(commentFields > (data.size() - 8) / 4) { return; } for(uint i = 0; i < commentFields; i++) { // Each comment field is in the format "KEY=value" in a UTF8 string and has // 4 bytes before the text starts that gives the length. uint commentLength = data.mid(pos, 4).toUInt(false); pos += 4; String comment = String(data.mid(pos, commentLength), String::UTF8); pos += commentLength; if(pos > data.size()) { break; } int commentSeparatorPosition = comment.find("="); if(commentSeparatorPosition == -1) { break; } String key = comment.substr(0, commentSeparatorPosition); String value = comment.substr(commentSeparatorPosition + 1); addField(key, value, false); } }
1
CVE-2012-1108
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
8,571
tensorflow
b1b323042264740c398140da32e93fb9c2c9f33e
explicit CTCGreedyDecoderOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("merge_repeated", &merge_repeated_)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,481
openldap
a08a2db4063f54a6217a0f091aebd02f8bdb482e
fe_op_modrdn( Operation *op, SlapReply *rs ) { struct berval dest_ndn = BER_BVNULL, dest_pndn, pdn = BER_BVNULL; BackendDB *op_be, *bd = op->o_bd; ber_slen_t diff; if( op->o_req_ndn.bv_len == 0 ) { Debug( LDAP_DEBUG_ANY, "%s do_modrdn: root dse!\n", op->o_log_prefix ); send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM, "cannot rename the root DSE" ); goto cleanup; } else if ( bvmatch( &op->o_req_ndn, &frontendDB->be_schemandn ) ) { Debug( LDAP_DEBUG_ANY, "%s do_modrdn: subschema subentry: %s (%ld)\n", op->o_log_prefix, frontendDB->be_schemandn.bv_val, (long)frontendDB->be_schemandn.bv_len ); send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM, "cannot rename subschema subentry" ); goto cleanup; } if( op->orr_nnewSup ) { dest_pndn = *op->orr_nnewSup; } else { dnParent( &op->o_req_ndn, &dest_pndn ); } build_new_dn( &dest_ndn, &dest_pndn, &op->orr_nnewrdn, op->o_tmpmemctx ); diff = (ber_slen_t) dest_ndn.bv_len - (ber_slen_t) op->o_req_ndn.bv_len; if ( diff > 0 ? dnIsSuffix( &dest_ndn, &op->o_req_ndn ) : diff < 0 && dnIsSuffix( &op->o_req_ndn, &dest_ndn ) ) { send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM, diff > 0 ? "cannot place an entry below itself" : "cannot place an entry above itself" ); goto cleanup; } /* * We could be serving multiple database backends. Select the * appropriate one, or send a referral to our "referral server" * if we don't hold it. */ op->o_bd = select_backend( &op->o_req_ndn, 1 ); if ( op->o_bd == NULL ) { op->o_bd = bd; rs->sr_ref = referral_rewrite( default_referral, NULL, &op->o_req_dn, LDAP_SCOPE_DEFAULT ); if (!rs->sr_ref) rs->sr_ref = default_referral; if ( rs->sr_ref != NULL ) { rs->sr_err = LDAP_REFERRAL; send_ldap_result( op, rs ); if (rs->sr_ref != default_referral) ber_bvarray_free( rs->sr_ref ); } else { send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM, "no global superior knowledge" ); } goto cleanup; } /* If we've got a glued backend, check the real backend */ op_be = op->o_bd; if ( SLAP_GLUE_INSTANCE( op->o_bd )) { op->o_bd = select_backend( &op->o_req_ndn, 0 ); } /* check restrictions */ if( backend_check_restrictions( op, rs, NULL ) != LDAP_SUCCESS ) { send_ldap_result( op, rs ); goto cleanup; } /* check for referrals */ if ( backend_check_referrals( op, rs ) != LDAP_SUCCESS ) { goto cleanup; } /* check that destination DN is in the same backend as source DN */ if ( select_backend( &dest_ndn, 0 ) != op->o_bd ) { send_ldap_error( op, rs, LDAP_AFFECTS_MULTIPLE_DSAS, "cannot rename between DSAs" ); goto cleanup; } /* * do the modrdn if 1 && (2 || 3) * 1) there is a modrdn function implemented in this backend; * 2) this backend is the provider for what it holds; * 3) it's a replica and the dn supplied is the update_ndn. */ if ( op->o_bd->be_modrdn ) { /* do the update here */ int repl_user = be_isupdate( op ); if ( !SLAP_SINGLE_SHADOW(op->o_bd) || repl_user ) { op->o_bd = op_be; op->o_bd->be_modrdn( op, rs ); if ( op->o_bd->be_delete ) { struct berval org_req_dn = BER_BVNULL; struct berval org_req_ndn = BER_BVNULL; struct berval org_dn = BER_BVNULL; struct berval org_ndn = BER_BVNULL; int org_managedsait; org_req_dn = op->o_req_dn; org_req_ndn = op->o_req_ndn; org_dn = op->o_dn; org_ndn = op->o_ndn; org_managedsait = get_manageDSAit( op ); op->o_dn = op->o_bd->be_rootdn; op->o_ndn = op->o_bd->be_rootndn; op->o_managedsait = SLAP_CONTROL_NONCRITICAL; while ( rs->sr_err == LDAP_SUCCESS && op->o_delete_glue_parent ) { op->o_delete_glue_parent = 0; if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) { slap_callback cb = { NULL }; cb.sc_response = slap_null_cb; dnParent( &op->o_req_ndn, &pdn ); op->o_req_dn = pdn; op->o_req_ndn = pdn; op->o_callback = &cb; op->o_bd->be_delete( op, rs ); } else { break; } } op->o_managedsait = org_managedsait; op->o_dn = org_dn; op->o_ndn = org_ndn; op->o_req_dn = org_req_dn; op->o_req_ndn = org_req_ndn; op->o_delete_glue_parent = 0; } } else { BerVarray defref = op->o_bd->be_update_refs ? op->o_bd->be_update_refs : default_referral; if ( defref != NULL ) { rs->sr_ref = referral_rewrite( defref, NULL, &op->o_req_dn, LDAP_SCOPE_DEFAULT ); if (!rs->sr_ref) rs->sr_ref = defref; rs->sr_err = LDAP_REFERRAL; send_ldap_result( op, rs ); if (rs->sr_ref != defref) ber_bvarray_free( rs->sr_ref ); } else { send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM, "shadow context; no update referral" ); } } } else { send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM, "operation not supported within namingContext" ); } cleanup:; if ( dest_ndn.bv_val != NULL ) ber_memfree_x( dest_ndn.bv_val, op->o_tmpmemctx ); op->o_bd = bd; return rs->sr_err; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
23,609
Chrome
116d0963cadfbf55ef2ec3d13781987c4d80517a
~PrintPreviewDataStore() {}
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
14,618
php-src
97eff7eb57fc2320c267a949cffd622c38712484?w=1
PHP_NAMED_FUNCTION(zif_locale_set_default) { char* locale_name = NULL; int len=0; if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &locale_name ,&len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_set_default: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(len == 0) { locale_name = (char *)uloc_getDefault() ; len = strlen(locale_name); } zend_alter_ini_entry(LOCALE_INI_NAME, sizeof(LOCALE_INI_NAME), locale_name, len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); RETURN_TRUE; }
1
CVE-2016-5093
CWE-125
Out-of-bounds Read
The product reads data past the end, or before the beginning, of the intended buffer.
Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs. Phase: Architecture and Design Strategy: Language Selection Use a language that provides appropriate memory abstractions.
5,619
FreeRDP
e2745807c4c3e0a590c0f69a9b655dc74ebaa03e
SCOPE_LIST* license_new_scope_list() { SCOPE_LIST* scopeList; scopeList = (SCOPE_LIST*) malloc(sizeof(SCOPE_LIST)); scopeList->count = 0; scopeList->array = NULL; return scopeList; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
16,883
linux
dee1f973ca341c266229faa5a1a5bb268bed3531
static int ext4_split_unwritten_extents(handle_t *handle, struct inode *inode, struct ext4_map_blocks *map, struct ext4_ext_path *path, int flags) { ext4_lblk_t eof_block; ext4_lblk_t ee_block; struct ext4_extent *ex; unsigned int ee_len; int split_flag = 0, depth; ext_debug("ext4_split_unwritten_extents: inode %lu, logical" "block %llu, max_blocks %u\n", inode->i_ino, (unsigned long long)map->m_lblk, map->m_len); eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >> inode->i_sb->s_blocksize_bits; if (eof_block < map->m_lblk + map->m_len) eof_block = map->m_lblk + map->m_len; /* * It is safe to convert extent to initialized via explicit * zeroout only if extent is fully insde i_size or new_size. */ depth = ext_depth(inode); ex = path[depth].p_ext; ee_block = le32_to_cpu(ex->ee_block); ee_len = ext4_ext_get_actual_len(ex); split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0; split_flag |= EXT4_EXT_MARK_UNINIT2; flags |= EXT4_GET_BLOCKS_PRE_IO; return ext4_split_extent(handle, inode, path, map, split_flag, flags); }
1
CVE-2012-4508
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
7,022
ImageMagick
e9438e2a82d35b6657e908ff38ec0303f432b655
MagickExport MagickBooleanType DeleteImageProfile(Image *image,const char *name) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return(MagickFalse); return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->profiles,name)); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,044
Android
42a25c46b844518ff0d0b920c20c519e1417be69
void MediaPlayer::clear_l() { mCurrentPosition = -1; mSeekPosition = -1; mVideoWidth = mVideoHeight = 0; mRetransmitEndpointValid = false; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
13,770
spice
8ba174816d245757e743e636df357910e1d5eb61
struct vdagent_file_xfers *vdagent_file_xfers_create( struct udscs_connection *vdagentd, const char *save_dir, int open_save_dir, int debug) { struct vdagent_file_xfers *xfers; xfers = g_malloc(sizeof(*xfers)); xfers->xfers = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, vdagent_file_xfer_task_free); xfers->vdagentd = vdagentd; xfers->save_dir = g_strdup(save_dir); xfers->open_save_dir = open_save_dir; xfers->debug = debug; return xfers; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
22,510
poco
bb7e5feece68ccfd8660caee93da25c5c39a4707
ZipIOS::~ZipIOS() { }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
11,687
php-src
426aeb2808955ee3d3f52e0cfb102834cdb836a5
*/ static void php_wddx_process_data(void *user_data, const XML_Char *s, int len) { st_entry *ent; wddx_stack *stack = (wddx_stack *)user_data; TSRMLS_FETCH(); if (!wddx_stack_is_empty(stack) && !stack->done) { wddx_stack_top(stack, (void**)&ent); switch (ent->type) { case ST_STRING: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len); Z_STRLEN_P(ent->data) = len; } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; } break; case ST_BINARY: if (Z_STRLEN_P(ent->data) == 0) { STR_FREE(Z_STRVAL_P(ent->data)); Z_STRVAL_P(ent->data) = estrndup(s, len + 1); } else { Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1); memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len); } Z_STRLEN_P(ent->data) += len; Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0'; break; case ST_NUMBER: Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); convert_scalar_to_number(ent->data TSRMLS_CC); break; case ST_BOOLEAN: if(!ent->data) { break; } if (!strcmp(s, "true")) { Z_LVAL_P(ent->data) = 1; } else if (!strcmp(s, "false")) { Z_LVAL_P(ent->data) = 0; } else { zval_ptr_dtor(&ent->data); if (ent->varname) { efree(ent->varname); ent->varname = NULL; } ent->data = NULL; } break; case ST_DATETIME: { char *tmp; tmp = emalloc(len + 1); memcpy(tmp, s, len); tmp[len] = '\0'; Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL); /* date out of range < 1969 or > 2038 */ if (Z_LVAL_P(ent->data) == -1) { Z_TYPE_P(ent->data) = IS_STRING; Z_STRLEN_P(ent->data) = len; Z_STRVAL_P(ent->data) = estrndup(s, len); } efree(tmp); } break; default: break; } }
1
CVE-2016-7129
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
Phase: Architecture and Design Strategy: Attack Surface Reduction Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111] Phase: Architecture and Design Strategy: Libraries or Frameworks Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173). Phases: Architecture and Design; Implementation Strategy: Attack Surface Reduction Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls. Phase: Implementation Strategy: Input Validation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. Effectiveness: High Phase: Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings. Phase: Implementation When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined. Phase: Implementation Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow. Phase: Implementation Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained. Phase: Implementation Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control. Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content. Phase: Implementation When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so.
8,871
samba
530d50a1abdcdf4d1775652d4c456c1274d83d8d
static bool ldap_push_filter(struct asn1_data *data, struct ldb_parse_tree *tree) { int i; switch (tree->operation) { case LDB_OP_AND: case LDB_OP_OR: asn1_push_tag(data, ASN1_CONTEXT(tree->operation==LDB_OP_AND?0:1)); for (i=0; i<tree->u.list.num_elements; i++) { if (!ldap_push_filter(data, tree->u.list.elements[i])) { return false; } } asn1_pop_tag(data); break; case LDB_OP_NOT: asn1_push_tag(data, ASN1_CONTEXT(2)); if (!ldap_push_filter(data, tree->u.isnot.child)) { return false; } asn1_pop_tag(data); break; case LDB_OP_EQUALITY: /* equality test */ asn1_push_tag(data, ASN1_CONTEXT(3)); asn1_write_OctetString(data, tree->u.equality.attr, strlen(tree->u.equality.attr)); asn1_write_OctetString(data, tree->u.equality.value.data, tree->u.equality.value.length); asn1_pop_tag(data); break; case LDB_OP_SUBSTRING: /* SubstringFilter ::= SEQUENCE { type AttributeDescription, -- at least one must be present substrings SEQUENCE OF CHOICE { initial [0] LDAPString, any [1] LDAPString, final [2] LDAPString } } */ asn1_push_tag(data, ASN1_CONTEXT(4)); asn1_write_OctetString(data, tree->u.substring.attr, strlen(tree->u.substring.attr)); asn1_push_tag(data, ASN1_SEQUENCE(0)); if (tree->u.substring.chunks && tree->u.substring.chunks[0]) { i = 0; if (!tree->u.substring.start_with_wildcard) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0)); asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]); asn1_pop_tag(data); i++; } while (tree->u.substring.chunks[i]) { int ctx; if (( ! tree->u.substring.chunks[i + 1]) && (tree->u.substring.end_with_wildcard == 0)) { ctx = 2; } else { ctx = 1; } asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(ctx)); asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]); asn1_pop_tag(data); i++; } } asn1_pop_tag(data); asn1_pop_tag(data); break; case LDB_OP_GREATER: /* greaterOrEqual test */ asn1_push_tag(data, ASN1_CONTEXT(5)); asn1_write_OctetString(data, tree->u.comparison.attr, strlen(tree->u.comparison.attr)); asn1_write_OctetString(data, tree->u.comparison.value.data, tree->u.comparison.value.length); asn1_pop_tag(data); break; case LDB_OP_LESS: /* lessOrEqual test */ asn1_push_tag(data, ASN1_CONTEXT(6)); asn1_write_OctetString(data, tree->u.comparison.attr, strlen(tree->u.comparison.attr)); asn1_write_OctetString(data, tree->u.comparison.value.data, tree->u.comparison.value.length); asn1_pop_tag(data); break; case LDB_OP_PRESENT: /* present test */ asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(7)); asn1_write_LDAPString(data, tree->u.present.attr); asn1_pop_tag(data); return !data->has_error; case LDB_OP_APPROX: /* approx test */ asn1_push_tag(data, ASN1_CONTEXT(8)); asn1_write_OctetString(data, tree->u.comparison.attr, strlen(tree->u.comparison.attr)); asn1_write_OctetString(data, tree->u.comparison.value.data, tree->u.comparison.value.length); asn1_pop_tag(data); break; case LDB_OP_EXTENDED: /* MatchingRuleAssertion ::= SEQUENCE { matchingRule [1] MatchingRuleID OPTIONAL, type [2] AttributeDescription OPTIONAL, matchValue [3] AssertionValue, dnAttributes [4] BOOLEAN DEFAULT FALSE } */ asn1_push_tag(data, ASN1_CONTEXT(9)); if (tree->u.extended.rule_id) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1)); asn1_write_LDAPString(data, tree->u.extended.rule_id); asn1_pop_tag(data); } if (tree->u.extended.attr) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2)); asn1_write_LDAPString(data, tree->u.extended.attr); asn1_pop_tag(data); } asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3)); asn1_write_DATA_BLOB_LDAPString(data, &tree->u.extended.value); asn1_pop_tag(data); asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4)); asn1_write_uint8(data, tree->u.extended.dnAttributes); asn1_pop_tag(data); asn1_pop_tag(data); break; default: return false; } return !data->has_error; }
1
CVE-2015-7540
CWE-399
Resource Management Errors
Weaknesses in this category are related to improper management of system resources.
Not Found in CWE Page
6,065
tcpdump
6fca58f5f9c96749a575f52e20598ad43f5bdf30
pimv1_print(netdissect_options *ndo, register const u_char *bp, register u_int len) { register const u_char *ep; register u_char type; ep = (const u_char *)ndo->ndo_snapend; if (bp >= ep) return; ND_TCHECK(bp[1]); type = bp[1]; ND_PRINT((ndo, " %s", tok2str(pimv1_type_str, "[type %u]", type))); switch (type) { case PIMV1_TYPE_QUERY: if (ND_TTEST(bp[8])) { switch (bp[8] >> 4) { case 0: ND_PRINT((ndo, " Dense-mode")); break; case 1: ND_PRINT((ndo, " Sparse-mode")); break; case 2: ND_PRINT((ndo, " Sparse-Dense-mode")); break; default: ND_PRINT((ndo, " mode-%d", bp[8] >> 4)); break; } } if (ndo->ndo_vflag) { ND_TCHECK2(bp[10],2); ND_PRINT((ndo, " (Hold-time ")); unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[10])); ND_PRINT((ndo, ")")); } break; case PIMV1_TYPE_REGISTER: ND_TCHECK2(bp[8], 20); /* ip header */ ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[20]), ipaddr_string(ndo, &bp[24]))); break; case PIMV1_TYPE_REGISTER_STOP: ND_TCHECK2(bp[12], sizeof(struct in_addr)); ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[8]), ipaddr_string(ndo, &bp[12]))); break; case PIMV1_TYPE_RP_REACHABILITY: if (ndo->ndo_vflag) { ND_TCHECK2(bp[22], 2); ND_PRINT((ndo, " group %s", ipaddr_string(ndo, &bp[8]))); if (EXTRACT_32BITS(&bp[12]) != 0xffffffff) ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12]))); ND_PRINT((ndo, " RP %s hold ", ipaddr_string(ndo, &bp[16]))); unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[22])); } break; case PIMV1_TYPE_ASSERT: ND_TCHECK2(bp[16], sizeof(struct in_addr)); ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[16]), ipaddr_string(ndo, &bp[8]))); if (EXTRACT_32BITS(&bp[12]) != 0xffffffff) ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12]))); ND_TCHECK2(bp[24], 4); ND_PRINT((ndo, " %s pref %d metric %d", (bp[20] & 0x80) ? "RP-tree" : "SPT", EXTRACT_32BITS(&bp[20]) & 0x7fffffff, EXTRACT_32BITS(&bp[24]))); break; case PIMV1_TYPE_JOIN_PRUNE: case PIMV1_TYPE_GRAFT: case PIMV1_TYPE_GRAFT_ACK: if (ndo->ndo_vflag) pimv1_join_prune_print(ndo, &bp[8], len - 8); break; } ND_TCHECK(bp[4]); if ((bp[4] >> 4) != 1) ND_PRINT((ndo, " [v%d]", bp[4] >> 4)); return; trunc: ND_PRINT((ndo, "[|pim]")); return; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
21,967
radare2
7ab66cca5bbdf6cb2d69339ef4f513d95e532dbf
char* r_pkcs7_signerinfos_dump (RX509CertificateRevocationList *crl, char* buffer, ut32 length, const char* pad) { RASN1String *algo = NULL, *last = NULL, *next = NULL; ut32 i, p; int r; char *tmp, *pad2, *pad3; if (!crl || !buffer || !length) { return NULL; } if (!pad) { pad = ""; } pad3 = r_str_newf ("%s ", pad); if (!pad3) return NULL; pad2 = pad3 + 2; algo = crl->signature.algorithm; last = crl->lastUpdate; next = crl->nextUpdate; r = snprintf (buffer, length, "%sCRL:\n%sSignature:\n%s%s\n%sIssuer\n", pad, pad2, pad3, algo ? algo->string : "", pad2); p = (ut32) r; if (r < 0 || !(tmp = r_x509_name_dump (&crl->issuer, buffer + p, length - p, pad3))) { free (pad3); return NULL; } p = tmp - buffer; if (length <= p) { free (pad3); return NULL; } r = snprintf (buffer + p, length - p, "%sLast Update: %s\n%sNext Update: %s\n%sRevoked Certificates:\n", pad2, last ? last->string : "Missing", pad2, next ? next->string : "Missing", pad2); p += (ut32) r; if (r < 0) { free (pad3); return NULL; } for (i = 0; i < crl->length; ++i) { if (length <= p || !(tmp = r_x509_crlentry_dump (crl->revokedCertificates[i], buffer + p, length - p, pad3))) { free (pad3); return NULL; } p = tmp - buffer; } free (pad3); return buffer + p; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
18,292
FFmpeg
6bbef938839adc55e8e048bc9cc2e0fafe2064df
void ff_mpeg4_init_partitions(MpegEncContext *s) { uint8_t *start = put_bits_ptr(&s->pb); uint8_t *end = s->pb.buf_end; int size = end - start; int pb_size = (((intptr_t)start + size / 3) & (~3)) - (intptr_t)start; int tex_size = (size - 2 * pb_size) & (~3); set_put_bits_buffer_size(&s->pb, pb_size); init_put_bits(&s->tex_pb, start + pb_size, tex_size); init_put_bits(&s->pb2, start + pb_size + tex_size, pb_size); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
15,974
libarchive
5562545b5562f6d12a4ef991fae158bf4ccf92b6
read_header(struct archive_read *a, struct archive_entry *entry, char head_type) { const void *h; const char *p, *endp; struct rar *rar; struct rar_header rar_header; struct rar_file_header file_header; int64_t header_size; unsigned filename_size, end; char *filename; char *strp; char packed_size[8]; char unp_size[8]; int ttime; struct archive_string_conv *sconv, *fn_sconv; unsigned long crc32_val; int ret = (ARCHIVE_OK), ret2; rar = (struct rar *)(a->format->data); /* Setup a string conversion object for non-rar-unicode filenames. */ sconv = rar->opt_sconv; if (sconv == NULL) { if (!rar->init_default_conversion) { rar->sconv_default = archive_string_default_conversion_for_read( &(a->archive)); rar->init_default_conversion = 1; } sconv = rar->sconv_default; } if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; memcpy(&rar_header, p, sizeof(rar_header)); rar->file_flags = archive_le16dec(rar_header.flags); header_size = archive_le16dec(rar_header.size); if (header_size < (int64_t)sizeof(file_header) + 7) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2); __archive_read_consume(a, 7); if (!(rar->file_flags & FHD_SOLID)) { rar->compression_method = 0; rar->packed_size = 0; rar->unp_size = 0; rar->mtime = 0; rar->ctime = 0; rar->atime = 0; rar->arctime = 0; rar->mode = 0; memset(&rar->salt, 0, sizeof(rar->salt)); rar->atime = 0; rar->ansec = 0; rar->ctime = 0; rar->cnsec = 0; rar->mtime = 0; rar->mnsec = 0; rar->arctime = 0; rar->arcnsec = 0; } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR solid archive support unavailable."); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); /* File Header CRC check. */ crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7)); if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } /* If no CRC error, Go on parsing File Header. */ p = h; endp = p + header_size - 7; memcpy(&file_header, p, sizeof(file_header)); p += sizeof(file_header); rar->compression_method = file_header.method; ttime = archive_le32dec(file_header.file_time); rar->mtime = get_time(ttime); rar->file_crc = archive_le32dec(file_header.file_crc); if (rar->file_flags & FHD_PASSWORD) { archive_entry_set_is_data_encrypted(entry, 1); rar->has_encrypted_entries = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR encryption support unavailable."); /* Since it is only the data part itself that is encrypted we can at least extract information about the currently processed entry and don't need to return ARCHIVE_FATAL here. */ /*return (ARCHIVE_FATAL);*/ } if (rar->file_flags & FHD_LARGE) { memcpy(packed_size, file_header.pack_size, 4); memcpy(packed_size + 4, p, 4); /* High pack size */ p += 4; memcpy(unp_size, file_header.unp_size, 4); memcpy(unp_size + 4, p, 4); /* High unpack size */ p += 4; rar->packed_size = archive_le64dec(&packed_size); rar->unp_size = archive_le64dec(&unp_size); } else { rar->packed_size = archive_le32dec(file_header.pack_size); rar->unp_size = archive_le32dec(file_header.unp_size); } if (rar->packed_size < 0 || rar->unp_size < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid sizes specified."); return (ARCHIVE_FATAL); } rar->bytes_remaining = rar->packed_size; /* TODO: RARv3 subblocks contain comments. For now the complete block is * consumed at the end. */ if (head_type == NEWSUB_HEAD) { size_t distance = p - (const char *)h; header_size += rar->packed_size; /* Make sure we have the extended data. */ if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; endp = p + header_size - 7; p += distance; } filename_size = archive_le16dec(file_header.name_size); if (p + filename_size > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename size"); return (ARCHIVE_FATAL); } if (rar->filename_allocated < filename_size * 2 + 2) { char *newptr; size_t newsize = filename_size * 2 + 2; newptr = realloc(rar->filename, newsize); if (newptr == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->filename = newptr; rar->filename_allocated = newsize; } filename = rar->filename; memcpy(filename, p, filename_size); filename[filename_size] = '\0'; if (rar->file_flags & FHD_UNICODE) { if (filename_size != strlen(filename)) { unsigned char highbyte, flagbits, flagbyte; unsigned fn_end, offset; end = filename_size; fn_end = filename_size * 2; filename_size = 0; offset = (unsigned)strlen(filename) + 1; highbyte = *(p + offset++); flagbits = 0; flagbyte = 0; while (offset < end && filename_size < fn_end) { if (!flagbits) { flagbyte = *(p + offset++); flagbits = 8; } flagbits -= 2; switch((flagbyte >> flagbits) & 3) { case 0: filename[filename_size++] = '\0'; filename[filename_size++] = *(p + offset++); break; case 1: filename[filename_size++] = highbyte; filename[filename_size++] = *(p + offset++); break; case 2: filename[filename_size++] = *(p + offset + 1); filename[filename_size++] = *(p + offset); offset += 2; break; case 3: { char extra, high; uint8_t length = *(p + offset++); if (length & 0x80) { extra = *(p + offset++); high = (char)highbyte; } else extra = high = 0; length = (length & 0x7f) + 2; while (length && filename_size < fn_end) { unsigned cp = filename_size >> 1; filename[filename_size++] = high; filename[filename_size++] = p[cp] + extra; length--; } } break; } } if (filename_size > fn_end) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename"); return (ARCHIVE_FATAL); } filename[filename_size++] = '\0'; filename[filename_size++] = '\0'; /* Decoded unicode form is UTF-16BE, so we have to update a string * conversion object for it. */ if (rar->sconv_utf16be == NULL) { rar->sconv_utf16be = archive_string_conversion_from_charset( &a->archive, "UTF-16BE", 1); if (rar->sconv_utf16be == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf16be; strp = filename; while (memcmp(strp, "\x00\x00", 2)) { if (!memcmp(strp, "\x00\\", 2)) *(strp + 1) = '/'; strp += 2; } p += offset; } else { /* * If FHD_UNICODE is set but no unicode data, this file name form * is UTF-8, so we have to update a string conversion object for * it accordingly. */ if (rar->sconv_utf8 == NULL) { rar->sconv_utf8 = archive_string_conversion_from_charset( &a->archive, "UTF-8", 1); if (rar->sconv_utf8 == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf8; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } } else { fn_sconv = sconv; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } /* Split file in multivolume RAR. No more need to process header. */ if (rar->filename_save && filename_size == rar->filename_save_size && !memcmp(rar->filename, rar->filename_save, filename_size + 1)) { __archive_read_consume(a, header_size - 7); rar->cursor++; if (rar->cursor >= rar->nodes) { rar->nodes++; if ((rar->dbo = realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[rar->cursor].header_size = header_size; rar->dbo[rar->cursor].start_offset = -1; rar->dbo[rar->cursor].end_offset = -1; } if (rar->dbo[rar->cursor].start_offset < 0) { rar->dbo[rar->cursor].start_offset = a->filter->position; rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset + rar->packed_size; } return ret; } rar->filename_save = (char*)realloc(rar->filename_save, filename_size + 1); memcpy(rar->filename_save, rar->filename, filename_size + 1); rar->filename_save_size = filename_size; /* Set info for seeking */ free(rar->dbo); if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[0].header_size = header_size; rar->dbo[0].start_offset = -1; rar->dbo[0].end_offset = -1; rar->cursor = 0; rar->nodes = 1; if (rar->file_flags & FHD_SALT) { if (p + 8 > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } memcpy(rar->salt, p, 8); p += 8; } if (rar->file_flags & FHD_EXTTIME) { if (read_exttime(p, rar, endp) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } } __archive_read_consume(a, header_size - 7); rar->dbo[0].start_offset = a->filter->position; rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size; switch(file_header.host_os) { case OS_MSDOS: case OS_OS2: case OS_WIN32: rar->mode = archive_le32dec(file_header.file_attr); if (rar->mode & FILE_ATTRIBUTE_DIRECTORY) rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH; else rar->mode = AE_IFREG; rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; break; case OS_UNIX: case OS_MAC_OS: case OS_BEOS: rar->mode = archive_le32dec(file_header.file_attr); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unknown file attributes from RAR file's host OS"); return (ARCHIVE_FATAL); } rar->bytes_uncopied = rar->bytes_unconsumed = 0; rar->lzss.position = rar->offset = 0; rar->offset_seek = 0; rar->dictionary_size = 0; rar->offset_outgoing = 0; rar->br.cache_avail = 0; rar->br.avail_in = 0; rar->crc_calculated = 0; rar->entry_eof = 0; rar->valid = 1; rar->is_ppmd_block = 0; rar->start_new_table = 1; free(rar->unp_buffer); rar->unp_buffer = NULL; rar->unp_offset = 0; rar->unp_buffer_size = UNP_BUFFER_SIZE; memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); rar->ppmd_valid = rar->ppmd_eod = 0; /* Don't set any archive entries for non-file header types */ if (head_type == NEWSUB_HEAD) return ret; archive_entry_set_mtime(entry, rar->mtime, rar->mnsec); archive_entry_set_ctime(entry, rar->ctime, rar->cnsec); archive_entry_set_atime(entry, rar->atime, rar->ansec); archive_entry_set_size(entry, rar->unp_size); archive_entry_set_mode(entry, rar->mode); if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(fn_sconv)); ret = (ARCHIVE_WARN); } if (((rar->mode) & AE_IFMT) == AE_IFLNK) { /* Make sure a symbolic-link file does not have its body. */ rar->bytes_remaining = 0; archive_entry_set_size(entry, 0); /* Read a symbolic-link name. */ if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN)) return ret2; if (ret > ret2) ret = ret2; } if (rar->bytes_remaining == 0) rar->entry_eof = 1; return ret; }
1
CVE-2017-14502
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,787
gstreamer
9398b7f1a75b38844ae7050b5a7967e4cdebe24f
gst_date_time_get_month (const GstDateTime * datetime) { g_return_val_if_fail (datetime != NULL, 0); g_return_val_if_fail (gst_date_time_has_month (datetime), 0); return g_date_time_get_month (datetime->datetime); }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
12,532
gpac
2da2f68bffd51d89b1d272d22aa8cc023c1c066e
GF_Err stbl_GetSampleDepType(GF_SampleDependencyTypeBox *sdep, u32 SampleNumber, u32 *isLeading, u32 *dependsOn, u32 *dependedOn, u32 *redundant) { u8 flag; assert(dependsOn && dependedOn && redundant); *dependsOn = *dependedOn = *redundant = 0; if (SampleNumber > sdep->sampleCount) { return GF_OK; } flag = sdep->sample_info[SampleNumber-1]; *isLeading = (flag >> 6) & 3; *dependsOn = (flag >> 4) & 3; *dependedOn = (flag >> 2) & 3; *redundant = (flag) & 3; return GF_OK; }
0
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
NOT_APPLICABLE
19,471