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
|
---|---|---|---|---|---|---|---|---|---|
radare2 | 9b46d38dd3c4de6048a488b655c7319f845af185 | static int oplldt(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_WORD ) {
data[l++] = 0x0f;
data[l++] = 0x00;
if ( op->operands[0].type & OT_MEMORY ) {
data[l++] = 0x10 | op->operands[0].regs[0];
} else {
data[l++] = 0xd0 | op->operands[0].reg;
}
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,387 |
savannah | f290f48a621867084884bfff87f8093c15195e6a | do_ed_script (char const *inname, char const *outname,
bool *outname_needs_removal, FILE *ofp)
{
static char const editor_program[] = EDITOR_PROGRAM;
file_offset beginning_of_this_line;
FILE *pipefp = 0;
size_t chars_read;
if (! dry_run && ! skip_rest_of_patch) {
int exclusive = *outname_needs_removal ? 0 : O_EXCL;
assert (! inerrno);
*outname_needs_removal = true;
copy_file (inname, outname, 0, exclusive, instat.st_mode, true);
sprintf (buf, "%s %s%s", editor_program,
verbosity == VERBOSE ? "" : "- ",
outname);
fflush (stdout);
pipefp = popen(buf, binary_transput ? "wb" : "w");
if (!pipefp)
pfatal ("Can't open pipe to %s", quotearg (buf));
}
for (;;) {
char ed_command_letter;
beginning_of_this_line = file_tell (pfp);
chars_read = get_line ();
if (! chars_read) {
next_intuit_at(beginning_of_this_line,p_input_line);
break;
}
ed_command_letter = get_ed_command_letter (buf);
if (ed_command_letter) {
if (pipefp)
if (! fwrite (buf, sizeof *buf, chars_read, pipefp))
write_fatal ();
if (ed_command_letter != 'd' && ed_command_letter != 's') {
p_pass_comments_through = true;
while ((chars_read = get_line ()) != 0) {
if (pipefp)
if (! fwrite (buf, sizeof *buf, chars_read, pipefp))
write_fatal ();
if (chars_read == 2 && strEQ (buf, ".\n"))
break;
}
p_pass_comments_through = false;
}
}
else {
next_intuit_at(beginning_of_this_line,p_input_line);
break;
}
}
if (!pipefp)
return;
if (fwrite ("w\nq\n", sizeof (char), (size_t) 4, pipefp) == 0
|| fflush (pipefp) != 0)
write_fatal ();
if (pclose (pipefp) != 0)
fatal ("%s FAILED", editor_program);
if (ofp)
{
FILE *ifp = fopen (outname, binary_transput ? "rb" : "r");
int c;
if (!ifp)
pfatal ("can't open '%s'", outname);
while ((c = getc (ifp)) != EOF)
if (putc (c, ofp) == EOF)
write_fatal ();
if (ferror (ifp) || fclose (ifp) != 0)
read_fatal ();
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,445 |
libav | 635bcfccd439480003b74a665b5aa7c872c1ad6b | static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame)
{
const uint8_t* as_pack;
int freq, stype, smpls, quant, i, ach;
as_pack = dv_extract_pack(frame, dv_audio_source);
if (!as_pack || !c->sys) { /* No audio ? */
c->ach = 0;
return 0;
}
smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */
freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */
stype = (as_pack[3] & 0x1f); /* 0 - 2CH, 2 - 4CH, 3 - 8CH */
quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */
if (stype > 3) {
av_log(c->fctx, AV_LOG_ERROR, "stype %d is invalid\n", stype);
c->ach = 0;
return 0;
}
/* note: ach counts PAIRS of channels (i.e. stereo channels) */
ach = ((int[4]){ 1, 0, 2, 4})[stype];
if (ach == 1 && quant && freq == 2)
if (!c->ast[i])
break;
avpriv_set_pts_info(c->ast[i], 64, 1, 30000);
c->ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO;
c->ast[i]->codec->codec_id = CODEC_ID_PCM_S16LE;
av_init_packet(&c->audio_pkt[i]);
c->audio_pkt[i].size = 0;
c->audio_pkt[i].data = c->audio_buf[i];
c->audio_pkt[i].stream_index = c->ast[i]->index;
c->audio_pkt[i].flags |= AV_PKT_FLAG_KEY;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,757 |
FFmpeg | fe448cd28d674c3eff3072552eae366d0b659ce9 | static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
{
int i, csize = 1;
int32_t *src[3], i0, i1, i2;
float *srcf[3], i0f, i1f, i2f;
for (i = 1; i < 3; i++)
if (tile->codsty[0].transform != tile->codsty[i].transform) {
av_log(s->avctx, AV_LOG_ERROR, "Transforms mismatch, MCT not supported\n");
return;
}
for (i = 0; i < 3; i++)
if (tile->codsty[0].transform == FF_DWT97)
srcf[i] = tile->comp[i].f_data;
else
src [i] = tile->comp[i].i_data;
for (i = 0; i < 2; i++)
csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
switch (tile->codsty[0].transform) {
case FF_DWT97:
for (i = 0; i < csize; i++) {
i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]);
i1f = *srcf[0] - (f_ict_params[1] * *srcf[1])
- (f_ict_params[2] * *srcf[2]);
i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]);
*srcf[0]++ = i0f;
*srcf[1]++ = i1f;
*srcf[2]++ = i2f;
}
break;
case FF_DWT97_INT:
for (i = 0; i < csize; i++) {
i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16);
i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16)
- (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16);
i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16);
*src[0]++ = i0;
*src[1]++ = i1;
*src[2]++ = i2;
}
break;
case FF_DWT53:
for (i = 0; i < csize; i++) {
i1 = *src[0] - (*src[2] + *src[1] >> 2);
i0 = i1 + *src[2];
i2 = i1 + *src[1];
*src[0]++ = i0;
*src[1]++ = i1;
*src[2]++ = i2;
}
break;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,125 |
gnutls | 3db352734472d851318944db13be73da61300568 | _wrap_gost28147_imit_set_key_tc26z(void *ctx, size_t len, const uint8_t * key)
{
gost28147_imit_set_param(ctx, &gost28147_param_TC26_Z);
gost28147_imit_set_key(ctx, len, key);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,999 |
FFmpeg | d227ed5d598340e719eff7156b1aa0a4469e9a6a | static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,
additional_code_len, sign, mismatch;
VLC *cur_vlc = &ctx->studio_intra_tab[0];
uint8_t *const scantable = s->intra_scantable.permutated;
const uint16_t *quant_matrix;
uint32_t flc;
const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6));
const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);
mismatch = 1;
memset(block, 0, 64 * sizeof(int32_t));
if (n < 4) {
cc = 0;
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->intra_matrix;
} else {
cc = (n & 1) + 1;
if (ctx->rgb)
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
else
dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->chroma_intra_matrix;
}
if (dct_dc_size < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n");
return AVERROR_INVALIDDATA;
} else if (dct_dc_size == 0) {
dct_diff = 0;
} else {
dct_diff = get_xbits(&s->gb, dct_dc_size);
if (dct_dc_size > 8) {
if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8"))
return AVERROR_INVALIDDATA;
}
}
s->last_dc[cc] += dct_diff;
if (s->mpeg_quant)
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);
else
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);
/* TODO: support mpeg_quant for AC coefficients */
block[0] = av_clip(block[0], min, max);
mismatch ^= block[0];
/* AC Coefficients */
while (1) {
group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2);
if (group < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n");
return AVERROR_INVALIDDATA;
}
additional_code_len = ac_state_tab[group][0];
cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]];
if (group == 0) {
/* End of Block */
break;
} else if (group >= 1 && group <= 6) {
/* Zero run length (Table B.47) */
run = 1 << additional_code_len;
if (additional_code_len)
run += get_bits(&s->gb, additional_code_len);
idx += run;
continue;
} else if (group >= 7 && group <= 12) {
/* Zero run length and +/-1 level (Table B.48) */
code = get_bits(&s->gb, additional_code_len);
sign = code & 1;
code >>= 1;
run = (1 << (additional_code_len - 1)) + code;
idx += run;
j = scantable[idx++];
block[j] = sign ? 1 : -1;
} else if (group >= 13 && group <= 20) {
/* Level value (Table B.49) */
j = scantable[idx++];
block[j] = get_xbits(&s->gb, additional_code_len);
} else if (group == 21) {
/* Escape */
j = scantable[idx++];
additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;
flc = get_bits(&s->gb, additional_code_len);
if (flc >> (additional_code_len-1))
block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);
else
block[j] = flc;
}
block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32;
block[j] = av_clip(block[j], min, max);
mismatch ^= block[j];
}
block[63] ^= mismatch & 1;
return 0;
}
| 1 | CVE-2019-11339 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 4,112 |
linux | 54a20552e1eae07aa240fa370a0293e006b5faed | static void init_vmcb(struct vcpu_svm *svm)
{
struct vmcb_control_area *control = &svm->vmcb->control;
struct vmcb_save_area *save = &svm->vmcb->save;
svm->vcpu.fpu_active = 1;
svm->vcpu.arch.hflags = 0;
set_cr_intercept(svm, INTERCEPT_CR0_READ);
set_cr_intercept(svm, INTERCEPT_CR3_READ);
set_cr_intercept(svm, INTERCEPT_CR4_READ);
set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
set_dr_intercepts(svm);
set_exception_intercept(svm, PF_VECTOR);
set_exception_intercept(svm, UD_VECTOR);
set_exception_intercept(svm, MC_VECTOR);
set_intercept(svm, INTERCEPT_INTR);
set_intercept(svm, INTERCEPT_NMI);
set_intercept(svm, INTERCEPT_SMI);
set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
set_intercept(svm, INTERCEPT_RDPMC);
set_intercept(svm, INTERCEPT_CPUID);
set_intercept(svm, INTERCEPT_INVD);
set_intercept(svm, INTERCEPT_HLT);
set_intercept(svm, INTERCEPT_INVLPG);
set_intercept(svm, INTERCEPT_INVLPGA);
set_intercept(svm, INTERCEPT_IOIO_PROT);
set_intercept(svm, INTERCEPT_MSR_PROT);
set_intercept(svm, INTERCEPT_TASK_SWITCH);
set_intercept(svm, INTERCEPT_SHUTDOWN);
set_intercept(svm, INTERCEPT_VMRUN);
set_intercept(svm, INTERCEPT_VMMCALL);
set_intercept(svm, INTERCEPT_VMLOAD);
set_intercept(svm, INTERCEPT_VMSAVE);
set_intercept(svm, INTERCEPT_STGI);
set_intercept(svm, INTERCEPT_CLGI);
set_intercept(svm, INTERCEPT_SKINIT);
set_intercept(svm, INTERCEPT_WBINVD);
set_intercept(svm, INTERCEPT_MONITOR);
set_intercept(svm, INTERCEPT_MWAIT);
set_intercept(svm, INTERCEPT_XSETBV);
control->iopm_base_pa = iopm_base;
control->msrpm_base_pa = __pa(svm->msrpm);
control->int_ctl = V_INTR_MASKING_MASK;
init_seg(&save->es);
init_seg(&save->ss);
init_seg(&save->ds);
init_seg(&save->fs);
init_seg(&save->gs);
save->cs.selector = 0xf000;
save->cs.base = 0xffff0000;
/* Executable/Readable Code Segment */
save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
save->cs.limit = 0xffff;
save->gdtr.limit = 0xffff;
save->idtr.limit = 0xffff;
init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
svm_set_efer(&svm->vcpu, 0);
save->dr6 = 0xffff0ff0;
kvm_set_rflags(&svm->vcpu, 2);
save->rip = 0x0000fff0;
svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
/*
* svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
* It also updates the guest-visible cr0 value.
*/
svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
kvm_mmu_reset_context(&svm->vcpu);
save->cr4 = X86_CR4_PAE;
/* rdx = ?? */
if (npt_enabled) {
/* Setup VMCB for Nested Paging */
control->nested_ctl = 1;
clr_intercept(svm, INTERCEPT_INVLPG);
clr_exception_intercept(svm, PF_VECTOR);
clr_cr_intercept(svm, INTERCEPT_CR3_READ);
clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
save->g_pat = svm->vcpu.arch.pat;
save->cr3 = 0;
save->cr4 = 0;
}
svm->asid_generation = 0;
svm->nested.vmcb = 0;
svm->vcpu.arch.hflags = 0;
if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
control->pause_filter_count = 3000;
set_intercept(svm, INTERCEPT_PAUSE);
}
mark_all_dirty(svm->vmcb);
enable_gif(svm);
}
| 1 | CVE-2015-5307 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 6,797 |
libidn | 11abd0e02c16f9e0b6944aea4ef0f2df44b42dd4 | idna_to_ascii_4i (const uint32_t * in, size_t inlen, char *out, int flags)
{
size_t len, outlen;
uint32_t *src; /* XXX don't need to copy data? */
int rc;
/*
* ToASCII consists of the following steps:
*
* 1. If all code points in the sequence are in the ASCII range (0..7F)
* then skip to step 3.
*/
{
size_t i;
int inasciirange;
inasciirange = 1;
for (i = 0; i < inlen; i++)
if (in[i] > 0x7F)
inasciirange = 0;
if (inasciirange)
{
src = malloc (sizeof (in[0]) * (inlen + 1));
if (src == NULL)
return IDNA_MALLOC_ERROR;
memcpy (src, in, sizeof (in[0]) * inlen);
src[inlen] = 0;
goto step3;
}
}
/*
* 2. Perform the steps specified in [NAMEPREP] and fail if there is
* an error. The AllowUnassigned flag is used in [NAMEPREP].
*/
{
char *p;
p = stringprep_ucs4_to_utf8 (in, (ssize_t) inlen, NULL, NULL);
if (p == NULL)
return IDNA_MALLOC_ERROR;
len = strlen (p);
do
{
char *newp;
len = 2 * len + 10; /* XXX better guess? */
newp = realloc (p, len);
if (newp == NULL)
{
free (p);
return IDNA_MALLOC_ERROR;
}
p = newp;
if (flags & IDNA_ALLOW_UNASSIGNED)
rc = stringprep_nameprep (p, len);
else
rc = stringprep_nameprep_no_unassigned (p, len);
}
while (rc == STRINGPREP_TOO_SMALL_BUFFER);
if (rc != STRINGPREP_OK)
{
free (p);
return IDNA_STRINGPREP_ERROR;
}
src = stringprep_utf8_to_ucs4 (p, -1, NULL);
free (p);
if (!src)
return IDNA_MALLOC_ERROR;
}
step3:
/*
* 3. If the UseSTD3ASCIIRules flag is set, then perform these checks:
*
* (a) Verify the absence of non-LDH ASCII code points; that is,
* the absence of 0..2C, 2E..2F, 3A..40, 5B..60, and 7B..7F.
*
* (b) Verify the absence of leading and trailing hyphen-minus;
* that is, the absence of U+002D at the beginning and end of
* the sequence.
*/
if (flags & IDNA_USE_STD3_ASCII_RULES)
{
size_t i;
for (i = 0; src[i]; i++)
if (src[i] <= 0x2C || src[i] == 0x2E || src[i] == 0x2F ||
(src[i] >= 0x3A && src[i] <= 0x40) ||
(src[i] >= 0x5B && src[i] <= 0x60) ||
(src[i] >= 0x7B && src[i] <= 0x7F))
{
free (src);
return IDNA_CONTAINS_NON_LDH;
}
if (src[0] == 0x002D || (i > 0 && src[i - 1] == 0x002D))
{
free (src);
return IDNA_CONTAINS_MINUS;
}
}
/*
* 4. If all code points in the sequence are in the ASCII range
* (0..7F), then skip to step 8.
*/
{
size_t i;
int inasciirange;
inasciirange = 1;
for (i = 0; src[i]; i++)
{
if (src[i] > 0x7F)
inasciirange = 0;
/* copy string to output buffer if we are about to skip to step8 */
if (i < 64)
out[i] = src[i];
}
if (i < 64)
out[i] = '\0';
else
return IDNA_INVALID_LENGTH;
if (inasciirange)
goto step8;
}
/*
* 5. Verify that the sequence does NOT begin with the ACE prefix.
*
*/
{
size_t i;
int match;
match = 1;
for (i = 0; match && i < strlen (IDNA_ACE_PREFIX); i++)
if (((uint32_t) IDNA_ACE_PREFIX[i] & 0xFF) != src[i])
match = 0;
if (match)
{
free (src);
return IDNA_CONTAINS_ACE_PREFIX;
}
}
/*
* 6. Encode the sequence using the encoding algorithm in [PUNYCODE]
* and fail if there is an error.
*/
for (len = 0; src[len]; len++)
;
src[len] = '\0';
outlen = 63 - strlen (IDNA_ACE_PREFIX);
rc = punycode_encode (len, src, NULL,
&outlen, &out[strlen (IDNA_ACE_PREFIX)]);
if (rc != PUNYCODE_SUCCESS)
{
free (src);
return IDNA_PUNYCODE_ERROR;
}
out[strlen (IDNA_ACE_PREFIX) + outlen] = '\0';
/*
* 7. Prepend the ACE prefix.
*/
memcpy (out, IDNA_ACE_PREFIX, strlen (IDNA_ACE_PREFIX));
/*
* 8. Verify that the number of code points is in the range 1 to 63
* inclusive (0 is excluded).
*/
step8:
free (src);
if (strlen (out) < 1)
return IDNA_INVALID_LENGTH;
return IDNA_SUCCESS;
} | 1 | CVE-2016-6261 | 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,708 |
curl | 8c7ee9083d0d719d0a77ab20d9cc2ae84eeea7f3 | static CURLcode single_transfer(struct GlobalConfig *global,
struct OperationConfig *config,
CURLSH *share,
bool capath_from_env,
bool *added)
{
CURLcode result = CURLE_OK;
struct getout *urlnode;
bool orig_noprogress = global->noprogress;
bool orig_isatty = global->isatty;
struct State *state = &config->state;
char *httpgetfields = state->httpgetfields;
*added = FALSE; /* not yet */
if(config->postfields) {
if(config->use_httpget) {
if(!httpgetfields) {
/* Use the postfields data for a http get */
httpgetfields = state->httpgetfields = strdup(config->postfields);
Curl_safefree(config->postfields);
if(!httpgetfields) {
errorf(global, "out of memory\n");
result = CURLE_OUT_OF_MEMORY;
}
else if(SetHTTPrequest(config,
(config->no_body?HTTPREQ_HEAD:HTTPREQ_GET),
&config->httpreq)) {
result = CURLE_FAILED_INIT;
}
}
}
else {
if(SetHTTPrequest(config, HTTPREQ_SIMPLEPOST, &config->httpreq))
result = CURLE_FAILED_INIT;
}
if(result) {
single_transfer_cleanup(config);
return result;
}
}
if(!state->urlnode) {
/* first time caller, setup things */
state->urlnode = config->url_list;
state->infilenum = 1;
}
while(config->state.urlnode) {
static bool warn_more_options = FALSE;
char *infiles; /* might be a glob pattern */
struct URLGlob *inglob = state->inglob;
urlnode = config->state.urlnode;
/* urlnode->url is the full URL (it might be NULL) */
if(!urlnode->url) {
/* This node has no URL. Free node data without destroying the
node itself nor modifying next pointer and continue to next */
Curl_safefree(urlnode->outfile);
Curl_safefree(urlnode->infile);
urlnode->flags = 0;
config->state.urlnode = urlnode->next;
state->up = 0;
if(!warn_more_options) {
/* only show this once */
warnf(config->global, "Got more output options than URLs\n");
warn_more_options = TRUE;
}
continue; /* next URL please */
}
/* save outfile pattern before expansion */
if(urlnode->outfile && !state->outfiles) {
state->outfiles = strdup(urlnode->outfile);
if(!state->outfiles) {
errorf(global, "out of memory\n");
result = CURLE_OUT_OF_MEMORY;
break;
}
}
infiles = urlnode->infile;
if(!config->globoff && infiles && !inglob) {
/* Unless explicitly shut off */
result = glob_url(&inglob, infiles, &state->infilenum,
global->showerror?global->errors:NULL);
if(result)
break;
config->state.inglob = inglob;
}
{
unsigned long urlnum;
if(!state->up && !infiles)
Curl_nop_stmt;
else {
if(!state->uploadfile) {
if(inglob) {
result = glob_next_url(&state->uploadfile, inglob);
if(result == CURLE_OUT_OF_MEMORY)
errorf(global, "out of memory\n");
}
else if(!state->up) {
state->uploadfile = strdup(infiles);
if(!state->uploadfile) {
errorf(global, "out of memory\n");
result = CURLE_OUT_OF_MEMORY;
}
}
}
if(result)
break;
}
if(!state->urlnum) {
if(!config->globoff) {
/* Unless explicitly shut off, we expand '{...}' and '[...]'
expressions and return total number of URLs in pattern set */
result = glob_url(&state->urls, urlnode->url, &state->urlnum,
global->showerror?global->errors:NULL);
if(result)
break;
urlnum = state->urlnum;
}
else
urlnum = 1; /* without globbing, this is a single URL */
}
else
urlnum = state->urlnum;
if(state->up < state->infilenum) {
struct per_transfer *per = NULL;
struct OutStruct *outs;
struct InStruct *input;
struct OutStruct *heads;
struct OutStruct *etag_save;
struct HdrCbData *hdrcbdata = NULL;
struct OutStruct etag_first;
long use_proto;
CURL *curl;
/* --etag-save */
memset(&etag_first, 0, sizeof(etag_first));
etag_save = &etag_first;
etag_save->stream = stdout;
/* --etag-compare */
if(config->etag_compare_file) {
char *etag_from_file = NULL;
char *header = NULL;
ParameterError pe;
/* open file for reading: */
FILE *file = fopen(config->etag_compare_file, FOPEN_READTEXT);
if(!file && !config->etag_save_file) {
errorf(global,
"Failed to open %s\n", config->etag_compare_file);
result = CURLE_READ_ERROR;
break;
}
if((PARAM_OK == file2string(&etag_from_file, file)) &&
etag_from_file) {
header = aprintf("If-None-Match: %s", etag_from_file);
Curl_safefree(etag_from_file);
}
else
header = aprintf("If-None-Match: \"\"");
if(!header) {
if(file)
fclose(file);
errorf(global,
"Failed to allocate memory for custom etag header\n");
result = CURLE_OUT_OF_MEMORY;
break;
}
/* add Etag from file to list of custom headers */
pe = add2list(&config->headers, header);
Curl_safefree(header);
if(file)
fclose(file);
if(pe != PARAM_OK) {
result = CURLE_OUT_OF_MEMORY;
break;
}
}
if(config->etag_save_file) {
/* open file for output: */
if(strcmp(config->etag_save_file, "-")) {
FILE *newfile = fopen(config->etag_save_file, "wb");
if(!newfile) {
warnf(global, "Failed creating file for saving etags: \"%s\". "
"Skip this transfer\n", config->etag_save_file);
Curl_safefree(state->outfiles);
glob_cleanup(state->urls);
return CURLE_OK;
}
else {
etag_save->filename = config->etag_save_file;
etag_save->s_isreg = TRUE;
etag_save->fopened = TRUE;
etag_save->stream = newfile;
}
}
else {
/* always use binary mode for protocol header output */
set_binmode(etag_save->stream);
}
}
curl = curl_easy_init();
if(curl)
result = add_per_transfer(&per);
else
result = CURLE_OUT_OF_MEMORY;
if(result) {
curl_easy_cleanup(curl);
if(etag_save->fopened)
fclose(etag_save->stream);
break;
}
per->etag_save = etag_first; /* copy the whole struct */
if(state->uploadfile) {
per->uploadfile = strdup(state->uploadfile);
if(!per->uploadfile) {
curl_easy_cleanup(curl);
result = CURLE_OUT_OF_MEMORY;
break;
}
if(SetHTTPrequest(config, HTTPREQ_PUT, &config->httpreq)) {
Curl_safefree(per->uploadfile);
curl_easy_cleanup(curl);
result = CURLE_FAILED_INIT;
break;
}
}
*added = TRUE;
per->config = config;
per->curl = curl;
per->urlnum = urlnode->num;
/* default headers output stream is stdout */
heads = &per->heads;
heads->stream = stdout;
/* Single header file for all URLs */
if(config->headerfile) {
/* open file for output: */
if(strcmp(config->headerfile, "-")) {
FILE *newfile;
newfile = fopen(config->headerfile, per->prev == NULL?"wb":"ab");
if(!newfile) {
warnf(global, "Failed to open %s\n", config->headerfile);
result = CURLE_WRITE_ERROR;
break;
}
else {
heads->filename = config->headerfile;
heads->s_isreg = TRUE;
heads->fopened = TRUE;
heads->stream = newfile;
}
}
else {
/* always use binary mode for protocol header output */
set_binmode(heads->stream);
}
}
hdrcbdata = &per->hdrcbdata;
outs = &per->outs;
input = &per->input;
per->outfile = NULL;
per->infdopen = FALSE;
per->infd = STDIN_FILENO;
/* default output stream is stdout */
outs->stream = stdout;
if(state->urls) {
result = glob_next_url(&per->this_url, state->urls);
if(result)
break;
}
else if(!state->li) {
per->this_url = strdup(urlnode->url);
if(!per->this_url) {
result = CURLE_OUT_OF_MEMORY;
break;
}
}
else
per->this_url = NULL;
if(!per->this_url)
break;
if(state->outfiles) {
per->outfile = strdup(state->outfiles);
if(!per->outfile) {
result = CURLE_OUT_OF_MEMORY;
break;
}
}
if(((urlnode->flags&GETOUT_USEREMOTE) ||
(per->outfile && strcmp("-", per->outfile)))) {
/*
* We have specified a file name to store the result in, or we have
* decided we want to use the remote file name.
*/
if(!per->outfile) {
/* extract the file name from the URL */
result = get_url_file_name(&per->outfile, per->this_url);
if(result) {
errorf(global, "Failed to extract a sensible file name"
" from the URL to use for storage!\n");
break;
}
if(!*per->outfile && !config->content_disposition) {
errorf(global, "Remote file name has no length!\n");
result = CURLE_WRITE_ERROR;
break;
}
}
else if(state->urls) {
/* fill '#1' ... '#9' terms from URL pattern */
char *storefile = per->outfile;
result = glob_match_url(&per->outfile, storefile, state->urls);
Curl_safefree(storefile);
if(result) {
/* bad globbing */
warnf(global, "bad output glob!\n");
break;
}
if(!*per->outfile) {
warnf(global, "output glob produces empty string!\n");
result = CURLE_WRITE_ERROR;
break;
}
}
if(config->output_dir && *config->output_dir) {
char *d = aprintf("%s/%s", config->output_dir, per->outfile);
if(!d) {
result = CURLE_WRITE_ERROR;
break;
}
free(per->outfile);
per->outfile = d;
}
/* Create the directory hierarchy, if not pre-existent to a multiple
file output call */
if(config->create_dirs) {
result = create_dir_hierarchy(per->outfile, global->errors);
/* create_dir_hierarchy shows error upon CURLE_WRITE_ERROR */
if(result)
break;
}
if((urlnode->flags & GETOUT_USEREMOTE)
&& config->content_disposition) {
/* Our header callback MIGHT set the filename */
DEBUGASSERT(!outs->filename);
}
if(config->resume_from_current) {
/* We're told to continue from where we are now. Get the size
of the file as it is now and open it for append instead */
struct_stat fileinfo;
/* VMS -- Danger, the filesize is only valid for stream files */
if(0 == stat(per->outfile, &fileinfo))
/* set offset to current file size: */
config->resume_from = fileinfo.st_size;
else
/* let offset be 0 */
config->resume_from = 0;
}
if(config->resume_from) {
#ifdef __VMS
/* open file for output, forcing VMS output format into stream
mode which is needed for stat() call above to always work. */
FILE *file = fopen(outfile, "ab",
"ctx=stm", "rfm=stmlf", "rat=cr", "mrs=0");
#else
/* open file for output: */
FILE *file = fopen(per->outfile, "ab");
#endif
if(!file) {
errorf(global, "Can't open '%s'!\n", per->outfile);
result = CURLE_WRITE_ERROR;
break;
}
outs->fopened = TRUE;
outs->stream = file;
outs->init = config->resume_from;
}
else {
outs->stream = NULL; /* open when needed */
}
outs->filename = per->outfile;
outs->s_isreg = TRUE;
}
if(per->uploadfile && !stdin_upload(per->uploadfile)) {
/*
* We have specified a file to upload and it isn't "-".
*/
char *nurl = add_file_name_to_url(per->this_url, per->uploadfile);
if(!nurl) {
result = CURLE_OUT_OF_MEMORY;
break;
}
per->this_url = nurl;
}
else if(per->uploadfile && stdin_upload(per->uploadfile)) {
/* count to see if there are more than one auth bit set
in the authtype field */
int authbits = 0;
int bitcheck = 0;
while(bitcheck < 32) {
if(config->authtype & (1UL << bitcheck++)) {
authbits++;
if(authbits > 1) {
/* more than one, we're done! */
break;
}
}
}
/*
* If the user has also selected --anyauth or --proxy-anyauth
* we should warn him/her.
*/
if(config->proxyanyauth || (authbits>1)) {
warnf(global,
"Using --anyauth or --proxy-anyauth with upload from stdin"
" involves a big risk of it not working. Use a temporary"
" file or a fixed auth type instead!\n");
}
DEBUGASSERT(per->infdopen == FALSE);
DEBUGASSERT(per->infd == STDIN_FILENO);
set_binmode(stdin);
if(!strcmp(per->uploadfile, ".")) {
if(curlx_nonblock((curl_socket_t)per->infd, TRUE) < 0)
warnf(global,
"fcntl failed on fd=%d: %s\n", per->infd, strerror(errno));
}
}
if(per->uploadfile && config->resume_from_current)
config->resume_from = -1; /* -1 will then force get-it-yourself */
if(output_expected(per->this_url, per->uploadfile) && outs->stream &&
isatty(fileno(outs->stream)))
/* we send the output to a tty, therefore we switch off the progress
meter */
per->noprogress = global->noprogress = global->isatty = TRUE;
else {
/* progress meter is per download, so restore config
values */
per->noprogress = global->noprogress = orig_noprogress;
global->isatty = orig_isatty;
}
if(httpgetfields) {
char *urlbuffer;
/* Find out whether the url contains a file name */
const char *pc = strstr(per->this_url, "://");
char sep = '?';
if(pc)
pc += 3;
else
pc = per->this_url;
pc = strrchr(pc, '/'); /* check for a slash */
if(pc) {
/* there is a slash present in the URL */
if(strchr(pc, '?'))
/* Ouch, there's already a question mark in the URL string, we
then append the data with an ampersand separator instead! */
sep = '&';
}
/*
* Then append ? followed by the get fields to the url.
*/
if(pc)
urlbuffer = aprintf("%s%c%s", per->this_url, sep, httpgetfields);
else
/* Append / before the ? to create a well-formed url
if the url contains a hostname only
*/
urlbuffer = aprintf("%s/?%s", per->this_url, httpgetfields);
if(!urlbuffer) {
result = CURLE_OUT_OF_MEMORY;
break;
}
Curl_safefree(per->this_url); /* free previous URL */
per->this_url = urlbuffer; /* use our new URL instead! */
}
if(!global->errors)
global->errors = stderr;
if((!per->outfile || !strcmp(per->outfile, "-")) &&
!config->use_ascii) {
/* We get the output to stdout and we have not got the ASCII/text
flag, then set stdout to be binary */
set_binmode(stdout);
}
/* explicitly passed to stdout means okaying binary gunk */
config->terminal_binary_ok =
(per->outfile && !strcmp(per->outfile, "-"));
/* Avoid having this setopt added to the --libcurl source output. */
result = curl_easy_setopt(curl, CURLOPT_SHARE, share);
if(result)
break;
/* here */
use_proto = url_proto(per->this_url);
#if 0
if(!(use_proto & built_in_protos)) {
warnf(global, "URL is '%s' but no support for the scheme\n",
per->this_url);
}
#endif
if(!config->tcp_nodelay)
my_setopt(curl, CURLOPT_TCP_NODELAY, 0L);
if(config->tcp_fastopen)
my_setopt(curl, CURLOPT_TCP_FASTOPEN, 1L);
/* where to store */
my_setopt(curl, CURLOPT_WRITEDATA, per);
my_setopt(curl, CURLOPT_INTERLEAVEDATA, per);
/* what call to write */
my_setopt(curl, CURLOPT_WRITEFUNCTION, tool_write_cb);
/* for uploads */
input->config = config;
/* Note that if CURLOPT_READFUNCTION is fread (the default), then
* lib/telnet.c will Curl_poll() on the input file descriptor
* rather than calling the READFUNCTION at regular intervals.
* The circumstances in which it is preferable to enable this
* behavior, by omitting to set the READFUNCTION & READDATA options,
* have not been determined.
*/
my_setopt(curl, CURLOPT_READDATA, input);
/* what call to read */
my_setopt(curl, CURLOPT_READFUNCTION, tool_read_cb);
/* in 7.18.0, the CURLOPT_SEEKFUNCTION/DATA pair is taking over what
CURLOPT_IOCTLFUNCTION/DATA pair previously provided for seeking */
my_setopt(curl, CURLOPT_SEEKDATA, input);
my_setopt(curl, CURLOPT_SEEKFUNCTION, tool_seek_cb);
if(config->recvpersecond &&
(config->recvpersecond < BUFFER_SIZE))
/* use a smaller sized buffer for better sleeps */
my_setopt(curl, CURLOPT_BUFFERSIZE, (long)config->recvpersecond);
else
my_setopt(curl, CURLOPT_BUFFERSIZE, (long)BUFFER_SIZE);
my_setopt_str(curl, CURLOPT_URL, per->this_url);
my_setopt(curl, CURLOPT_NOPROGRESS, global->noprogress?1L:0L);
if(config->no_body)
my_setopt(curl, CURLOPT_NOBODY, 1L);
if(config->oauth_bearer)
my_setopt_str(curl, CURLOPT_XOAUTH2_BEARER, config->oauth_bearer);
my_setopt_str(curl, CURLOPT_PROXY, config->proxy);
if(config->proxy && result) {
errorf(global, "proxy support is disabled in this libcurl\n");
config->synthetic_error = TRUE;
result = CURLE_NOT_BUILT_IN;
break;
}
/* new in libcurl 7.5 */
if(config->proxy)
my_setopt_enum(curl, CURLOPT_PROXYTYPE, config->proxyver);
my_setopt_str(curl, CURLOPT_PROXYUSERPWD, config->proxyuserpwd);
/* new in libcurl 7.3 */
my_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, config->proxytunnel?1L:0L);
/* new in libcurl 7.52.0 */
if(config->preproxy)
my_setopt_str(curl, CURLOPT_PRE_PROXY, config->preproxy);
/* new in libcurl 7.10.6 */
if(config->proxyanyauth)
my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
(long)CURLAUTH_ANY);
else if(config->proxynegotiate)
my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
(long)CURLAUTH_GSSNEGOTIATE);
else if(config->proxyntlm)
my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
(long)CURLAUTH_NTLM);
else if(config->proxydigest)
my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
(long)CURLAUTH_DIGEST);
else if(config->proxybasic)
my_setopt_bitmask(curl, CURLOPT_PROXYAUTH,
(long)CURLAUTH_BASIC);
/* new in libcurl 7.19.4 */
my_setopt_str(curl, CURLOPT_NOPROXY, config->noproxy);
my_setopt(curl, CURLOPT_SUPPRESS_CONNECT_HEADERS,
config->suppress_connect_headers?1L:0L);
my_setopt(curl, CURLOPT_FAILONERROR, config->failonerror?1L:0L);
my_setopt(curl, CURLOPT_REQUEST_TARGET, config->request_target);
my_setopt(curl, CURLOPT_UPLOAD, per->uploadfile?1L:0L);
my_setopt(curl, CURLOPT_DIRLISTONLY, config->dirlistonly?1L:0L);
my_setopt(curl, CURLOPT_APPEND, config->ftp_append?1L:0L);
if(config->netrc_opt)
my_setopt_enum(curl, CURLOPT_NETRC, (long)CURL_NETRC_OPTIONAL);
else if(config->netrc || config->netrc_file)
my_setopt_enum(curl, CURLOPT_NETRC, (long)CURL_NETRC_REQUIRED);
else
my_setopt_enum(curl, CURLOPT_NETRC, (long)CURL_NETRC_IGNORED);
if(config->netrc_file)
my_setopt_str(curl, CURLOPT_NETRC_FILE, config->netrc_file);
my_setopt(curl, CURLOPT_TRANSFERTEXT, config->use_ascii?1L:0L);
if(config->login_options)
my_setopt_str(curl, CURLOPT_LOGIN_OPTIONS, config->login_options);
my_setopt_str(curl, CURLOPT_USERPWD, config->userpwd);
my_setopt_str(curl, CURLOPT_RANGE, config->range);
my_setopt(curl, CURLOPT_ERRORBUFFER, per->errorbuffer);
my_setopt(curl, CURLOPT_TIMEOUT_MS, (long)(config->timeout * 1000));
switch(config->httpreq) {
case HTTPREQ_SIMPLEPOST:
my_setopt_str(curl, CURLOPT_POSTFIELDS,
config->postfields);
my_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE,
config->postfieldsize);
break;
case HTTPREQ_MIMEPOST:
/* free previous remainders */
curl_mime_free(config->mimepost);
config->mimepost = NULL;
result = tool2curlmime(curl, config->mimeroot, &config->mimepost);
if(result)
break;
my_setopt_mimepost(curl, CURLOPT_MIMEPOST, config->mimepost);
break;
default:
break;
}
if(result)
break;
/* new in libcurl 7.81.0 */
if(config->mime_options)
my_setopt(curl, CURLOPT_MIME_OPTIONS, config->mime_options);
/* new in libcurl 7.10.6 (default is Basic) */
if(config->authtype)
my_setopt_bitmask(curl, CURLOPT_HTTPAUTH, (long)config->authtype);
my_setopt_slist(curl, CURLOPT_HTTPHEADER, config->headers);
if(built_in_protos & (CURLPROTO_HTTP | CURLPROTO_RTSP)) {
my_setopt_str(curl, CURLOPT_REFERER, config->referer);
my_setopt_str(curl, CURLOPT_USERAGENT, config->useragent);
}
if(built_in_protos & CURLPROTO_HTTP) {
long postRedir = 0;
my_setopt(curl, CURLOPT_FOLLOWLOCATION,
config->followlocation?1L:0L);
my_setopt(curl, CURLOPT_UNRESTRICTED_AUTH,
config->unrestricted_auth?1L:0L);
my_setopt(curl, CURLOPT_AUTOREFERER, config->autoreferer?1L:0L);
/* new in libcurl 7.36.0 */
if(config->proxyheaders) {
my_setopt_slist(curl, CURLOPT_PROXYHEADER, config->proxyheaders);
my_setopt(curl, CURLOPT_HEADEROPT, CURLHEADER_SEPARATE);
}
/* new in libcurl 7.5 */
my_setopt(curl, CURLOPT_MAXREDIRS, config->maxredirs);
if(config->httpversion)
my_setopt_enum(curl, CURLOPT_HTTP_VERSION, config->httpversion);
else if(curlinfo->features & CURL_VERSION_HTTP2) {
my_setopt_enum(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
}
/* curl 7.19.1 (the 301 version existed in 7.18.2),
303 was added in 7.26.0 */
if(config->post301)
postRedir |= CURL_REDIR_POST_301;
if(config->post302)
postRedir |= CURL_REDIR_POST_302;
if(config->post303)
postRedir |= CURL_REDIR_POST_303;
my_setopt(curl, CURLOPT_POSTREDIR, postRedir);
/* new in libcurl 7.21.6 */
if(config->encoding)
my_setopt_str(curl, CURLOPT_ACCEPT_ENCODING, "");
/* new in libcurl 7.21.6 */
if(config->tr_encoding)
my_setopt(curl, CURLOPT_TRANSFER_ENCODING, 1L);
/* new in libcurl 7.64.0 */
my_setopt(curl, CURLOPT_HTTP09_ALLOWED,
config->http09_allowed ? 1L : 0L);
if(result) {
errorf(global, "HTTP/0.9 is not supported in this build!\n");
return result;
}
} /* (built_in_protos & CURLPROTO_HTTP) */
my_setopt_str(curl, CURLOPT_FTPPORT, config->ftpport);
my_setopt(curl, CURLOPT_LOW_SPEED_LIMIT,
config->low_speed_limit);
my_setopt(curl, CURLOPT_LOW_SPEED_TIME, config->low_speed_time);
my_setopt(curl, CURLOPT_MAX_SEND_SPEED_LARGE,
config->sendpersecond);
my_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE,
config->recvpersecond);
if(config->use_resume)
my_setopt(curl, CURLOPT_RESUME_FROM_LARGE, config->resume_from);
else
my_setopt(curl, CURLOPT_RESUME_FROM_LARGE, CURL_OFF_T_C(0));
my_setopt_str(curl, CURLOPT_KEYPASSWD, config->key_passwd);
my_setopt_str(curl, CURLOPT_PROXY_KEYPASSWD, config->proxy_key_passwd);
if(use_proto & (CURLPROTO_SCP|CURLPROTO_SFTP)) {
/* SSH and SSL private key uses same command-line option */
/* new in libcurl 7.16.1 */
my_setopt_str(curl, CURLOPT_SSH_PRIVATE_KEYFILE, config->key);
/* new in libcurl 7.16.1 */
my_setopt_str(curl, CURLOPT_SSH_PUBLIC_KEYFILE, config->pubkey);
/* new in libcurl 7.17.1: SSH host key md5 checking allows us
to fail if we are not talking to who we think we should */
my_setopt_str(curl, CURLOPT_SSH_HOST_PUBLIC_KEY_MD5,
config->hostpubmd5);
/* new in libcurl 7.80.0: SSH host key sha256 checking allows us
to fail if we are not talking to who we think we should */
my_setopt_str(curl, CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256,
config->hostpubsha256);
/* new in libcurl 7.56.0 */
if(config->ssh_compression)
my_setopt(curl, CURLOPT_SSH_COMPRESSION, 1L);
}
if(config->cacert)
my_setopt_str(curl, CURLOPT_CAINFO, config->cacert);
if(config->proxy_cacert)
my_setopt_str(curl, CURLOPT_PROXY_CAINFO, config->proxy_cacert);
if(config->capath) {
result = res_setopt_str(curl, CURLOPT_CAPATH, config->capath);
if(result == CURLE_NOT_BUILT_IN) {
warnf(global, "ignoring %s, not supported by libcurl\n",
capath_from_env?
"SSL_CERT_DIR environment variable":"--capath");
}
else if(result)
break;
}
/* For the time being if --proxy-capath is not set then we use the
--capath value for it, if any. See #1257 */
if(config->proxy_capath || config->capath) {
result = res_setopt_str(curl, CURLOPT_PROXY_CAPATH,
(config->proxy_capath ?
config->proxy_capath :
config->capath));
if(result == CURLE_NOT_BUILT_IN) {
if(config->proxy_capath) {
warnf(global,
"ignoring --proxy-capath, not supported by libcurl\n");
}
}
else if(result)
break;
}
if(config->crlfile)
my_setopt_str(curl, CURLOPT_CRLFILE, config->crlfile);
if(config->proxy_crlfile)
my_setopt_str(curl, CURLOPT_PROXY_CRLFILE, config->proxy_crlfile);
else if(config->crlfile) /* CURLOPT_PROXY_CRLFILE default is crlfile */
my_setopt_str(curl, CURLOPT_PROXY_CRLFILE, config->crlfile);
if(config->pinnedpubkey)
my_setopt_str(curl, CURLOPT_PINNEDPUBLICKEY, config->pinnedpubkey);
if(config->ssl_ec_curves)
my_setopt_str(curl, CURLOPT_SSL_EC_CURVES, config->ssl_ec_curves);
if(curlinfo->features & CURL_VERSION_SSL) {
/* Check if config->cert is a PKCS#11 URI and set the
* config->cert_type if necessary */
if(config->cert) {
if(!config->cert_type) {
if(is_pkcs11_uri(config->cert)) {
config->cert_type = strdup("ENG");
}
}
}
/* Check if config->key is a PKCS#11 URI and set the
* config->key_type if necessary */
if(config->key) {
if(!config->key_type) {
if(is_pkcs11_uri(config->key)) {
config->key_type = strdup("ENG");
}
}
}
/* Check if config->proxy_cert is a PKCS#11 URI and set the
* config->proxy_type if necessary */
if(config->proxy_cert) {
if(!config->proxy_cert_type) {
if(is_pkcs11_uri(config->proxy_cert)) {
config->proxy_cert_type = strdup("ENG");
}
}
}
/* Check if config->proxy_key is a PKCS#11 URI and set the
* config->proxy_key_type if necessary */
if(config->proxy_key) {
if(!config->proxy_key_type) {
if(is_pkcs11_uri(config->proxy_key)) {
config->proxy_key_type = strdup("ENG");
}
}
}
/* In debug build of curl tool, using
* --cert loadmem=<filename>:<password> --cert-type p12
* must do the same thing as classic:
* --cert <filename>:<password> --cert-type p12
* but is designed to test blob */
#if defined(CURLDEBUG) || defined(DEBUGBUILD)
if(config->cert && (strlen(config->cert) > 8) &&
(memcmp(config->cert, "loadmem=",8) == 0)) {
FILE *fInCert = fopen(config->cert + 8, "rb");
void *certdata = NULL;
long filesize = 0;
bool continue_reading = fInCert != NULL;
if(continue_reading)
continue_reading = fseek(fInCert, 0, SEEK_END) == 0;
if(continue_reading)
filesize = ftell(fInCert);
if(filesize < 0)
continue_reading = FALSE;
if(continue_reading)
continue_reading = fseek(fInCert, 0, SEEK_SET) == 0;
if(continue_reading)
certdata = malloc(((size_t)filesize) + 1);
if((!certdata) ||
((int)fread(certdata, (size_t)filesize, 1, fInCert) != 1))
continue_reading = FALSE;
if(fInCert)
fclose(fInCert);
if((filesize > 0) && continue_reading) {
struct curl_blob structblob;
structblob.data = certdata;
structblob.len = (size_t)filesize;
structblob.flags = CURL_BLOB_COPY;
my_setopt_str(curl, CURLOPT_SSLCERT_BLOB, &structblob);
/* if test run well, we are sure we don't reuse
* original mem pointer */
memset(certdata, 0, (size_t)filesize);
}
free(certdata);
}
else
#endif
my_setopt_str(curl, CURLOPT_SSLCERT, config->cert);
my_setopt_str(curl, CURLOPT_PROXY_SSLCERT, config->proxy_cert);
my_setopt_str(curl, CURLOPT_SSLCERTTYPE, config->cert_type);
my_setopt_str(curl, CURLOPT_PROXY_SSLCERTTYPE,
config->proxy_cert_type);
#if defined(CURLDEBUG) || defined(DEBUGBUILD)
if(config->key && (strlen(config->key) > 8) &&
(memcmp(config->key, "loadmem=",8) == 0)) {
FILE *fInCert = fopen(config->key + 8, "rb");
void *certdata = NULL;
long filesize = 0;
bool continue_reading = fInCert != NULL;
if(continue_reading)
continue_reading = fseek(fInCert, 0, SEEK_END) == 0;
if(continue_reading)
filesize = ftell(fInCert);
if(filesize < 0)
continue_reading = FALSE;
if(continue_reading)
continue_reading = fseek(fInCert, 0, SEEK_SET) == 0;
if(continue_reading)
certdata = malloc(((size_t)filesize) + 1);
if((!certdata) ||
((int)fread(certdata, (size_t)filesize, 1, fInCert) != 1))
continue_reading = FALSE;
if(fInCert)
fclose(fInCert);
if((filesize > 0) && continue_reading) {
struct curl_blob structblob;
structblob.data = certdata;
structblob.len = (size_t)filesize;
structblob.flags = CURL_BLOB_COPY;
my_setopt_str(curl, CURLOPT_SSLKEY_BLOB, &structblob);
/* if test run well, we are sure we don't reuse
* original mem pointer */
memset(certdata, 0, (size_t)filesize);
}
free(certdata);
}
else
#endif
my_setopt_str(curl, CURLOPT_SSLKEY, config->key);
my_setopt_str(curl, CURLOPT_PROXY_SSLKEY, config->proxy_key);
my_setopt_str(curl, CURLOPT_SSLKEYTYPE, config->key_type);
my_setopt_str(curl, CURLOPT_PROXY_SSLKEYTYPE,
config->proxy_key_type);
my_setopt_str(curl, CURLOPT_AWS_SIGV4,
config->aws_sigv4);
if(config->insecure_ok) {
my_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
my_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
}
else {
my_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
/* libcurl default is strict verifyhost -> 2L */
/* my_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); */
}
if(config->doh_insecure_ok) {
my_setopt(curl, CURLOPT_DOH_SSL_VERIFYPEER, 0L);
my_setopt(curl, CURLOPT_DOH_SSL_VERIFYHOST, 0L);
}
if(config->proxy_insecure_ok) {
my_setopt(curl, CURLOPT_PROXY_SSL_VERIFYPEER, 0L);
my_setopt(curl, CURLOPT_PROXY_SSL_VERIFYHOST, 0L);
}
else {
my_setopt(curl, CURLOPT_PROXY_SSL_VERIFYPEER, 1L);
}
if(config->verifystatus)
my_setopt(curl, CURLOPT_SSL_VERIFYSTATUS, 1L);
if(config->doh_verifystatus)
my_setopt(curl, CURLOPT_DOH_SSL_VERIFYSTATUS, 1L);
if(config->falsestart)
my_setopt(curl, CURLOPT_SSL_FALSESTART, 1L);
my_setopt_enum(curl, CURLOPT_SSLVERSION,
config->ssl_version | config->ssl_version_max);
if(config->proxy)
my_setopt_enum(curl, CURLOPT_PROXY_SSLVERSION,
config->proxy_ssl_version);
{
long mask =
(config->ssl_allow_beast ?
CURLSSLOPT_ALLOW_BEAST : 0) |
(config->ssl_no_revoke ?
CURLSSLOPT_NO_REVOKE : 0) |
(config->ssl_revoke_best_effort ?
CURLSSLOPT_REVOKE_BEST_EFFORT : 0) |
(config->native_ca_store ?
CURLSSLOPT_NATIVE_CA : 0) |
(config->ssl_auto_client_cert ?
CURLSSLOPT_AUTO_CLIENT_CERT : 0);
if(mask)
my_setopt_bitmask(curl, CURLOPT_SSL_OPTIONS, mask);
}
{
long mask =
(config->proxy_ssl_allow_beast ?
CURLSSLOPT_ALLOW_BEAST : 0) |
(config->proxy_ssl_auto_client_cert ?
CURLSSLOPT_AUTO_CLIENT_CERT : 0);
if(mask)
my_setopt_bitmask(curl, CURLOPT_PROXY_SSL_OPTIONS, mask);
}
}
if(config->path_as_is)
my_setopt(curl, CURLOPT_PATH_AS_IS, 1L);
if((use_proto & (CURLPROTO_SCP|CURLPROTO_SFTP)) &&
!config->insecure_ok) {
char *known = findfile(".ssh/known_hosts", FALSE);
if(known) {
/* new in curl 7.19.6 */
result = res_setopt_str(curl, CURLOPT_SSH_KNOWNHOSTS, known);
curl_free(known);
if(result == CURLE_UNKNOWN_OPTION)
/* libssh2 version older than 1.1.1 */
result = CURLE_OK;
if(result)
break;
}
else
warnf(global, "Couldn't find a known_hosts file!");
}
if(config->no_body || config->remote_time) {
/* no body or use remote time */
my_setopt(curl, CURLOPT_FILETIME, 1L);
}
my_setopt(curl, CURLOPT_CRLF, config->crlf?1L:0L);
my_setopt_slist(curl, CURLOPT_QUOTE, config->quote);
my_setopt_slist(curl, CURLOPT_POSTQUOTE, config->postquote);
my_setopt_slist(curl, CURLOPT_PREQUOTE, config->prequote);
if(config->cookies) {
struct curlx_dynbuf cookies;
struct curl_slist *cl;
/* The maximum size needs to match MAX_NAME in cookie.h */
curlx_dyn_init(&cookies, 4096);
for(cl = config->cookies; cl; cl = cl->next) {
if(cl == config->cookies)
result = curlx_dyn_addf(&cookies, "%s", cl->data);
else
result = curlx_dyn_addf(&cookies, ";%s", cl->data);
if(result)
break;
}
my_setopt_str(curl, CURLOPT_COOKIE, curlx_dyn_ptr(&cookies));
curlx_dyn_free(&cookies);
}
if(config->cookiefiles) {
struct curl_slist *cfl;
for(cfl = config->cookiefiles; cfl; cfl = cfl->next)
my_setopt_str(curl, CURLOPT_COOKIEFILE, cfl->data);
}
/* new in libcurl 7.9 */
if(config->cookiejar)
my_setopt_str(curl, CURLOPT_COOKIEJAR, config->cookiejar);
/* new in libcurl 7.9.7 */
my_setopt(curl, CURLOPT_COOKIESESSION, config->cookiesession?1L:0L);
my_setopt_enum(curl, CURLOPT_TIMECONDITION, (long)config->timecond);
my_setopt(curl, CURLOPT_TIMEVALUE_LARGE, config->condtime);
my_setopt_str(curl, CURLOPT_CUSTOMREQUEST, config->customrequest);
customrequest_helper(config, config->httpreq, config->customrequest);
my_setopt(curl, CURLOPT_STDERR, global->errors);
/* three new ones in libcurl 7.3: */
my_setopt_str(curl, CURLOPT_INTERFACE, config->iface);
my_setopt_str(curl, CURLOPT_KRBLEVEL, config->krblevel);
progressbarinit(&per->progressbar, config);
if((global->progressmode == CURL_PROGRESS_BAR) &&
!global->noprogress && !global->mute) {
/* we want the alternative style, then we have to implement it
ourselves! */
my_setopt(curl, CURLOPT_XFERINFOFUNCTION, tool_progress_cb);
my_setopt(curl, CURLOPT_XFERINFODATA, per);
}
else if(per->uploadfile && !strcmp(per->uploadfile, ".")) {
/* when reading from stdin in non-blocking mode, we use the progress
function to unpause a busy read */
my_setopt(curl, CURLOPT_NOPROGRESS, 0L);
my_setopt(curl, CURLOPT_XFERINFOFUNCTION, tool_readbusy_cb);
my_setopt(curl, CURLOPT_XFERINFODATA, per);
}
/* new in libcurl 7.24.0: */
if(config->dns_servers)
my_setopt_str(curl, CURLOPT_DNS_SERVERS, config->dns_servers);
/* new in libcurl 7.33.0: */
if(config->dns_interface)
my_setopt_str(curl, CURLOPT_DNS_INTERFACE, config->dns_interface);
if(config->dns_ipv4_addr)
my_setopt_str(curl, CURLOPT_DNS_LOCAL_IP4, config->dns_ipv4_addr);
if(config->dns_ipv6_addr)
my_setopt_str(curl, CURLOPT_DNS_LOCAL_IP6, config->dns_ipv6_addr);
/* new in libcurl 7.6.2: */
my_setopt_slist(curl, CURLOPT_TELNETOPTIONS, config->telnet_options);
/* new in libcurl 7.7: */
my_setopt_str(curl, CURLOPT_RANDOM_FILE, config->random_file);
my_setopt_str(curl, CURLOPT_EGDSOCKET, config->egd_file);
my_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS,
(long)(config->connecttimeout * 1000));
if(config->doh_url)
my_setopt_str(curl, CURLOPT_DOH_URL, config->doh_url);
if(config->cipher_list)
my_setopt_str(curl, CURLOPT_SSL_CIPHER_LIST, config->cipher_list);
if(config->proxy_cipher_list)
my_setopt_str(curl, CURLOPT_PROXY_SSL_CIPHER_LIST,
config->proxy_cipher_list);
if(config->cipher13_list)
my_setopt_str(curl, CURLOPT_TLS13_CIPHERS, config->cipher13_list);
if(config->proxy_cipher13_list)
my_setopt_str(curl, CURLOPT_PROXY_TLS13_CIPHERS,
config->proxy_cipher13_list);
/* new in libcurl 7.9.2: */
if(config->disable_epsv)
/* disable it */
my_setopt(curl, CURLOPT_FTP_USE_EPSV, 0L);
/* new in libcurl 7.10.5 */
if(config->disable_eprt)
/* disable it */
my_setopt(curl, CURLOPT_FTP_USE_EPRT, 0L);
if(global->tracetype != TRACE_NONE) {
my_setopt(curl, CURLOPT_DEBUGFUNCTION, tool_debug_cb);
my_setopt(curl, CURLOPT_DEBUGDATA, config);
my_setopt(curl, CURLOPT_VERBOSE, 1L);
}
/* new in curl 7.9.3 */
if(config->engine) {
result = res_setopt_str(curl, CURLOPT_SSLENGINE, config->engine);
if(result)
break;
}
/* new in curl 7.10.7, extended in 7.19.4. Modified to use
CREATE_DIR_RETRY in 7.49.0 */
my_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS,
(long)(config->ftp_create_dirs?
CURLFTP_CREATE_DIR_RETRY:
CURLFTP_CREATE_DIR_NONE));
/* new in curl 7.10.8 */
if(config->max_filesize)
my_setopt(curl, CURLOPT_MAXFILESIZE_LARGE,
config->max_filesize);
my_setopt(curl, CURLOPT_IPRESOLVE, config->ip_version);
/* new in curl 7.15.5 */
if(config->ftp_ssl_reqd)
my_setopt_enum(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
/* new in curl 7.11.0 */
else if(config->ftp_ssl)
my_setopt_enum(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_TRY);
/* new in curl 7.16.0 */
else if(config->ftp_ssl_control)
my_setopt_enum(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_CONTROL);
/* new in curl 7.16.1 */
if(config->ftp_ssl_ccc)
my_setopt_enum(curl, CURLOPT_FTP_SSL_CCC,
(long)config->ftp_ssl_ccc_mode);
/* new in curl 7.19.4 */
if(config->socks5_gssapi_nec)
my_setopt_str(curl, CURLOPT_SOCKS5_GSSAPI_NEC,
config->socks5_gssapi_nec);
/* new in curl 7.55.0 */
if(config->socks5_auth)
my_setopt_bitmask(curl, CURLOPT_SOCKS5_AUTH,
(long)config->socks5_auth);
/* new in curl 7.43.0 */
if(config->proxy_service_name)
my_setopt_str(curl, CURLOPT_PROXY_SERVICE_NAME,
config->proxy_service_name);
/* new in curl 7.43.0 */
if(config->service_name)
my_setopt_str(curl, CURLOPT_SERVICE_NAME,
config->service_name);
/* curl 7.13.0 */
my_setopt_str(curl, CURLOPT_FTP_ACCOUNT, config->ftp_account);
my_setopt(curl, CURLOPT_IGNORE_CONTENT_LENGTH, config->ignorecl?1L:0L);
/* curl 7.14.2 */
my_setopt(curl, CURLOPT_FTP_SKIP_PASV_IP, config->ftp_skip_ip?1L:0L);
/* curl 7.15.1 */
my_setopt(curl, CURLOPT_FTP_FILEMETHOD, (long)config->ftp_filemethod);
/* curl 7.15.2 */
if(config->localport) {
my_setopt(curl, CURLOPT_LOCALPORT, config->localport);
my_setopt_str(curl, CURLOPT_LOCALPORTRANGE, config->localportrange);
}
/* curl 7.15.5 */
my_setopt_str(curl, CURLOPT_FTP_ALTERNATIVE_TO_USER,
config->ftp_alternative_to_user);
/* curl 7.16.0 */
if(config->disable_sessionid)
/* disable it */
my_setopt(curl, CURLOPT_SSL_SESSIONID_CACHE, 0L);
/* curl 7.16.2 */
if(config->raw) {
my_setopt(curl, CURLOPT_HTTP_CONTENT_DECODING, 0L);
my_setopt(curl, CURLOPT_HTTP_TRANSFER_DECODING, 0L);
}
/* curl 7.17.1 */
if(!config->nokeepalive) {
my_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
if(config->alivetime) {
my_setopt(curl, CURLOPT_TCP_KEEPIDLE, config->alivetime);
my_setopt(curl, CURLOPT_TCP_KEEPINTVL, config->alivetime);
}
}
else
my_setopt(curl, CURLOPT_TCP_KEEPALIVE, 0L);
/* curl 7.20.0 */
if(config->tftp_blksize)
my_setopt(curl, CURLOPT_TFTP_BLKSIZE, config->tftp_blksize);
if(config->mail_from)
my_setopt_str(curl, CURLOPT_MAIL_FROM, config->mail_from);
if(config->mail_rcpt)
my_setopt_slist(curl, CURLOPT_MAIL_RCPT, config->mail_rcpt);
/* curl 7.69.x */
my_setopt(curl, CURLOPT_MAIL_RCPT_ALLLOWFAILS,
config->mail_rcpt_allowfails ? 1L : 0L);
/* curl 7.20.x */
if(config->ftp_pret)
my_setopt(curl, CURLOPT_FTP_USE_PRET, 1L);
if(config->create_file_mode)
my_setopt(curl, CURLOPT_NEW_FILE_PERMS, config->create_file_mode);
if(config->proto_present)
my_setopt_flags(curl, CURLOPT_PROTOCOLS, config->proto);
if(config->proto_redir_present)
my_setopt_flags(curl, CURLOPT_REDIR_PROTOCOLS, config->proto_redir);
if(config->content_disposition
&& (urlnode->flags & GETOUT_USEREMOTE))
hdrcbdata->honor_cd_filename = TRUE;
else
hdrcbdata->honor_cd_filename = FALSE;
hdrcbdata->outs = outs;
hdrcbdata->heads = heads;
hdrcbdata->etag_save = etag_save;
hdrcbdata->global = global;
hdrcbdata->config = config;
my_setopt(curl, CURLOPT_HEADERFUNCTION, tool_header_cb);
my_setopt(curl, CURLOPT_HEADERDATA, per);
if(config->resolve)
/* new in 7.21.3 */
my_setopt_slist(curl, CURLOPT_RESOLVE, config->resolve);
if(config->connect_to)
/* new in 7.49.0 */
my_setopt_slist(curl, CURLOPT_CONNECT_TO, config->connect_to);
/* new in 7.21.4 */
if(curlinfo->features & CURL_VERSION_TLSAUTH_SRP) {
if(config->tls_username)
my_setopt_str(curl, CURLOPT_TLSAUTH_USERNAME,
config->tls_username);
if(config->tls_password)
my_setopt_str(curl, CURLOPT_TLSAUTH_PASSWORD,
config->tls_password);
if(config->tls_authtype)
my_setopt_str(curl, CURLOPT_TLSAUTH_TYPE,
config->tls_authtype);
if(config->proxy_tls_username)
my_setopt_str(curl, CURLOPT_PROXY_TLSAUTH_USERNAME,
config->proxy_tls_username);
if(config->proxy_tls_password)
my_setopt_str(curl, CURLOPT_PROXY_TLSAUTH_PASSWORD,
config->proxy_tls_password);
if(config->proxy_tls_authtype)
my_setopt_str(curl, CURLOPT_PROXY_TLSAUTH_TYPE,
config->proxy_tls_authtype);
}
/* new in 7.22.0 */
if(config->gssapi_delegation)
my_setopt_str(curl, CURLOPT_GSSAPI_DELEGATION,
config->gssapi_delegation);
if(config->mail_auth)
my_setopt_str(curl, CURLOPT_MAIL_AUTH, config->mail_auth);
/* new in 7.66.0 */
if(config->sasl_authzid)
my_setopt_str(curl, CURLOPT_SASL_AUTHZID, config->sasl_authzid);
/* new in 7.31.0 */
if(config->sasl_ir)
my_setopt(curl, CURLOPT_SASL_IR, 1L);
if(config->nonpn) {
my_setopt(curl, CURLOPT_SSL_ENABLE_NPN, 0L);
}
if(config->noalpn) {
my_setopt(curl, CURLOPT_SSL_ENABLE_ALPN, 0L);
}
/* new in 7.40.0, abstract support added in 7.53.0 */
if(config->unix_socket_path) {
if(config->abstract_unix_socket) {
my_setopt_str(curl, CURLOPT_ABSTRACT_UNIX_SOCKET,
config->unix_socket_path);
}
else {
my_setopt_str(curl, CURLOPT_UNIX_SOCKET_PATH,
config->unix_socket_path);
}
}
/* new in 7.45.0 */
if(config->proto_default)
my_setopt_str(curl, CURLOPT_DEFAULT_PROTOCOL, config->proto_default);
/* new in 7.47.0 */
if(config->expect100timeout > 0)
my_setopt_str(curl, CURLOPT_EXPECT_100_TIMEOUT_MS,
(long)(config->expect100timeout*1000));
/* new in 7.48.0 */
if(config->tftp_no_options)
my_setopt(curl, CURLOPT_TFTP_NO_OPTIONS, 1L);
/* new in 7.59.0 */
if(config->happy_eyeballs_timeout_ms != CURL_HET_DEFAULT)
my_setopt(curl, CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS,
config->happy_eyeballs_timeout_ms);
/* new in 7.60.0 */
if(config->haproxy_protocol)
my_setopt(curl, CURLOPT_HAPROXYPROTOCOL, 1L);
if(config->disallow_username_in_url)
my_setopt(curl, CURLOPT_DISALLOW_USERNAME_IN_URL, 1L);
if(config->altsvc)
my_setopt_str(curl, CURLOPT_ALTSVC, config->altsvc);
if(config->hsts)
my_setopt_str(curl, CURLOPT_HSTS, config->hsts);
/* initialize retry vars for loop below */
per->retry_sleep_default = (config->retry_delay) ?
config->retry_delay*1000L : RETRY_SLEEP_DEFAULT; /* ms */
per->retry_numretries = config->req_retry;
per->retry_sleep = per->retry_sleep_default; /* ms */
per->retrystart = tvnow();
state->li++;
/* Here's looping around each globbed URL */
if(state->li >= urlnum) {
state->li = 0;
state->urlnum = 0; /* forced reglob of URLs */
glob_cleanup(state->urls);
state->urls = NULL;
state->up++;
Curl_safefree(state->uploadfile); /* clear it to get the next */
}
}
else {
/* Free this URL node data without destroying the
node itself nor modifying next pointer. */
Curl_safefree(urlnode->outfile);
Curl_safefree(urlnode->infile);
urlnode->flags = 0;
glob_cleanup(state->urls);
state->urls = NULL;
state->urlnum = 0;
Curl_safefree(state->outfiles);
Curl_safefree(state->uploadfile);
if(state->inglob) {
/* Free list of globbed upload files */
glob_cleanup(state->inglob);
state->inglob = NULL;
}
config->state.urlnode = urlnode->next;
state->up = 0;
continue;
}
}
break;
}
if(!*added || result) {
*added = FALSE;
single_transfer_cleanup(config);
}
return result;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,292 |
LibRaw | e47384546b43d0fd536e933249047bc397a4d88b | void CLASS process_Sony_0x9402(uchar *buf, ushort len)
{
if (len < 23)
return;
imgdata.shootinginfo.FocusMode = SonySubstitution[buf[0x16]];
if ((imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_SLT) ||
(imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_ILCA))
return;
short bufx = buf[0x00];
if ((bufx == 0x05) || (bufx == 0xff) || (buf[0x02] != 0xff))
return;
imgdata.other.AmbientTemperature = (float)((short)SonySubstitution[buf[0x04]]);
return;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,897 |
wireshark | 5803c7b87b3414cdb8bf502af50bb406ca774482 | static int dissect_multipart(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data)
{
proto_tree *subtree;
proto_item *ti;
proto_item *type_ti;
http_message_info_t *message_info = (http_message_info_t *)data;
multipart_info_t *m_info = get_multipart_info(pinfo, message_info);
gint header_start = 0;
gint body_index = 0;
gboolean last_boundary = FALSE;
if (m_info == NULL) {
/*
* We can't get the required multipart information
*/
proto_tree_add_expert(tree, pinfo, &ei_multipart_no_required_parameter, tvb, 0, -1);
call_data_dissector(tvb, pinfo, tree);
return tvb_reported_length(tvb);
}
/* Add stuff to the protocol tree */
ti = proto_tree_add_item(tree, proto_multipart,
tvb, 0, -1, ENC_NA);
subtree = proto_item_add_subtree(ti, ett_multipart);
proto_item_append_text(ti, ", Type: %s, Boundary: \"%s\"",
m_info->type, m_info->boundary);
/* Show multi-part type as a generated field */
type_ti = proto_tree_add_string(subtree, hf_multipart_type,
tvb, 0, 0, pinfo->match_string);
PROTO_ITEM_SET_GENERATED(type_ti);
/*
* Make no entries in Protocol column and Info column on summary display,
* but stop sub-dissectors from clearing entered text in summary display.
*/
col_set_fence(pinfo->cinfo, COL_INFO);
/*
* Process the multipart preamble
*/
header_start = process_preamble(subtree, tvb, m_info, &last_boundary);
if (header_start == -1) {
call_data_dissector(tvb, pinfo, subtree);
return tvb_reported_length(tvb);
}
/*
* Process the encapsulated bodies
*/
while (last_boundary == FALSE) {
header_start = process_body_part(subtree, tvb, message_info, m_info,
pinfo, header_start, body_index++, &last_boundary);
if (header_start == -1) {
return tvb_reported_length(tvb);
}
}
/*
* Process the multipart trailer
*/
if (tvb_reported_length_remaining(tvb, header_start) > 0) {
proto_tree_add_item(subtree, hf_multipart_trailer, tvb, header_start, -1, ENC_NA);
}
return tvb_reported_length(tvb);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,455 |
ImageMagick6 | dc070da861a015d3c97488fdcca6063b44d47a7b | static const char *GetMagickPropertyLetter(const ImageInfo *image_info,
Image *image,const char letter)
{
#define WarnNoImageInfoReturn(format,arg) \
if (image_info == (ImageInfo *) NULL ) { \
(void) ThrowMagickException(&image->exception,GetMagickModule(), \
OptionWarning,"NoImageInfoForProperty",format,arg); \
return((const char *) NULL); \
}
char
value[MaxTextExtent];
const char
*string;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
*value='\0';
string=(char *) NULL;
switch (letter)
{
case 'b':
{
/*
Image size read in - in bytes.
*/
(void) FormatMagickSize(image->extent,MagickFalse,value);
if (image->extent == 0)
(void) FormatMagickSize(GetBlobSize(image),MagickFalse,value);
break;
}
case 'c':
{
/*
Image comment property - empty string by default.
*/
string=GetImageProperty(image,"comment");
if (string == (const char *) NULL)
string="";
break;
}
case 'd':
{
/*
Directory component of filename.
*/
GetPathComponent(image->magick_filename,HeadPath,value);
if (*value == '\0')
string="";
break;
}
case 'e':
{
/*
Filename extension (suffix) of image file.
*/
GetPathComponent(image->magick_filename,ExtensionPath,value);
if (*value == '\0')
string="";
break;
}
case 'f':
{
/*
Filename without directory component.
*/
GetPathComponent(image->magick_filename,TailPath,value);
if (*value == '\0')
string="";
break;
}
case 'g':
{
/*
Image geometry, canvas and offset %Wx%H+%X+%Y.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20gx%.20g%+.20g%+.20g",
(double) image->page.width,(double) image->page.height,
(double) image->page.x,(double) image->page.y);
break;
}
case 'h':
{
/*
Image height (current).
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
(image->rows != 0 ? image->rows : image->magick_rows));
break;
}
case 'i':
{
/*
Filename last used for image (read or write).
*/
string=image->filename;
break;
}
case 'k':
{
/*
Number of unique colors.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
GetNumberColors(image,(FILE *) NULL,&image->exception));
break;
}
case 'l':
{
/*
Image label property - empty string by default.
*/
string=GetImageProperty(image,"label");
if (string == (const char *) NULL)
string="";
break;
}
case 'm':
{
/*
Image format (file magick).
*/
string=image->magick;
break;
}
case 'n':
{
/*
Number of images in the list.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
GetImageListLength(image));
break;
}
case 'o':
{
/*
Output Filename - for delegate use only
*/
WarnNoImageInfoReturn("\"%%%c\"",letter);
string=image_info->filename;
break;
}
case 'p':
{
/*
Image index in current image list -- As 'n' OBSOLETE.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
GetImageIndexInList(image));
break;
}
case 'q':
{
/*
Quantum depth of image in memory.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
MAGICKCORE_QUANTUM_DEPTH);
break;
}
case 'r':
{
ColorspaceType
colorspace;
/*
Image storage class and colorspace.
*/
colorspace=image->colorspace;
if ((image->columns != 0) && (image->rows != 0) &&
(SetImageGray(image,&image->exception) != MagickFalse))
colorspace=GRAYColorspace;
(void) FormatLocaleString(value,MaxTextExtent,"%s %s %s",
CommandOptionToMnemonic(MagickClassOptions,(ssize_t)
image->storage_class),CommandOptionToMnemonic(MagickColorspaceOptions,
(ssize_t) colorspace),image->matte != MagickFalse ? "Matte" : "" );
break;
}
case 's':
{
/*
Image scene number.
*/
WarnNoImageInfoReturn("\"%%%c\"",letter);
if (image_info->number_scenes != 0)
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
image_info->scene);
else
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
image->scene);
break;
}
case 't':
{
/*
Base filename without directory or extension.
*/
GetPathComponent(image->magick_filename,BasePath,value);
break;
}
case 'u':
{
/*
Unique filename.
*/
WarnNoImageInfoReturn("\"%%%c\"",letter);
string=image_info->unique;
break;
}
case 'w':
{
/*
Image width (current).
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
(image->columns != 0 ? image->columns : image->magick_columns));
break;
}
case 'x':
{
/*
Image horizontal resolution.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",
fabs(image->x_resolution) > MagickEpsilon ? image->x_resolution :
image->units == PixelsPerCentimeterResolution ? DefaultResolution/2.54 :
DefaultResolution);
break;
}
case 'y':
{
/*
Image vertical resolution.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",
fabs(image->y_resolution) > MagickEpsilon ? image->y_resolution :
image->units == PixelsPerCentimeterResolution ? DefaultResolution/2.54 :
DefaultResolution);
break;
}
case 'z':
{
/*
Image depth.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
image->depth);
break;
}
case 'A':
{
/*
Image alpha channel.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%s",
CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) image->matte));
break;
}
case 'B':
{
/*
Image size read in - in bytes.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
image->extent);
if (image->extent == 0)
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
GetBlobSize(image));
break;
}
case 'C':
{
/*
Image compression method.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%s",
CommandOptionToMnemonic(MagickCompressOptions,(ssize_t)
image->compression));
break;
}
case 'D':
{
/*
Image dispose method.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%s",
CommandOptionToMnemonic(MagickDisposeOptions,(ssize_t) image->dispose));
break;
}
case 'F':
{
const char
*q;
char
*p;
static char
allowlist[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 "
"$-_.+!*'(),{}|\\^~[]`\"><#%;/?:@&=";
/*
Magick filename (sanitized) - filename given incl. coder & read mods.
*/
(void) CopyMagickString(value,image->magick_filename,MaxTextExtent);
p=value;
q=value+strlen(value);
for (p+=strspn(p,allowlist); p != q; p+=strspn(p,allowlist))
*p='_';
break;
}
case 'G':
{
/*
Image size as geometry = "%wx%h".
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20gx%.20g",(double)
image->magick_columns,(double) image->magick_rows);
break;
}
case 'H':
{
/*
Layer canvas height.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
image->page.height);
break;
}
case 'M':
{
/*
Magick filename - filename given incl. coder & read mods.
*/
string=image->magick_filename;
break;
}
case 'N': /* Number of images in the list. */
{
if ((image != (Image *) NULL) && (image->next == (Image *) NULL))
(void) FormatLocaleString(value,MagickPathExtent,"%.20g\n",(double)
GetImageListLength(image));
else
string="";
break;
}
case 'O':
{
/*
Layer canvas offset with sign = "+%X+%Y".
*/
(void) FormatLocaleString(value,MaxTextExtent,"%+ld%+ld",(long)
image->page.x,(long) image->page.y);
break;
}
case 'P':
{
/*
Layer canvas page size = "%Wx%H".
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20gx%.20g",(double)
image->page.width,(double) image->page.height);
break;
}
case 'Q':
{
/*
Image compression quality.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
(image->quality == 0 ? 92 : image->quality));
break;
}
case 'S':
{
/*
Image scenes.
*/
WarnNoImageInfoReturn("\"%%%c\"",letter);
if (image_info->number_scenes == 0)
string="2147483647";
else
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
image_info->scene+image_info->number_scenes);
break;
}
case 'T':
{
/*
Image time delay for animations.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
image->delay);
break;
}
case 'U':
{
/*
Image resolution units.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%s",
CommandOptionToMnemonic(MagickResolutionOptions,(ssize_t)
image->units));
break;
}
case 'W':
{
/*
Layer canvas width.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
image->page.width);
break;
}
case 'X':
{
/*
Layer canvas X offset.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%+.20g",(double)
image->page.x);
break;
}
case 'Y':
{
/*
Layer canvas Y offset.
*/
(void) FormatLocaleString(value,MaxTextExtent,"%+.20g",(double)
image->page.y);
break;
}
case 'Z':
{
/*
Zero filename.
*/
WarnNoImageInfoReturn("\"%%%c\"",letter);
string=image_info->zero;
break;
}
case '@':
{
RectangleInfo
page;
/*
Image bounding box.
*/
page=GetImageBoundingBox(image,&image->exception);
(void) FormatLocaleString(value,MaxTextExtent,"%.20gx%.20g%+.20g%+.20g",
(double) page.width,(double) page.height,(double) page.x,(double)
page.y);
break;
}
case '#':
{
/*
Image signature.
*/
if ((image->columns != 0) && (image->rows != 0))
(void) SignatureImage(image);
string=GetImageProperty(image,"signature");
break;
}
case '%':
{
/*
Percent escaped.
*/
string="%";
break;
}
}
if (*value != '\0')
string=value;
if (string != (char *) NULL)
{
(void) SetImageArtifact(image,"get-property",string);
return(GetImageArtifact(image,"get-property"));
}
return((char *) NULL);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,925 |
savannah | a18788b14db60ae3673f932249cd02d33a227c4e | tt_cmap10_char_next( TT_CMap cmap,
FT_UInt32 *pchar_code )
{
FT_Byte* table = cmap->data;
FT_UInt32 char_code = *pchar_code + 1;
FT_UInt gindex = 0;
FT_Byte* p = table + 12;
FT_UInt32 start = TT_NEXT_ULONG( p );
FT_UInt32 count = TT_NEXT_ULONG( p );
FT_UInt32 idx;
if ( char_code < start )
char_code = start;
idx = (FT_UInt32)( char_code - start );
p += 2 * idx;
for ( ; idx < count; idx++ )
{
gindex = TT_NEXT_USHORT( p );
if ( gindex != 0 )
break;
char_code++;
}
*pchar_code = char_code;
return gindex;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,226 |
linux | 1b5e2423164b3670e8bc9174e4762d297990deff | brcmf_cfg80211_set_rekey_data(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_gtk_rekey_data *gtk)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_gtk_keyinfo_le gtk_le;
int ret;
brcmf_dbg(TRACE, "Enter, bssidx=%d\n", ifp->bsscfgidx);
memcpy(gtk_le.kck, gtk->kck, sizeof(gtk_le.kck));
memcpy(gtk_le.kek, gtk->kek, sizeof(gtk_le.kek));
memcpy(gtk_le.replay_counter, gtk->replay_ctr,
sizeof(gtk_le.replay_counter));
ret = brcmf_fil_iovar_data_set(ifp, "gtk_key_info", >k_le,
sizeof(gtk_le));
if (ret < 0)
bphy_err(wiphy, "gtk_key_info iovar failed: ret=%d\n", ret);
return ret;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,917 |
Chrome | cfb022640b5eec337b06f88a485487dc92ca1ac1 | MediaStreamDispatcherHost::~MediaStreamDispatcherHost() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
CancelAllRequests();
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,197 |
linux | 942080643bce061c3dd9d5718d3b745dcb39a8bc | void ecryptfs_write_crypt_stat_flags(char *page_virt,
struct ecryptfs_crypt_stat *crypt_stat,
size_t *written)
{
u32 flags = 0;
int i;
for (i = 0; i < ((sizeof(ecryptfs_flag_map)
/ sizeof(struct ecryptfs_flag_map_elem))); i++)
if (crypt_stat->flags & ecryptfs_flag_map[i].local_flag)
flags |= ecryptfs_flag_map[i].file_flag;
/* Version is in top 8 bits of the 32-bit flag vector */
flags |= ((((u8)crypt_stat->file_version) << 24) & 0xFF000000);
put_unaligned_be32(flags, page_virt);
(*written) = 4;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,433 |
Chrome | dbcfe72cb16222c9f7e7907fcc5f35b27cc25331 | void NetworkActionPredictor::DeleteAllRows() {
if (!initialized_)
return;
db_cache_.clear();
db_id_cache_.clear();
content::BrowserThread::PostTask(content::BrowserThread::DB, FROM_HERE,
base::Bind(&NetworkActionPredictorDatabase::DeleteAllRows, db_));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,308 |
Chrome | 3fe224d430d863880df0050faaa037b0eb00d3c0 | aura::Window* OpenTestWindow(aura::Window* parent) {
views::Widget* widget =
views::Widget::CreateWindowWithParent(this, parent);
widget->Show();
return widget->GetNativeView();
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,008 |
linux | 434a964daa14b9db083ce20404a4a2add54d037a | void hfs_bmap_free(struct hfs_bnode *node)
{
struct hfs_btree *tree;
struct page *page;
u16 off, len;
u32 nidx;
u8 *data, byte, m;
dprint(DBG_BNODE_MOD, "btree_free_node: %u\n", node->this);
tree = node->tree;
nidx = node->this;
node = hfs_bnode_find(tree, 0);
if (IS_ERR(node))
return;
len = hfs_brec_lenoff(node, 2, &off);
while (nidx >= len * 8) {
u32 i;
nidx -= len * 8;
i = node->next;
hfs_bnode_put(node);
if (!i) {
/* panic */;
printk(KERN_CRIT "hfs: unable to free bnode %u. bmap not found!\n", node->this);
return;
}
node = hfs_bnode_find(tree, i);
if (IS_ERR(node))
return;
if (node->type != HFS_NODE_MAP) {
/* panic */;
printk(KERN_CRIT "hfs: invalid bmap found! (%u,%d)\n", node->this, node->type);
hfs_bnode_put(node);
return;
}
len = hfs_brec_lenoff(node, 0, &off);
}
off += node->page_offset + nidx / 8;
page = node->page[off >> PAGE_CACHE_SHIFT];
data = kmap(page);
off &= ~PAGE_CACHE_MASK;
m = 1 << (~nidx & 7);
byte = data[off];
if (!(byte & m)) {
printk(KERN_CRIT "hfs: trying to free free bnode %u(%d)\n", node->this, node->type);
kunmap(page);
hfs_bnode_put(node);
return;
}
data[off] = byte & ~m;
set_page_dirty(page);
kunmap(page);
hfs_bnode_put(node);
tree->free_nodes++;
mark_inode_dirty(tree->inode);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,653 |
mruby | a4d97934d51cb88954cc49161dc1d151f64afb6b | break_new(mrb_state *mrb, uint32_t tag, const struct RProc *p, mrb_value val)
{
struct RBreak *brk;
brk = MRB_OBJ_ALLOC(mrb, MRB_TT_BREAK, NULL);
mrb_break_proc_set(brk, p);
mrb_break_value_set(brk, val);
mrb_break_tag_set(brk, tag);
return brk;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,990 |
Chrome | 4504a474c069d07104237d0c03bfce7b29a42de6 | void HTMLMediaElement::MediaLoadingFailed(WebMediaPlayer::NetworkState error,
const String& message) {
BLINK_MEDIA_LOG << "MediaLoadingFailed(" << (void*)this << ", "
<< static_cast<int>(error) << ", message='" << message
<< "')";
StopPeriodicTimers();
if (ready_state_ < kHaveMetadata &&
load_state_ == kLoadingFromSourceElement) {
if (current_source_node_) {
current_source_node_->ScheduleErrorEvent();
} else {
BLINK_MEDIA_LOG << "mediaLoadingFailed(" << (void*)this
<< ") - error event not sent, <source> was removed";
}
ForgetResourceSpecificTracks();
if (HavePotentialSourceChild()) {
BLINK_MEDIA_LOG << "mediaLoadingFailed(" << (void*)this
<< ") - scheduling next <source>";
ScheduleNextSourceChild();
} else {
BLINK_MEDIA_LOG << "mediaLoadingFailed(" << (void*)this
<< ") - no more <source> elements, waiting";
WaitForSourceChange();
}
return;
}
if (error == WebMediaPlayer::kNetworkStateNetworkError &&
ready_state_ >= kHaveMetadata) {
MediaEngineError(MediaError::Create(MediaError::kMediaErrNetwork, message));
} else if (error == WebMediaPlayer::kNetworkStateDecodeError) {
MediaEngineError(MediaError::Create(MediaError::kMediaErrDecode, message));
} else if ((error == WebMediaPlayer::kNetworkStateFormatError ||
error == WebMediaPlayer::kNetworkStateNetworkError) &&
load_state_ == kLoadingFromSrcAttr) {
if (message.IsEmpty()) {
NoneSupported(BuildElementErrorMessage(
error == WebMediaPlayer::kNetworkStateFormatError ? "Format error"
: "Network error"));
} else {
NoneSupported(message);
}
}
UpdateDisplayState();
}
| 1 | CVE-2018-6177 | 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,530 |
tensorflow | c5b0d5f8ac19888e46ca14b0e27562e7fbbee9a9 | void Compute(OpKernelContext* ctx) override {
const Tensor& input = ctx->input(0);
OP_REQUIRES(ctx, axis_ < input.dims(),
errors::InvalidArgument(
"Axis requested is larger than input dimensions. Axis: ",
axis_, " Input Dimensions: ", input.dims()));
const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);
Tensor* output = nullptr;
OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));
Tensor num_bits_tensor;
num_bits_tensor = ctx->input(3);
int num_bits_val = num_bits_tensor.scalar<int32>()();
OP_REQUIRES(
ctx, num_bits_val > 0 && num_bits_val < (signed_input_ ? 62 : 63),
errors::InvalidArgument("num_bits is out of range: ", num_bits_val,
" with signed_input_ ", signed_input_));
Tensor input_min_tensor;
Tensor input_max_tensor;
if (range_given_) {
input_min_tensor = ctx->input(1);
input_max_tensor = ctx->input(2);
if (axis_ == -1) {
auto min_val = input_min_tensor.scalar<T>()();
auto max_val = input_max_tensor.scalar<T>()();
OP_REQUIRES(ctx, min_val <= max_val,
errors::InvalidArgument("Invalid range: input_min ",
min_val, " > input_max ", max_val));
} else {
OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth,
errors::InvalidArgument(
"input_min_tensor has incorrect size, was ",
input_min_tensor.dim_size(0), " expected ", depth,
" to match dim ", axis_, " of the input ",
input_min_tensor.shape()));
OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth,
errors::InvalidArgument(
"input_max_tensor has incorrect size, was ",
input_max_tensor.dim_size(0), " expected ", depth,
" to match dim ", axis_, " of the input ",
input_max_tensor.shape()));
}
} else {
auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth});
OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
range_shape, &input_min_tensor));
OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
range_shape, &input_max_tensor));
}
if (axis_ == -1) {
functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f;
f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_,
num_bits_val, range_given_, &input_min_tensor, &input_max_tensor,
ROUND_HALF_TO_EVEN, narrow_range_, output->flat<T>());
} else {
functor::QuantizeAndDequantizePerChannelFunctor<Device, T> f;
f(ctx->eigen_device<Device>(),
input.template flat_inner_outer_dims<T, 3>(axis_ - 1), signed_input_,
num_bits_val, range_given_, &input_min_tensor, &input_max_tensor,
ROUND_HALF_TO_EVEN, narrow_range_,
output->template flat_inner_outer_dims<T, 3>(axis_ - 1));
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,727 |
iperf | 91f2fa59e8ed80dfbf400add0164ee0e508e412a | send_parameters(struct iperf_test *test)
{
int r = 0;
cJSON *j;
j = cJSON_CreateObject();
if (j == NULL) {
i_errno = IESENDPARAMS;
r = -1;
} else {
if (test->protocol->id == Ptcp)
cJSON_AddTrueToObject(j, "tcp");
else if (test->protocol->id == Pudp)
cJSON_AddTrueToObject(j, "udp");
cJSON_AddIntToObject(j, "omit", test->omit);
if (test->server_affinity != -1)
cJSON_AddIntToObject(j, "server_affinity", test->server_affinity);
if (test->duration)
cJSON_AddIntToObject(j, "time", test->duration);
if (test->settings->bytes)
cJSON_AddIntToObject(j, "num", test->settings->bytes);
if (test->settings->blocks)
cJSON_AddIntToObject(j, "blockcount", test->settings->blocks);
if (test->settings->mss)
cJSON_AddIntToObject(j, "MSS", test->settings->mss);
if (test->no_delay)
cJSON_AddTrueToObject(j, "nodelay");
cJSON_AddIntToObject(j, "parallel", test->num_streams);
if (test->reverse)
cJSON_AddTrueToObject(j, "reverse");
if (test->settings->socket_bufsize)
cJSON_AddIntToObject(j, "window", test->settings->socket_bufsize);
if (test->settings->blksize)
cJSON_AddIntToObject(j, "len", test->settings->blksize);
if (test->settings->rate)
cJSON_AddIntToObject(j, "bandwidth", test->settings->rate);
if (test->settings->burst)
cJSON_AddIntToObject(j, "burst", test->settings->burst);
if (test->settings->tos)
cJSON_AddIntToObject(j, "TOS", test->settings->tos);
if (test->settings->flowlabel)
cJSON_AddIntToObject(j, "flowlabel", test->settings->flowlabel);
if (test->title)
cJSON_AddStringToObject(j, "title", test->title);
if (test->congestion)
cJSON_AddStringToObject(j, "congestion", test->congestion);
if (test->get_server_output)
cJSON_AddIntToObject(j, "get_server_output", iperf_get_test_get_server_output(test));
if (test->debug) {
printf("send_parameters:\n%s\n", cJSON_Print(j));
}
if (JSON_write(test->ctrl_sck, j) < 0) {
i_errno = IESENDPARAMS;
r = -1;
}
cJSON_Delete(j);
}
return r;
}
| 1 | CVE-2016-4303 | 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). | 546 |
lftp | a27e07d90a4608ceaf928b1babb27d4d803e1992 | void MirrorJob::SetOnChange(const char *oc)
{
on_change.set(oc);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,785 |
tcpdump | 83c64fce3a5226b080e535f5131a8a318f30e79b | rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)
{
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, ", RPKI-RTR"));
return;
}
while (len) {
u_int pdu_len = rpki_rtr_pdu_print(ndo, pptr, len, 1, 8);
len -= pdu_len;
pptr += pdu_len;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,792 |
nefarious2 | f50a84bad996d438e7b31b9e74c32a41e43f8be5 | static void sasl_timeout_callback(struct Event* ev)
{
struct Client *cptr;
assert(0 != ev_timer(ev));
assert(0 != t_data(ev_timer(ev)));
if (ev_type(ev) == ET_EXPIRE) {
cptr = (struct Client*) t_data(ev_timer(ev));
abort_sasl(cptr, 1);
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,822 |
FreeRDP | 2ee663f39dc8dac3d9988e847db19b2d7e3ac8c6 | void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name)
{
WLog_DBG(TAG, "%s (Len: %"PRIu16" MaxLen: %"PRIu16" BufferOffset: %"PRIu32")",
name, fields->Len, fields->MaxLen, fields->BufferOffset);
if (fields->Len > 0)
winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len);
}
| 1 | CVE-2018-8789 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 4,523 |
linux | c7559663e42f4294ffe31fe159da6b6a66b35d61 | int nfs_write_need_commit(struct nfs_write_data *data)
{
if (data->verf.committed == NFS_DATA_SYNC)
return data->header->lseg == NULL;
return data->verf.committed != NFS_FILE_SYNC;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,434 |
linux | 6aeb75e6adfaed16e58780309613a578fe1ee90b | static int edge_calc_num_ports(struct usb_serial *serial,
struct usb_serial_endpoints *epds)
{
struct device *dev = &serial->interface->dev;
unsigned char num_ports = serial->type->num_ports;
/* Make sure we have the required endpoints when in download mode. */
if (serial->interface->cur_altsetting->desc.bNumEndpoints > 1) {
if (epds->num_bulk_in < num_ports ||
epds->num_bulk_out < num_ports ||
epds->num_interrupt_in < 1) {
dev_err(dev, "required endpoints missing\n");
return -ENODEV;
}
}
return num_ports;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,729 |
tcpdump | 4c3aee4bb0294c232d56b6d34e9eeb74f630fe8c | mp_dss_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_dss *mdss = (const struct mp_dss *) opt;
if ((opt_len != mp_dss_len(mdss, 1) &&
opt_len != mp_dss_len(mdss, 0)) || flags & TH_SYN)
return 0;
if (mdss->flags & MP_DSS_F)
ND_PRINT((ndo, " fin"));
opt += 4;
if (mdss->flags & MP_DSS_A) {
ND_PRINT((ndo, " ack "));
if (mdss->flags & MP_DSS_a) {
ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt)));
opt += 8;
} else {
ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt)));
opt += 4;
}
}
if (mdss->flags & MP_DSS_M) {
ND_PRINT((ndo, " seq "));
if (mdss->flags & MP_DSS_m) {
ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt)));
opt += 8;
} else {
ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt)));
opt += 4;
}
ND_PRINT((ndo, " subseq %u", EXTRACT_32BITS(opt)));
opt += 4;
ND_PRINT((ndo, " len %u", EXTRACT_16BITS(opt)));
opt += 2;
if (opt_len == mp_dss_len(mdss, 1))
ND_PRINT((ndo, " csum 0x%x", EXTRACT_16BITS(opt)));
}
return 1;
}
| 1 | CVE-2017-13040 | 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,407 |
grep | 8fcf61523644df42e1905c81bed26838e0b04f91 | main (int argc, char **argv)
{
char *keys;
size_t keycc, oldcc, keyalloc;
int with_filenames;
size_t cc;
int opt, status, prepended;
int prev_optind, last_recursive;
intmax_t default_context;
FILE *fp;
exit_failure = EXIT_TROUBLE;
initialize_main (&argc, &argv);
set_program_name (argv[0]);
program_name = argv[0];
keys = NULL;
keycc = 0;
with_filenames = 0;
eolbyte = '\n';
filename_mask = ~0;
max_count = INTMAX_MAX;
/* The value -1 means to use DEFAULT_CONTEXT. */
out_after = out_before = -1;
/* Default before/after context: chaged by -C/-NUM options */
default_context = 0;
/* Changed by -o option */
only_matching = 0;
/* Internationalization. */
#if defined HAVE_SETLOCALE
setlocale (LC_ALL, "");
#endif
#if defined ENABLE_NLS
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
#endif
exit_failure = EXIT_TROUBLE;
atexit (clean_up_stdout);
last_recursive = 0;
prepended = prepend_default_options (getenv ("GREP_OPTIONS"), &argc, &argv);
setmatcher (NULL);
while (prev_optind = optind,
(opt = get_nondigit_option (argc, argv, &default_context)) != -1)
switch (opt)
{
case 'A':
context_length_arg (optarg, &out_after);
break;
case 'B':
context_length_arg (optarg, &out_before);
break;
case 'C':
/* Set output match context, but let any explicit leading or
trailing amount specified with -A or -B stand. */
context_length_arg (optarg, &default_context);
break;
case 'D':
if (STREQ (optarg, "read"))
devices = READ_DEVICES;
else if (STREQ (optarg, "skip"))
devices = SKIP_DEVICES;
else
error (EXIT_TROUBLE, 0, _("unknown devices method"));
break;
case 'E':
setmatcher ("egrep");
break;
case 'F':
setmatcher ("fgrep");
break;
case 'P':
setmatcher ("perl");
break;
case 'G':
setmatcher ("grep");
break;
case 'X': /* undocumented on purpose */
setmatcher (optarg);
break;
case 'H':
with_filenames = 1;
no_filenames = 0;
break;
case 'I':
binary_files = WITHOUT_MATCH_BINARY_FILES;
break;
case 'T':
align_tabs = 1;
break;
case 'U':
#if defined HAVE_DOS_FILE_CONTENTS
dos_use_file_type = DOS_BINARY;
#endif
break;
case 'u':
#if defined HAVE_DOS_FILE_CONTENTS
dos_report_unix_offset = 1;
#endif
break;
case 'V':
show_version = 1;
break;
case 'a':
binary_files = TEXT_BINARY_FILES;
break;
case 'b':
out_byte = 1;
break;
case 'c':
count_matches = 1;
break;
case 'd':
directories = XARGMATCH ("--directories", optarg,
directories_args, directories_types);
if (directories == RECURSE_DIRECTORIES)
last_recursive = prev_optind;
break;
case 'e':
cc = strlen (optarg);
keys = xrealloc (keys, keycc + cc + 1);
strcpy (&keys[keycc], optarg);
keycc += cc;
keys[keycc++] = '\n';
break;
case 'f':
fp = STREQ (optarg, "-") ? stdin : fopen (optarg, "r");
if (!fp)
error (EXIT_TROUBLE, errno, "%s", optarg);
for (keyalloc = 1; keyalloc <= keycc + 1; keyalloc *= 2)
;
keys = xrealloc (keys, keyalloc);
oldcc = keycc;
while (!feof (fp)
&& (cc = fread (keys + keycc, 1, keyalloc - 1 - keycc, fp)) > 0)
{
keycc += cc;
if (keycc == keyalloc - 1)
keys = x2nrealloc (keys, &keyalloc, sizeof *keys);
}
if (fp != stdin)
fclose (fp);
/* Append final newline if file ended in non-newline. */
if (oldcc != keycc && keys[keycc - 1] != '\n')
keys[keycc++] = '\n';
break;
case 'h':
with_filenames = 0;
no_filenames = 1;
break;
case 'i':
case 'y': /* For old-timers . . . */
match_icase = 1;
break;
case 'L':
/* Like -l, except list files that don't contain matches.
Inspired by the same option in Hume's gre. */
list_files = -1;
break;
case 'l':
list_files = 1;
break;
case 'm':
switch (xstrtoimax (optarg, 0, 10, &max_count, ""))
{
case LONGINT_OK:
case LONGINT_OVERFLOW:
break;
default:
error (EXIT_TROUBLE, 0, _("invalid max count"));
}
break;
case 'n':
out_line = 1;
break;
case 'o':
only_matching = 1;
break;
case 'q':
exit_on_match = 1;
exit_failure = 0;
break;
case 'R':
case 'r':
directories = RECURSE_DIRECTORIES;
last_recursive = prev_optind;
break;
case 's':
suppress_errors = 1;
break;
case 'v':
out_invert = 1;
break;
case 'w':
match_words = 1;
break;
case 'x':
match_lines = 1;
break;
case 'Z':
filename_mask = 0;
break;
case 'z':
eolbyte = '\0';
break;
case BINARY_FILES_OPTION:
if (STREQ (optarg, "binary"))
binary_files = BINARY_BINARY_FILES;
else if (STREQ (optarg, "text"))
binary_files = TEXT_BINARY_FILES;
else if (STREQ (optarg, "without-match"))
binary_files = WITHOUT_MATCH_BINARY_FILES;
else
error (EXIT_TROUBLE, 0, _("unknown binary-files type"));
break;
case COLOR_OPTION:
if (optarg)
{
if (!strcasecmp (optarg, "always") || !strcasecmp (optarg, "yes")
|| !strcasecmp (optarg, "force"))
color_option = 1;
else if (!strcasecmp (optarg, "never") || !strcasecmp (optarg, "no")
|| !strcasecmp (optarg, "none"))
color_option = 0;
else if (!strcasecmp (optarg, "auto") || !strcasecmp (optarg, "tty")
|| !strcasecmp (optarg, "if-tty"))
color_option = 2;
else
show_help = 1;
}
else
color_option = 2;
break;
case EXCLUDE_OPTION:
if (!excluded_patterns)
excluded_patterns = new_exclude ();
add_exclude (excluded_patterns, optarg, EXCLUDE_WILDCARDS);
break;
case EXCLUDE_FROM_OPTION:
if (!excluded_patterns)
excluded_patterns = new_exclude ();
if (add_exclude_file (add_exclude, excluded_patterns, optarg,
EXCLUDE_WILDCARDS, '\n') != 0)
{
error (EXIT_TROUBLE, errno, "%s", optarg);
}
break;
case EXCLUDE_DIRECTORY_OPTION:
if (!excluded_directory_patterns)
excluded_directory_patterns = new_exclude ();
add_exclude (excluded_directory_patterns, optarg, EXCLUDE_WILDCARDS);
break;
case INCLUDE_OPTION:
if (!included_patterns)
included_patterns = new_exclude ();
add_exclude (included_patterns, optarg,
EXCLUDE_WILDCARDS | EXCLUDE_INCLUDE);
break;
case GROUP_SEPARATOR_OPTION:
group_separator = optarg;
break;
case LINE_BUFFERED_OPTION:
line_buffered = 1;
break;
case LABEL_OPTION:
label = optarg;
break;
case MMAP_OPTION:
error (0, 0, _("the --mmap option has been a no-op since 2010"));
break;
case 0:
/* long options */
break;
default:
usage (EXIT_TROUBLE);
break;
}
if (color_option == 2)
color_option = isatty (STDOUT_FILENO) && should_colorize ();
init_colorize ();
/* POSIX.2 says that -q overrides -l, which in turn overrides the
other output options. */
if (exit_on_match)
list_files = 0;
if (exit_on_match | list_files)
{
count_matches = 0;
done_on_match = 1;
}
out_quiet = count_matches | done_on_match;
if (out_after < 0)
out_after = default_context;
if (out_before < 0)
out_before = default_context;
if (color_option)
{
/* Legacy. */
char *userval = getenv ("GREP_COLOR");
if (userval != NULL && *userval != '\0')
selected_match_color = context_match_color = userval;
/* New GREP_COLORS has priority. */
parse_grep_colors ();
}
if (show_version)
{
version_etc (stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS,
(char *) NULL);
exit (EXIT_SUCCESS);
}
if (show_help)
usage (EXIT_SUCCESS);
struct stat tmp_stat;
if (fstat (STDOUT_FILENO, &tmp_stat) == 0 && S_ISREG (tmp_stat.st_mode))
out_stat = tmp_stat;
if (keys)
{
if (keycc == 0)
{
/* No keys were specified (e.g. -f /dev/null). Match nothing. */
out_invert ^= 1;
match_lines = match_words = 0;
}
else
/* Strip trailing newline. */
--keycc;
}
else if (optind < argc)
{
/* A copy must be made in case of an xrealloc() or free() later. */
keycc = strlen (argv[optind]);
keys = xmalloc (keycc + 1);
strcpy (keys, argv[optind++]);
}
else
usage (EXIT_TROUBLE);
compile (keys, keycc);
free (keys);
if ((argc - optind > 1 && !no_filenames) || with_filenames)
out_file = 1;
#ifdef SET_BINARY
/* Output is set to binary mode because we shouldn't convert
NL to CR-LF pairs, especially when grepping binary files. */
if (!isatty (1))
SET_BINARY (1);
#endif
if (max_count == 0)
exit (EXIT_FAILURE);
if (optind < argc)
{
status = 1;
do
{
char *file = argv[optind];
if (!STREQ (file, "-")
&& (included_patterns || excluded_patterns
|| excluded_directory_patterns))
{
if (isdir (file))
{
if (excluded_directory_patterns
&& excluded_file_name (excluded_directory_patterns,
file))
continue;
}
else
{
if (included_patterns
&& excluded_file_name (included_patterns, file))
continue;
if (excluded_patterns
&& excluded_file_name (excluded_patterns, file))
continue;
}
}
status &= grepfile (STREQ (file, "-") ? (char *) NULL : file,
&stats_base);
}
while (++optind < argc);
}
else if (directories == RECURSE_DIRECTORIES && prepended < last_recursive)
{
status = 1;
if (stat (".", &stats_base.stat) == 0)
status = grepdir (NULL, &stats_base);
else
suppressible_error (".", errno);
}
else
status = grepfile ((char *) NULL, &stats_base);
/* We register via atexit() to test stdout. */
exit (errseen ? EXIT_TROUBLE : status);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,951 |
linux | a4270d6795b0580287453ea55974d948393e66ef | */
int netdev_master_upper_dev_link(struct net_device *dev,
struct net_device *upper_dev,
void *upper_priv, void *upper_info,
struct netlink_ext_ack *extack)
{
return __netdev_upper_dev_link(dev, upper_dev, true,
upper_priv, upper_info, extack); | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,657 |
radare2 | ead645853a63bf83d8386702cad0cf23b31d7eeb | static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) {
struct r_bin_t *rbin = arch->rbin;
int i;
int *methods = NULL;
int sym_count = 0;
// doublecheck??
if (!bin || bin->methods_list) {
return false;
}
bin->code_from = UT64_MAX;
bin->code_to = 0;
bin->methods_list = r_list_newf ((RListFree)free);
if (!bin->methods_list) {
return false;
}
bin->imports_list = r_list_newf ((RListFree)free);
if (!bin->imports_list) {
r_list_free (bin->methods_list);
return false;
}
bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free);
if (!bin->classes_list) {
r_list_free (bin->methods_list);
r_list_free (bin->imports_list);
return false;
}
if (bin->header.method_size>bin->size) {
bin->header.method_size = 0;
return false;
}
/* WrapDown the header sizes to avoid huge allocations */
bin->header.method_size = R_MIN (bin->header.method_size, bin->size);
bin->header.class_size = R_MIN (bin->header.class_size, bin->size);
bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size);
// TODO: is this posible after R_MIN ??
if (bin->header.strings_size > bin->size) {
eprintf ("Invalid strings size\n");
return false;
}
if (bin->classes) {
ut64 amount = sizeof (int) * bin->header.method_size;
if (amount > UT32_MAX || amount < bin->header.method_size) {
return false;
}
methods = calloc (1, amount + 1);
for (i = 0; i < bin->header.class_size; i++) {
char *super_name, *class_name;
struct dex_class_t *c = &bin->classes[i];
class_name = dex_class_name (bin, c);
super_name = dex_class_super_name (bin, c);
if (dexdump) {
rbin->cb_printf ("Class #%d -\n", i);
}
parse_class (arch, bin, c, i, methods, &sym_count);
free (class_name);
free (super_name);
}
}
if (methods) {
int import_count = 0;
int sym_count = bin->methods_list->length;
for (i = 0; i < bin->header.method_size; i++) {
int len = 0;
if (methods[i]) {
continue;
}
if (bin->methods[i].class_id > bin->header.types_size - 1) {
continue;
}
if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) {
continue;
}
char *class_name = getstr (
bin, bin->types[bin->methods[i].class_id]
.descriptor_id);
if (!class_name) {
free (class_name);
continue;
}
len = strlen (class_name);
if (len < 1) {
continue;
}
class_name[len - 1] = 0; // remove last char ";"
char *method_name = dex_method_name (bin, i);
char *signature = dex_method_signature (bin, i);
if (method_name && *method_name) {
RBinImport *imp = R_NEW0 (RBinImport);
imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature);
imp->type = r_str_const ("FUNC");
imp->bind = r_str_const ("NONE");
imp->ordinal = import_count++;
r_list_append (bin->imports_list, imp);
RBinSymbol *sym = R_NEW0 (RBinSymbol);
sym->name = r_str_newf ("imp.%s", imp->name);
sym->type = r_str_const ("FUNC");
sym->bind = r_str_const ("NONE");
//XXX so damn unsafe check buffer boundaries!!!!
//XXX use r_buf API!!
sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ;
sym->ordinal = sym_count++;
r_list_append (bin->methods_list, sym);
sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0);
}
free (method_name);
free (signature);
free (class_name);
}
free (methods);
}
return true;
} | 1 | CVE-2017-6387 | 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,614 |
linux | 99253eb750fda6a644d5188fb26c43bad8d5a745 | static struct mfc6_cache *ip6mr_cache_find(struct mr6_table *mrt,
const struct in6_addr *origin,
const struct in6_addr *mcastgrp)
{
int line = MFC6_HASH(mcastgrp, origin);
struct mfc6_cache *c;
list_for_each_entry(c, &mrt->mfc6_cache_array[line], list) {
if (ipv6_addr_equal(&c->mf6c_origin, origin) &&
ipv6_addr_equal(&c->mf6c_mcastgrp, mcastgrp))
return c;
}
return NULL;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,894 |
busybox | 150dc7a2b483b8338a3e185c478b4b23ee884e71 | adjust_poll(int count)
{
G.polladj_count += count;
if (G.polladj_count > POLLADJ_LIMIT) {
G.polladj_count = 0;
if (G.poll_exp < MAXPOLL) {
G.poll_exp++;
VERB4 bb_error_msg("polladj: discipline_jitter:%f ++poll_exp=%d",
G.discipline_jitter, G.poll_exp);
}
} else if (G.polladj_count < -POLLADJ_LIMIT || (count < 0 && G.poll_exp > BIGPOLL)) {
G.polladj_count = 0;
if (G.poll_exp > MINPOLL) {
llist_t *item;
G.poll_exp--;
/* Correct p->next_action_time in each peer
* which waits for sending, so that they send earlier.
* Old pp->next_action_time are on the order
* of t + (1 << old_poll_exp) + small_random,
* we simply need to subtract ~half of that.
*/
for (item = G.ntp_peers; item != NULL; item = item->link) {
peer_t *pp = (peer_t *) item->data;
if (pp->p_fd < 0)
pp->next_action_time -= (1 << G.poll_exp);
}
VERB4 bb_error_msg("polladj: discipline_jitter:%f --poll_exp=%d",
G.discipline_jitter, G.poll_exp);
}
} else {
VERB4 bb_error_msg("polladj: count:%d", G.polladj_count);
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,895 |
Chrome | 3ca8e38ff57e83fcce76f9b54cd8f8bfa09c34ad | bool DoResolveRelativeHost(const char* base_url,
const url_parse::Parsed& base_parsed,
const CHAR* relative_url,
const url_parse::Component& relative_component,
CharsetConverter* query_converter,
CanonOutput* output,
url_parse::Parsed* out_parsed) {
url_parse::Parsed relative_parsed; // Everything but the scheme is valid.
url_parse::ParseAfterScheme(&relative_url[relative_component.begin],
relative_component.len, relative_component.begin,
&relative_parsed);
Replacements<CHAR> replacements;
replacements.SetUsername(relative_url, relative_parsed.username);
replacements.SetPassword(relative_url, relative_parsed.password);
replacements.SetHost(relative_url, relative_parsed.host);
replacements.SetPort(relative_url, relative_parsed.port);
replacements.SetPath(relative_url, relative_parsed.path);
replacements.SetQuery(relative_url, relative_parsed.query);
replacements.SetRef(relative_url, relative_parsed.ref);
return ReplaceStandardURL(base_url, base_parsed, replacements,
query_converter, output, out_parsed);
}
| 1 | CVE-2013-2920 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 1,107 |
php | 97aa752fee61fccdec361279adbfb17a3c60f3f4 | MYSQLND_METHOD(mysqlnd_conn_data, error)(const MYSQLND_CONN_DATA * const conn TSRMLS_DC)
{
return conn->error_info->error;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,271 |
radare2 | bd1bab05083d80464fea854bf4b5c49aaf1b8401 | static void r_bin_dwarf_dump_debug_info(FILE *f, const RBinDwarfDebugInfo *inf) {
size_t i, j, k;
RBinDwarfDIE *dies;
RBinDwarfAttrValue *values;
if (!inf || !f) {
return;
}
for (i = 0; i < inf->length; i++) {
fprintf (f, " Compilation Unit @ offset 0x%"PFMT64x":\n", inf->comp_units [i].offset);
fprintf (f, " Length: 0x%x\n", inf->comp_units [i].hdr.length);
fprintf (f, " Version: %d\n", inf->comp_units [i].hdr.version);
fprintf (f, " Abbrev Offset: 0x%x\n", inf->comp_units [i].hdr.abbrev_offset);
fprintf (f, " Pointer Size: %d\n", inf->comp_units [i].hdr.pointer_size);
dies = inf->comp_units[i].dies;
for (j = 0; j < inf->comp_units[i].length; j++) {
fprintf (f, " Abbrev Number: %"PFMT64u" ", dies[j].abbrev_code);
if (dies[j].tag && dies[j].tag <= DW_TAG_volatile_type &&
dwarf_tag_name_encodings[dies[j].tag]) {
fprintf (f, "(%s)\n", dwarf_tag_name_encodings[dies[j].tag]);
} else {
fprintf (f, "(Unknown abbrev tag)\n");
}
if (!dies[j].abbrev_code) {
continue;
}
values = dies[j].attr_values;
for (k = 0; k < dies[j].length; k++) {
if (!values[k].name) {
continue;
}
if (values[k].name < DW_AT_vtable_elem_location &&
dwarf_attr_encodings[values[k].name]) {
fprintf (f, " %-18s : ", dwarf_attr_encodings[values[k].name]);
} else {
fprintf (f, " TODO\t");
}
r_bin_dwarf_dump_attr_value (&values[k], f);
fprintf (f, "\n");
}
}
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,156 |
samba | fab6b79b7724f0b636963be528483e3e946884aa | static int ldb_canonicalise_generalizedtime(struct ldb_context *ldb, void *mem_ctx,
const struct ldb_val *in, struct ldb_val *out)
{
time_t t;
int ret;
ret = ldb_val_to_time(in, &t);
if (ret != LDB_SUCCESS) {
return ret;
}
out->data = (uint8_t *)ldb_timestring(mem_ctx, t);
if (out->data == NULL) {
ldb_oom(ldb);
return LDB_ERR_OPERATIONS_ERROR;
}
out->length = strlen((char *)out->data);
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,243 |
qemu | 070c4b92b8cd5390889716677a0b92444d6e087a | static void mcf_fec_do_tx(mcf_fec_state *s)
{
uint32_t addr;
mcf_fec_bd bd;
int frame_size;
int len;
uint8_t frame[FEC_MAX_FRAME_SIZE];
uint8_t *ptr;
DPRINTF("do_tx\n");
ptr = frame;
frame_size = 0;
addr = s->tx_descriptor;
while (1) {
mcf_fec_read_bd(&bd, addr);
DPRINTF("tx_bd %x flags %04x len %d data %08x\n",
addr, bd.flags, bd.length, bd.data);
if ((bd.flags & FEC_BD_R) == 0) {
/* Run out of descriptors to transmit. */
break;
}
len = bd.length;
if (frame_size + len > FEC_MAX_FRAME_SIZE) {
len = FEC_MAX_FRAME_SIZE - frame_size;
s->eir |= FEC_INT_BABT;
}
cpu_physical_memory_read(bd.data, ptr, len);
ptr += len;
frame_size += len;
if (bd.flags & FEC_BD_L) {
/* Last buffer in frame. */
DPRINTF("Sending packet\n");
qemu_send_packet(qemu_get_queue(s->nic), frame, len);
ptr = frame;
frame_size = 0;
s->eir |= FEC_INT_TXF;
}
s->eir |= FEC_INT_TXB;
bd.flags &= ~FEC_BD_R;
/* Write back the modified descriptor. */
mcf_fec_write_bd(&bd, addr);
/* Advance to the next descriptor. */
if ((bd.flags & FEC_BD_W) != 0) {
addr = s->etdsr;
} else {
addr += 8;
}
}
s->tx_descriptor = addr;
} | 1 | CVE-2016-7908 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 7,459 |
file-roller | f70be1f41688859ec8dbe266df35a1839ceb96c5 | _g_path_get_temp_work_dir (const char *parent_folder)
{
guint64 max_size = 0;
char *best_folder = NULL;
int i;
char *template;
char *result = NULL;
if (parent_folder == NULL) {
/* find the folder with more free space. */
for (i = 0; try_folder[i] != NULL; i++) {
const char *folder;
GFile *file;
guint64 size;
folder = get_nth_temp_folder_to_try (i);
file = g_file_new_for_path (folder);
size = _g_file_get_free_space (file);
g_object_unref (file);
if (max_size < size) {
max_size = size;
g_free (best_folder);
best_folder = g_strdup (folder);
}
}
}
else
best_folder = g_strdup (parent_folder);
if (best_folder == NULL)
return NULL;
template = g_strconcat (best_folder, "/.fr-XXXXXX", NULL);
result = mkdtemp (template);
g_free (best_folder);
if ((result == NULL) || (*result == '\0')) {
g_free (template);
result = NULL;
}
return result;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,744 |
libav | fb1473080223a634b8ac2cca48a632d037a0a69d | static av_cold int aac_parse_init(AVCodecParserContext *s1)
{
AACAC3ParseContext *s = s1->priv_data;
s->header_size = AAC_ADTS_HEADER_SIZE;
s->sync = aac_sync;
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,681 |
linux | 92964c79b357efd980812c4de5c1fd2ec8bb5520 | static struct sock *netlink_lookup(struct net *net, int protocol, u32 portid)
{
struct netlink_table *table = &nl_table[protocol];
struct sock *sk;
rcu_read_lock();
sk = __netlink_lookup(table, portid, net);
if (sk)
sock_hold(sk);
rcu_read_unlock();
return sk;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,075 |
tcpdump | 211124b972e74f0da66bc8b16f181f78793e2f66 | static int dccp_print_option(netdissect_options *ndo, const u_char *option, u_int hlen)
{
uint8_t optlen, i;
ND_TCHECK(*option);
if (*option >= 32) {
ND_TCHECK(*(option+1));
optlen = *(option +1);
if (optlen < 2) {
if (*option >= 128)
ND_PRINT((ndo, "CCID option %u optlen too short", *option));
else
ND_PRINT((ndo, "%s optlen too short",
tok2str(dccp_option_values, "Option %u", *option)));
return 0;
}
} else
optlen = 1;
if (hlen < optlen) {
if (*option >= 128)
ND_PRINT((ndo, "CCID option %u optlen goes past header length",
*option));
else
ND_PRINT((ndo, "%s optlen goes past header length",
tok2str(dccp_option_values, "Option %u", *option)));
return 0;
}
ND_TCHECK2(*option, optlen);
if (*option >= 128) {
ND_PRINT((ndo, "CCID option %d", *option));
switch (optlen) {
case 4:
ND_PRINT((ndo, " %u", EXTRACT_16BITS(option + 2)));
break;
case 6:
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
break;
default:
break;
}
} else {
ND_PRINT((ndo, "%s", tok2str(dccp_option_values, "Option %u", *option)));
switch (*option) {
case 32:
case 33:
case 34:
case 35:
if (optlen < 3) {
ND_PRINT((ndo, " optlen too short"));
return optlen;
}
if (*(option + 2) < 10){
ND_PRINT((ndo, " %s", dccp_feature_nums[*(option + 2)]));
for (i = 0; i < optlen - 3; i++)
ND_PRINT((ndo, " %d", *(option + 3 + i)));
}
break;
case 36:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 37:
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, " %d", *(option + 2 + i)));
break;
case 38:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 39:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 40:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 41:
if (optlen == 4)
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
else
ND_PRINT((ndo, " optlen != 4"));
break;
case 42:
if (optlen == 4)
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
else
ND_PRINT((ndo, " optlen != 4"));
break;
case 43:
if (optlen == 6)
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
else if (optlen == 4)
ND_PRINT((ndo, " %u", EXTRACT_16BITS(option + 2)));
else
ND_PRINT((ndo, " optlen != 4 or 6"));
break;
case 44:
if (optlen > 2) {
ND_PRINT((ndo, " "));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
}
}
return optlen;
trunc:
ND_PRINT((ndo, "%s", tstr));
return 0;
}
| 1 | CVE-2018-16229 | 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,944 |
Chrome | 0bd10e13a008389ec14bbe7cc95f17d82ea151c1 | void TestClearOnlyAutofilledFields(const char* html) {
LoadHTML(html);
WebLocalFrame* web_frame = GetMainFrame();
ASSERT_NE(nullptr, web_frame);
FormCache form_cache(web_frame);
std::vector<FormData> forms = form_cache.ExtractNewForms();
ASSERT_EQ(1U, forms.size());
WebInputElement firstname = GetInputElementById("firstname");
firstname.SetAutofillState(WebAutofillState::kNotFilled);
WebInputElement lastname = GetInputElementById("lastname");
lastname.SetAutofillState(WebAutofillState::kAutofilled);
WebInputElement email = GetInputElementById("email");
email.SetAutofillState(WebAutofillState::kAutofilled);
WebInputElement phone = GetInputElementById("phone");
phone.SetAutofillState(WebAutofillState::kAutofilled);
EXPECT_TRUE(form_cache.ClearSectionWithElement(firstname));
EXPECT_EQ(ASCIIToUTF16("Wyatt"), firstname.Value().Utf16());
EXPECT_TRUE(firstname.SuggestedValue().IsEmpty());
EXPECT_FALSE(firstname.IsAutofilled());
EXPECT_TRUE(lastname.Value().IsEmpty());
EXPECT_TRUE(lastname.SuggestedValue().IsEmpty());
EXPECT_FALSE(lastname.IsAutofilled());
EXPECT_TRUE(email.Value().IsEmpty());
EXPECT_TRUE(email.SuggestedValue().IsEmpty());
EXPECT_FALSE(email.IsAutofilled());
EXPECT_TRUE(phone.Value().IsEmpty());
EXPECT_TRUE(phone.SuggestedValue().IsEmpty());
EXPECT_FALSE(phone.IsAutofilled());
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,122 |
linux | 9e3bb6b6f6a0c535eb053fbf0005a8e79e053374 | int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
int seg;
int offset = offset_in_page(gpa);
int ret;
while ((seg = next_segment(len, offset)) != 0) {
ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
if (ret < 0)
return ret;
offset = 0;
len -= seg;
++gfn;
}
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,809 |
ImageMagick6 | a906fe9298bf89e01d5272023db687935068849a | static PixelChannels **AcquirePixelThreadSet(const Image *image)
{
PixelChannels
**pixels;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(PixelChannels **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (PixelChannels **) NULL)
return((PixelChannels **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
for (i=0; i < (ssize_t) number_threads; i++)
{
register ssize_t
j;
pixels[i]=(PixelChannels *) AcquireQuantumMemory(image->columns,
sizeof(**pixels));
if (pixels[i] == (PixelChannels *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) image->columns; j++)
{
register ssize_t
k;
for (k=0; k < MaxPixelChannels; k++)
pixels[i][j].channel[k]=0.0;
}
}
return(pixels);
}
| 1 | CVE-2019-13300 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 2,982 |
FreeRDP | 0773bb9303d24473fe1185d85a424dfe159aff53 | SECURITY_STATUS SEC_ENTRY DeleteSecurityContext(PCtxtHandle phContext)
{
char* Name;
SECURITY_STATUS status;
SecurityFunctionTableA* table;
Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);
if (!Name)
return SEC_E_SECPKG_NOT_FOUND;
table = sspi_GetSecurityFunctionTableAByNameA(Name);
if (!table)
return SEC_E_SECPKG_NOT_FOUND;
if (table->DeleteSecurityContext == NULL)
return SEC_E_UNSUPPORTED_FUNCTION;
status = table->DeleteSecurityContext(phContext);
return status;
}
| 1 | CVE-2013-4119 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 8,051 |
linux | ea04efee7635c9120d015dcdeeeb6988130cb67a | static int ims_pcu_parse_cdc_data(struct usb_interface *intf, struct ims_pcu *pcu)
{
const struct usb_cdc_union_desc *union_desc;
struct usb_host_interface *alt;
union_desc = ims_pcu_get_cdc_union_desc(intf);
if (!union_desc)
return -EINVAL;
pcu->ctrl_intf = usb_ifnum_to_if(pcu->udev,
union_desc->bMasterInterface0);
if (!pcu->ctrl_intf)
return -EINVAL;
alt = pcu->ctrl_intf->cur_altsetting;
if (alt->desc.bNumEndpoints < 1)
return -ENODEV;
pcu->ep_ctrl = &alt->endpoint[0].desc;
pcu->max_ctrl_size = usb_endpoint_maxp(pcu->ep_ctrl);
pcu->data_intf = usb_ifnum_to_if(pcu->udev,
union_desc->bSlaveInterface0);
if (!pcu->data_intf)
return -EINVAL;
alt = pcu->data_intf->cur_altsetting;
if (alt->desc.bNumEndpoints != 2) {
dev_err(pcu->dev,
"Incorrect number of endpoints on data interface (%d)\n",
alt->desc.bNumEndpoints);
return -EINVAL;
}
pcu->ep_out = &alt->endpoint[0].desc;
if (!usb_endpoint_is_bulk_out(pcu->ep_out)) {
dev_err(pcu->dev,
"First endpoint on data interface is not BULK OUT\n");
return -EINVAL;
}
pcu->max_out_size = usb_endpoint_maxp(pcu->ep_out);
if (pcu->max_out_size < 8) {
dev_err(pcu->dev,
"Max OUT packet size is too small (%zd)\n",
pcu->max_out_size);
return -EINVAL;
}
pcu->ep_in = &alt->endpoint[1].desc;
if (!usb_endpoint_is_bulk_in(pcu->ep_in)) {
dev_err(pcu->dev,
"Second endpoint on data interface is not BULK IN\n");
return -EINVAL;
}
pcu->max_in_size = usb_endpoint_maxp(pcu->ep_in);
if (pcu->max_in_size < 8) {
dev_err(pcu->dev,
"Max IN packet size is too small (%zd)\n",
pcu->max_in_size);
return -EINVAL;
}
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,819 |
linux | 0b79459b482e85cb7426aa7da683a9f2c97aeae1 | static void kvmclock_reset(struct kvm_vcpu *vcpu)
{
if (vcpu->arch.time_page) {
kvm_release_page_dirty(vcpu->arch.time_page);
vcpu->arch.time_page = NULL;
}
}
| 1 | CVE-2013-1797 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 6,422 |
httpd | cd2b7a26c776b0754fb98426a67804fd48118708 | AP_DECLARE(void) ap_destroy_sub_req(request_rec *r)
{
/* Reclaim the space */
apr_pool_destroy(r->pool);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,852 |
php | 25e8fcc88fa20dc9d4c47184471003f436927cde | static char *ps_files_path_create(char *buf, size_t buflen, ps_files *data, const char *key)
{
{
size_t len;
const char *p;
char c;
int ret = 1;
for (p = key; (c = *p); p++) {
/* valid characters are a..z,A..Z,0..9 */
if (!((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == ','
|| c == '-')) {
ret = 0;
break;
}
}
len = p - key;
/* Somewhat arbitrary length limit here, but should be way more than
anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */
if (len == 0 || len > 128) {
ret = 0;
}
return ret;
}
static char *ps_files_path_create(char *buf, size_t buflen, ps_files *data, const char *key)
{
size_t key_len;
const char *p;
int i;
int n;
key_len = strlen(key);
if (key_len <= data->dirdepth ||
buflen < (strlen(data->basedir) + 2 * data->dirdepth + key_len + 5 + sizeof(FILE_PREFIX))) {
return NULL;
}
p = key;
memcpy(buf, data->basedir, data->basedir_len);
n = data->basedir_len;
buf[n++] = PHP_DIR_SEPARATOR;
for (i = 0; i < (int)data->dirdepth; i++) {
buf[n++] = *p++;
buf[n++] = PHP_DIR_SEPARATOR;
}
memcpy(buf + n, FILE_PREFIX, sizeof(FILE_PREFIX) - 1);
n += sizeof(FILE_PREFIX) - 1;
memcpy(buf + n, key, key_len);
n += key_len;
ps_files_close(data);
if (!ps_files_valid_key(key)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'");
PS(invalid_session_id) = 1;
return;
}
if (!ps_files_path_create(buf, sizeof(buf), data, key)) {
return;
}
if (data->fd != -1) {
#ifdef PHP_WIN32
/* On Win32 locked files that are closed without being explicitly unlocked
will be unlocked only when "system resources become available". */
flock(data->fd, LOCK_UN);
#endif
close(data->fd);
data->fd = -1;
}
}
static void ps_files_open(ps_files *data, const char *key TSRMLS_DC)
{
char buf[MAXPATHLEN];
if (data->fd < 0 || !data->lastkey || strcmp(key, data->lastkey)) {
if (data->lastkey) {
efree(data->lastkey);
data->lastkey = NULL;
}
ps_files_close(data);
if (!ps_files_valid_key(key)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'");
PS(invalid_session_id) = 1;
return;
}
if (!ps_files_path_create(buf, sizeof(buf), data, key)) {
return;
}
data->lastkey = estrdup(key);
data->fd = VCWD_OPEN_MODE(buf, O_CREAT | O_RDWR | O_BINARY, data->filemode);
if (data->fd != -1) {
#ifndef PHP_WIN32
/* check to make sure that the opened file is not a symlink, linking to data outside of allowable dirs */
if (PG(open_basedir)) {
struct stat sbuf;
if (fstat(data->fd, &sbuf)) {
close(data->fd);
return;
}
if (S_ISLNK(sbuf.st_mode) && php_check_open_basedir(buf TSRMLS_CC)) {
close(data->fd);
return;
}
}
#endif
flock(data->fd, LOCK_EX);
#ifdef F_SETFD
# ifndef FD_CLOEXEC
# define FD_CLOEXEC 1
# endif
if (fcntl(data->fd, F_SETFD, FD_CLOEXEC)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "fcntl(%d, F_SETFD, FD_CLOEXEC) failed: %s (%d)", data->fd, strerror(errno), errno);
}
#endif
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "open(%s, O_RDWR) failed: %s (%d)", buf, strerror(errno), errno);
}
}
}
static int ps_files_cleanup_dir(const char *dirname, int maxlifetime TSRMLS_DC)
{
DIR *dir;
char dentry[sizeof(struct dirent) + MAXPATHLEN];
struct dirent *entry = (struct dirent *) &dentry;
struct stat sbuf;
char buf[MAXPATHLEN];
time_t now;
int nrdels = 0;
size_t dirname_len;
dir = opendir(dirname);
if (!dir) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ps_files_cleanup_dir: opendir(%s) failed: %s (%d)", dirname, strerror(errno), errno);
return (0);
}
time(&now);
return (nrdels);
}
#define PS_FILES_DATA ps_files *data = PS_GET_MOD_DATA()
PS_OPEN_FUNC(files)
(now - sbuf.st_mtime) > maxlifetime) {
VCWD_UNLINK(buf);
nrdels++;
}
}
| 1 | CVE-2011-4718 | 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,967 |
Chrome | 761d65ebcac0cdb730fd27b87e207201ac38e3b4 | void ServiceWorkerPaymentInstrument::OnPaymentAppInvoked(
mojom::PaymentHandlerResponsePtr response) {
DCHECK(delegate_);
if (delegate_ != nullptr) {
delegate_->OnInstrumentDetailsReady(response->method_name,
response->stringified_details);
delegate_ = nullptr;
}
}
| 1 | CVE-2019-5828 | CWE-416 | Use After Free | The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
Phase: Architecture and Design
Strategy: Language Selection
Choose a language that provides automatic memory management.
Phase: Implementation
Strategy: Attack Surface Reduction
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.
Effectiveness: Defense in Depth
Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution. | 3,827 |
tcpdump | 9f0730bee3eb65d07b49fd468bc2f269173352fe | bittok2str_internal(register const struct tok *lp, register const char *fmt,
register u_int v, const char *sep)
{
static char buf[256]; /* our stringbuffer */
int buflen=0;
register u_int rotbit; /* this is the bit we rotate through all bitpositions */
register u_int tokval;
const char * sepstr = "";
while (lp != NULL && lp->s != NULL) {
tokval=lp->v; /* load our first value */
rotbit=1;
while (rotbit != 0) {
/*
* lets AND the rotating bit with our token value
* and see if we have got a match
*/
if (tokval == (v&rotbit)) {
/* ok we have found something */
buflen+=snprintf(buf+buflen, sizeof(buf)-buflen, "%s%s",
sepstr, lp->s);
sepstr = sep;
break;
}
rotbit=rotbit<<1; /* no match - lets shift and try again */
}
lp++;
}
if (buflen == 0)
/* bummer - lets print the "unknown" message as advised in the fmt string if we got one */
(void)snprintf(buf, sizeof(buf), fmt == NULL ? "#%08x" : fmt, v);
return (buf);
}
| 1 | CVE-2017-13011 | 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,757 |
tcpdump | c5dd7bef5e54da5996dc4713284aa6266ae75b75 | vtp_print (netdissect_options *ndo,
const u_char *pptr, u_int length)
{
int type, len, tlv_len, tlv_value, mgmtd_len;
const u_char *tptr;
const struct vtp_vlan_ *vtp_vlan;
if (length < VTP_HEADER_LEN)
goto trunc;
tptr = pptr;
ND_TCHECK2(*tptr, VTP_HEADER_LEN);
type = *(tptr+1);
ND_PRINT((ndo, "VTPv%u, Message %s (0x%02x), length %u",
*tptr,
tok2str(vtp_message_type_values,"Unknown message type", type),
type,
length));
/* In non-verbose mode, just print version and message type */
if (ndo->ndo_vflag < 1) {
return;
}
/* verbose mode print all fields */
ND_PRINT((ndo, "\n\tDomain name: "));
mgmtd_len = *(tptr + 3);
if (mgmtd_len < 1 || mgmtd_len > 32) {
ND_PRINT((ndo, " [invalid MgmtD Len %d]", mgmtd_len));
return;
}
fn_printzp(ndo, tptr + 4, mgmtd_len, NULL);
ND_PRINT((ndo, ", %s: %u",
tok2str(vtp_header_values, "Unknown", type),
*(tptr+2)));
tptr += VTP_HEADER_LEN;
switch (type) {
case VTP_SUMMARY_ADV:
/*
* SUMMARY ADVERTISEMENT
*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | Code | Followers | MgmtD Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Management Domain Name (zero-padded to 32 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Configuration revision number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Updater Identity IP address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Update Timestamp (12 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | MD5 digest (16 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
ND_TCHECK2(*tptr, 8);
ND_PRINT((ndo, "\n\t Config Rev %x, Updater %s",
EXTRACT_32BITS(tptr),
ipaddr_string(ndo, tptr+4)));
tptr += 8;
ND_TCHECK2(*tptr, VTP_UPDATE_TIMESTAMP_LEN);
ND_PRINT((ndo, ", Timestamp 0x%08x 0x%08x 0x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8)));
tptr += VTP_UPDATE_TIMESTAMP_LEN;
ND_TCHECK2(*tptr, VTP_MD5_DIGEST_LEN);
ND_PRINT((ndo, ", MD5 digest: %08x%08x%08x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
EXTRACT_32BITS(tptr + 12)));
tptr += VTP_MD5_DIGEST_LEN;
break;
case VTP_SUBSET_ADV:
/*
* SUBSET ADVERTISEMENT
*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | Code | Seq number | MgmtD Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Management Domain Name (zero-padded to 32 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Configuration revision number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | VLAN info field 1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ................ |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | VLAN info field N |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
ND_PRINT((ndo, ", Config Rev %x", EXTRACT_32BITS(tptr)));
/*
* VLAN INFORMATION
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | V info len | Status | VLAN type | VLAN name len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ISL vlan id | MTU size |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 802.10 index (SAID) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | VLAN name |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
tptr += 4;
while (tptr < (pptr+length)) {
len = *tptr;
if (len == 0)
break;
ND_TCHECK2(*tptr, len);
vtp_vlan = (const struct vtp_vlan_*)tptr;
ND_TCHECK(*vtp_vlan);
ND_PRINT((ndo, "\n\tVLAN info status %s, type %s, VLAN-id %u, MTU %u, SAID 0x%08x, Name ",
tok2str(vtp_vlan_status,"Unknown",vtp_vlan->status),
tok2str(vtp_vlan_type_values,"Unknown",vtp_vlan->type),
EXTRACT_16BITS(&vtp_vlan->vlanid),
EXTRACT_16BITS(&vtp_vlan->mtu),
EXTRACT_32BITS(&vtp_vlan->index)));
fn_printzp(ndo, tptr + VTP_VLAN_INFO_OFFSET, vtp_vlan->name_len, NULL);
/*
* Vlan names are aligned to 32-bit boundaries.
*/
len -= VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4);
tptr += VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4);
/* TLV information follows */
while (len > 0) {
/*
* Cisco specs says 2 bytes for type + 2 bytes for length, take only 1
* See: http://www.cisco.com/univercd/cc/td/doc/product/lan/trsrb/frames.htm
*/
type = *tptr;
tlv_len = *(tptr+1);
ND_PRINT((ndo, "\n\t\t%s (0x%04x) TLV",
tok2str(vtp_vlan_tlv_values, "Unknown", type),
type));
/*
* infinite loop check
*/
if (type == 0 || tlv_len == 0) {
return;
}
ND_TCHECK2(*tptr, tlv_len * 2 +2);
tlv_value = EXTRACT_16BITS(tptr+2);
switch (type) {
case VTP_VLAN_STE_HOP_COUNT:
ND_PRINT((ndo, ", %u", tlv_value));
break;
case VTP_VLAN_PRUNING:
ND_PRINT((ndo, ", %s (%u)",
tlv_value == 1 ? "Enabled" : "Disabled",
tlv_value));
break;
case VTP_VLAN_STP_TYPE:
ND_PRINT((ndo, ", %s (%u)",
tok2str(vtp_stp_type_values, "Unknown", tlv_value),
tlv_value));
break;
case VTP_VLAN_BRIDGE_TYPE:
ND_PRINT((ndo, ", %s (%u)",
tlv_value == 1 ? "SRB" : "SRT",
tlv_value));
break;
case VTP_VLAN_BACKUP_CRF_MODE:
ND_PRINT((ndo, ", %s (%u)",
tlv_value == 1 ? "Backup" : "Not backup",
tlv_value));
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case VTP_VLAN_SOURCE_ROUTING_RING_NUMBER:
case VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER:
case VTP_VLAN_PARENT_VLAN:
case VTP_VLAN_TRANS_BRIDGED_VLAN:
case VTP_VLAN_ARP_HOP_COUNT:
default:
print_unknown_data(ndo, tptr, "\n\t\t ", 2 + tlv_len*2);
break;
}
len -= 2 + tlv_len*2;
tptr += 2 + tlv_len*2;
}
}
break;
case VTP_ADV_REQUEST:
/*
* ADVERTISEMENT REQUEST
*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | Code | Reserved | MgmtD Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Management Domain Name (zero-padded to 32 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Start value |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\tStart value: %u", EXTRACT_32BITS(tptr)));
break;
case VTP_JOIN_MESSAGE:
/* FIXME - Could not find message format */
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "[|vtp]"));
}
| 1 | CVE-2017-13020 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 9,953 |
src | 3095060f479b86288e31c79ecbc5131a66bcd2f9 | ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)
{
struct session_state *state = ssh->state;
struct sshbuf *b = NULL;
int r;
const u_char *inblob, *outblob;
size_t inl, outl;
if ((r = sshbuf_froms(m, &b)) != 0)
goto out;
if ((r = sshbuf_get_string_direct(b, &inblob, &inl)) != 0 ||
(r = sshbuf_get_string_direct(b, &outblob, &outl)) != 0)
goto out;
if (inl == 0)
state->compression_in_started = 0;
else if (inl != sizeof(state->compression_in_stream)) {
r = SSH_ERR_INTERNAL_ERROR;
goto out;
} else {
state->compression_in_started = 1;
memcpy(&state->compression_in_stream, inblob, inl);
}
if (outl == 0)
state->compression_out_started = 0;
else if (outl != sizeof(state->compression_out_stream)) {
r = SSH_ERR_INTERNAL_ERROR;
goto out;
} else {
state->compression_out_started = 1;
memcpy(&state->compression_out_stream, outblob, outl);
}
r = 0;
out:
sshbuf_free(b);
return r;
}
| 1 | CVE-2016-10012 | 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,918 |
openssl | b19d8143212ae5fbc9cebfd51c01f802fabccd33 | int ssl3_get_client_hello(SSL *s)
{
int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
unsigned int cookie_len;
long n;
unsigned long id;
unsigned char *p, *d;
SSL_CIPHER *c;
#ifndef OPENSSL_NO_COMP
unsigned char *q;
SSL_COMP *comp = NULL;
#endif
STACK_OF(SSL_CIPHER) *ciphers = NULL;
if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
goto retry_cert;
/*
* We do this so that we will respond with our native type. If we are
* TLSv1 and we get SSLv3, we will respond with TLSv1, This down
* switching should be handled by a different method. If we are SSLv3, we
* will respond with SSLv3, even if prompted with TLSv1.
*/
if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
s->state = SSL3_ST_SR_CLNT_HELLO_B;
}
s->first_packet = 1;
n = s->method->ssl_get_message(s,
SSL3_ST_SR_CLNT_HELLO_B,
SSL3_ST_SR_CLNT_HELLO_C,
SSL3_MT_CLIENT_HELLO,
SSL3_RT_MAX_PLAIN_LENGTH, &ok);
if (!ok)
return ((int)n);
s->first_packet = 0;
d = p = (unsigned char *)s->init_msg;
/*
* use version from inside client hello, not from record header (may
* differ: see RFC 2246, Appendix E, second paragraph)
*/
s->client_version = (((int)p[0]) << 8) | (int)p[1];
p += 2;
if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
s->method->version != DTLS_ANY_VERSION)
: (s->client_version < s->version)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
!s->enc_write_ctx && !s->write_hash) {
/*
* similar to ssl3_get_record, send alert using remote version
* number
*/
s->version = s->client_version;
}
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
}
/*
* If we require cookies and this ClientHello doesn't contain one, just
* return since we do not want to allocate any memory yet. So check
* cookie length...
*/
if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
unsigned int session_length, cookie_length;
session_length = *(p + SSL3_RANDOM_SIZE);
cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
if (cookie_length == 0)
return 1;
}
/* load the client random */
memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
p += SSL3_RANDOM_SIZE;
/* get the session-id */
j = *(p++);
s->hit = 0;
/*
* Versions before 0.9.7 always allow clients to resume sessions in
* renegotiation. 0.9.7 and later allow this by default, but optionally
* ignore resumption requests with flag
* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
* than a change to default behavior so that applications relying on this
* for security won't even compile against older library versions).
* 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
* request renegotiation but not a new session (s->new_session remains
* unset): for servers, this essentially just means that the
* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored.
*/
if ((s->new_session
&& (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
if (!ssl_get_new_session(s, 1))
goto err;
} else {
i = ssl_get_prev_session(s, p, j, d + n);
/*
* Only resume if the session's version matches the negotiated
* version.
* RFC 5246 does not provide much useful advice on resumption
* with a different protocol version. It doesn't forbid it but
* the sanity of such behaviour would be questionable.
* In practice, clients do not accept a version mismatch and
* will abort the handshake with an error.
*/
if (i == 1 && s->version == s->session->ssl_version) { /* previous
* session */
s->hit = 1;
} else if (i == -1)
goto err;
else { /* i == 0 */
if (!ssl_get_new_session(s, 1))
goto err;
}
}
p += j;
if (SSL_IS_DTLS(s)) {
/* cookie stuff */
cookie_len = *(p++);
/*
* The ClientHello may contain a cookie even if the
* HelloVerify message has not been sent--make sure that it
* does not cause an overflow.
*/
if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
/* too much data */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
goto f_err;
}
/* verify the cookie if appropriate option is set. */
if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) {
memcpy(s->d1->rcvd_cookie, p, cookie_len);
if (s->ctx->app_verify_cookie_cb != NULL) {
if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
cookie_len) == 0) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_COOKIE_MISMATCH);
goto f_err;
}
/* else cookie verification succeeded */
}
/* default verification */
else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie,
s->d1->cookie_len) != 0) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
goto f_err;
}
/* Set to -2 so if successful we return 2 */
ret = -2;
}
p += cookie_len;
if (s->method->version == DTLS_ANY_VERSION) {
/* Select version to use */
if (s->client_version <= DTLS1_2_VERSION &&
!(s->options & SSL_OP_NO_DTLSv1_2)) {
s->version = DTLS1_2_VERSION;
s->method = DTLSv1_2_server_method();
} else if (tls1_suiteb(s)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
s->version = s->client_version;
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
} else if (s->client_version <= DTLS1_VERSION &&
!(s->options & SSL_OP_NO_DTLSv1)) {
s->version = DTLS1_VERSION;
s->method = DTLSv1_server_method();
} else {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_WRONG_VERSION_NUMBER);
s->version = s->client_version;
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
}
s->session->ssl_version = s->version;
}
}
n2s(p, i);
if ((i == 0) && (j != 0)) {
/* we need a cipher if we are not resuming a session */
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
goto f_err;
}
if ((p + i) >= (d + n)) {
/* not enough data */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
if ((i > 0) && (ssl_bytes_to_cipher_list(s, p, i, &(ciphers))
== NULL)) {
goto err;
}
p += i;
/* If it is a hit, check that the cipher is in the list */
if ((s->hit) && (i > 0)) {
j = 0;
id = s->session->cipher->id;
#ifdef CIPHER_DEBUG
fprintf(stderr, "client sent %d ciphers\n",
sk_SSL_CIPHER_num(ciphers));
#endif
for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
c = sk_SSL_CIPHER_value(ciphers, i);
#ifdef CIPHER_DEBUG
fprintf(stderr, "client [%2d of %2d]:%s\n",
i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
#endif
if (c->id == id) {
j = 1;
break;
}
}
/*
* Disabled because it can be used in a ciphersuite downgrade attack:
* CVE-2010-4180.
*/
#if 0
if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
&& (sk_SSL_CIPHER_num(ciphers) == 1)) {
/*
* Special case as client bug workaround: the previously used
* cipher may not be in the current list, the client instead
* might be trying to continue using a cipher that before wasn't
* chosen due to server preferences. We'll have to reject the
* connection if the cipher is not enabled, though.
*/
c = sk_SSL_CIPHER_value(ciphers, 0);
if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
s->session->cipher = c;
j = 1;
}
}
#endif
if (j == 0) {
/*
* we need to have the cipher in the cipher list if we are asked
* to reuse it
*/
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_REQUIRED_CIPHER_MISSING);
goto f_err;
}
}
/* compression */
i = *(p++);
if ((p + i) > (d + n)) {
/* not enough data */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
#ifndef OPENSSL_NO_COMP
q = p;
#endif
for (j = 0; j < i; j++) {
if (p[j] == 0)
break;
}
p += i;
if (j >= i) {
/* no compress */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
goto f_err;
}
#ifndef OPENSSL_NO_TLSEXT
/* TLS extensions */
if (s->version >= SSL3_VERSION) {
if (!ssl_parse_clienthello_tlsext(s, &p, d, n)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
goto err;
}
}
/*
* Check if we want to use external pre-shared secret for this handshake
* for not reused session only. We need to generate server_random before
* calling tls_session_secret_cb in order to allow SessionTicket
* processing to use it in key derivation.
*/
{
unsigned char *pos;
pos = s->s3->server_random;
if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
goto f_err;
}
}
if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
SSL_CIPHER *pref_cipher = NULL;
s->session->master_key_length = sizeof(s->session->master_key);
if (s->tls_session_secret_cb(s, s->session->master_key,
&s->session->master_key_length, ciphers,
&pref_cipher,
s->tls_session_secret_cb_arg)) {
s->hit = 1;
s->session->ciphers = ciphers;
s->session->verify_result = X509_V_OK;
ciphers = NULL;
/* check if some cipher was preferred by call back */
pref_cipher =
pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
s->
session->ciphers,
SSL_get_ciphers
(s));
if (pref_cipher == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
goto f_err;
}
s->session->cipher = pref_cipher;
if (s->cipher_list)
sk_SSL_CIPHER_free(s->cipher_list);
if (s->cipher_list_by_id)
sk_SSL_CIPHER_free(s->cipher_list_by_id);
s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
}
}
#endif
/*
* Worst case, we will use the NULL compression, but if we have other
* options, we will now look for them. We have i-1 compression
* algorithms from the client, starting at q.
*/
s->s3->tmp.new_compression = NULL;
#ifndef OPENSSL_NO_COMP
/* This only happens if we have a cache hit */
if (s->session->compress_meth != 0) {
int m, comp_id = s->session->compress_meth;
/* Perform sanity checks on resumed compression algorithm */
/* Can't disable compression */
if (s->options & SSL_OP_NO_COMPRESSION) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_INCONSISTENT_COMPRESSION);
goto f_err;
}
/* Look for resumed compression method */
for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
if (comp_id == comp->id) {
s->s3->tmp.new_compression = comp;
break;
}
}
if (s->s3->tmp.new_compression == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_INVALID_COMPRESSION_ALGORITHM);
goto f_err;
}
/* Look for resumed method in compression list */
for (m = 0; m < i; m++) {
if (q[m] == comp_id)
break;
}
if (m >= i) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
goto f_err;
}
} else if (s->hit)
comp = NULL;
else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) {
/* See if we have a match */
int m, nn, o, v, done = 0;
nn = sk_SSL_COMP_num(s->ctx->comp_methods);
for (m = 0; m < nn; m++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
v = comp->id;
for (o = 0; o < i; o++) {
if (v == q[o]) {
done = 1;
break;
}
}
if (done)
break;
}
if (done)
s->s3->tmp.new_compression = comp;
else
comp = NULL;
}
#else
/*
* If compression is disabled we'd better not try to resume a session
* using compression.
*/
if (s->session->compress_meth != 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
goto f_err;
}
#endif
/*
* Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
*/
if (!s->hit) {
#ifdef OPENSSL_NO_COMP
s->session->compress_meth = 0;
#else
s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
#endif
if (s->session->ciphers != NULL)
sk_SSL_CIPHER_free(s->session->ciphers);
s->session->ciphers = ciphers;
if (ciphers == NULL) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_PASSED);
goto f_err;
}
ciphers = NULL;
if (!tls1_set_server_sigalgs(s)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
goto err;
}
/* Let cert callback update server certificates if required */
retry_cert:
if (s->cert->cert_cb) {
int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
if (rv == 0) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
goto f_err;
}
if (rv < 0) {
s->rwstate = SSL_X509_LOOKUP;
return -1;
}
s->rwstate = SSL_NOTHING;
}
c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
if (c == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
goto f_err;
}
s->s3->tmp.new_cipher = c;
} else {
/* Session-id reuse */
#ifdef REUSE_CIPHER_BUG
STACK_OF(SSL_CIPHER) *sk;
SSL_CIPHER *nc = NULL;
SSL_CIPHER *ec = NULL;
if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) {
sk = s->session->ciphers;
for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
c = sk_SSL_CIPHER_value(sk, i);
if (c->algorithm_enc & SSL_eNULL)
nc = c;
if (SSL_C_IS_EXPORT(c))
ec = c;
}
if (nc != NULL)
s->s3->tmp.new_cipher = nc;
else if (ec != NULL)
s->s3->tmp.new_cipher = ec;
else
s->s3->tmp.new_cipher = s->session->cipher;
} else
#endif
s->s3->tmp.new_cipher = s->session->cipher;
}
if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
if (!ssl3_digest_cached_records(s))
goto f_err;
}
/*-
* we now have the following setup.
* client_random
* cipher_list - our prefered list of ciphers
* ciphers - the clients prefered list of ciphers
* compression - basically ignored right now
* ssl version is set - sslv3
* s->session - The ssl session has been setup.
* s->hit - session reuse flag
* s->tmp.new_cipher - the new cipher to use.
*/
/* Handles TLS extensions that we couldn't check earlier */
if (s->version >= SSL3_VERSION) {
if (ssl_check_clienthello_tlsext_late(s) <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
goto err;
}
}
if (ret < 0)
ret = -ret;
if (0) {
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
}
err:
if (ciphers != NULL)
sk_SSL_CIPHER_free(ciphers);
return ret < 0 ? -1 : ret;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,031 |
php-src | 523f230c831d7b33353203fa34aee4e92ac12bba | php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper,
const char *path, const char *mode, int options, char **opened_path,
php_stream_context *context, int redirect_max, int flags STREAMS_DC TSRMLS_DC) /* {{{ */
{
php_stream *stream = NULL;
php_url *resource = NULL;
int use_ssl;
int use_proxy = 0;
char *scratch = NULL;
char *tmp = NULL;
char *ua_str = NULL;
zval **ua_zval = NULL, **tmpzval = NULL, *ssl_proxy_peer_name = NULL;
int scratch_len = 0;
int body = 0;
char location[HTTP_HEADER_BLOCK_SIZE];
zval *response_header = NULL;
int reqok = 0;
char *http_header_line = NULL;
char tmp_line[128];
size_t chunk_size = 0, file_size = 0;
int eol_detect = 0;
char *transport_string, *errstr = NULL;
int transport_len, have_header = 0, request_fulluri = 0, ignore_errors = 0;
char *protocol_version = NULL;
int protocol_version_len = 3; /* Default: "1.0" */
struct timeval timeout;
char *user_headers = NULL;
int header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0);
int redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0);
int follow_location = 1;
php_stream_filter *transfer_encoding = NULL;
int response_code;
tmp_line[0] = '\0';
if (redirect_max < 1) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Redirection limit reached, aborting");
return NULL;
}
resource = php_url_parse(path);
if (resource == NULL) {
return NULL;
}
if (strncasecmp(resource->scheme, "http", sizeof("http")) && strncasecmp(resource->scheme, "https", sizeof("https"))) {
if (!context ||
php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == FAILURE ||
Z_TYPE_PP(tmpzval) != IS_STRING ||
Z_STRLEN_PP(tmpzval) <= 0) {
php_url_free(resource);
return php_stream_open_wrapper_ex(path, mode, REPORT_ERRORS, NULL, context);
}
/* Called from a non-http wrapper with http proxying requested (i.e. ftp) */
request_fulluri = 1;
use_ssl = 0;
use_proxy = 1;
transport_len = Z_STRLEN_PP(tmpzval);
transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
} else {
/* Normal http request (possibly with proxy) */
if (strpbrk(mode, "awx+")) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections");
php_url_free(resource);
return NULL;
}
use_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's';
/* choose default ports */
if (use_ssl && resource->port == 0)
resource->port = 443;
else if (resource->port == 0)
resource->port = 80;
if (context &&
php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == SUCCESS &&
Z_TYPE_PP(tmpzval) == IS_STRING &&
Z_STRLEN_PP(tmpzval) > 0) {
use_proxy = 1;
transport_len = Z_STRLEN_PP(tmpzval);
transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
} else {
transport_len = spprintf(&transport_string, 0, "%s://%s:%d", use_ssl ? "ssl" : "tcp", resource->host, resource->port);
}
}
if (context && php_stream_context_get_option(context, wrapper->wops->label, "timeout", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_double_ex(tmpzval);
timeout.tv_sec = (time_t) Z_DVAL_PP(tmpzval);
timeout.tv_usec = (size_t) ((Z_DVAL_PP(tmpzval) - timeout.tv_sec) * 1000000);
} else {
timeout.tv_sec = FG(default_socket_timeout);
timeout.tv_usec = 0;
}
stream = php_stream_xport_create(transport_string, transport_len, options,
STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT,
NULL, &timeout, context, &errstr, NULL);
if (stream) {
php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout);
}
if (errstr) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "%s", errstr);
efree(errstr);
errstr = NULL;
}
efree(transport_string);
if (stream && use_proxy && use_ssl) {
smart_str header = {0};
/* Set peer_name or name verification will try to use the proxy server name */
if (!context || php_stream_context_get_option(context, "ssl", "peer_name", &tmpzval) == FAILURE) {
MAKE_STD_ZVAL(ssl_proxy_peer_name);
ZVAL_STRING(ssl_proxy_peer_name, resource->host, 1);
php_stream_context_set_option(stream->context, "ssl", "peer_name", ssl_proxy_peer_name);
}
smart_str_appendl(&header, "CONNECT ", sizeof("CONNECT ")-1);
smart_str_appends(&header, resource->host);
smart_str_appendc(&header, ':');
smart_str_append_unsigned(&header, resource->port);
smart_str_appendl(&header, " HTTP/1.0\r\n", sizeof(" HTTP/1.0\r\n")-1);
/* check if we have Proxy-Authorization header */
if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) {
char *s, *p;
if (Z_TYPE_PP(tmpzval) == IS_ARRAY) {
HashPosition pos;
zval **tmpheader = NULL;
for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos);
SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos);
zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)) {
if (Z_TYPE_PP(tmpheader) == IS_STRING) {
s = Z_STRVAL_PP(tmpheader);
do {
while (*s == ' ' || *s == '\t') s++;
p = s;
while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++;
if (*p == ':') {
p++;
if (p - s == sizeof("Proxy-Authorization:") - 1 &&
zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1,
"Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) {
while (*p != 0 && *p != '\r' && *p !='\n') p++;
smart_str_appendl(&header, s, p - s);
smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1);
goto finish;
} else {
while (*p != 0 && *p != '\r' && *p !='\n') p++;
}
}
s = p;
while (*s == '\r' || *s == '\n') s++;
} while (*s != 0);
}
}
} else if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) {
s = Z_STRVAL_PP(tmpzval);
do {
while (*s == ' ' || *s == '\t') s++;
p = s;
while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++;
if (*p == ':') {
p++;
if (p - s == sizeof("Proxy-Authorization:") - 1 &&
zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1,
"Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) {
while (*p != 0 && *p != '\r' && *p !='\n') p++;
smart_str_appendl(&header, s, p - s);
smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1);
goto finish;
} else {
while (*p != 0 && *p != '\r' && *p !='\n') p++;
}
}
s = p;
while (*s == '\r' || *s == '\n') s++;
} while (*s != 0);
}
}
finish:
smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1);
if (php_stream_write(stream, header.c, header.len) != header.len) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy");
php_stream_close(stream);
stream = NULL;
}
smart_str_free(&header);
if (stream) {
char header_line[HTTP_HEADER_BLOCK_SIZE];
/* get response header */
while (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL) {
if (header_line[0] == '\n' ||
header_line[0] == '\r' ||
header_line[0] == '\0') {
break;
}
}
}
/* enable SSL transport layer */
if (stream) {
if (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, NULL TSRMLS_CC) < 0 ||
php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy");
php_stream_close(stream);
stream = NULL;
}
}
}
if (stream == NULL)
goto out;
/* avoid buffering issues while reading header */
if (options & STREAM_WILL_CAST)
chunk_size = php_stream_set_chunk_size(stream, 1);
/* avoid problems with auto-detecting when reading the headers -> the headers
* are always in canonical \r\n format */
eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);
stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);
php_stream_context_set(stream, context);
php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0);
if (header_init && context && php_stream_context_get_option(context, "http", "max_redirects", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_long_ex(tmpzval);
redirect_max = Z_LVAL_PP(tmpzval);
}
if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) {
if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {
/* As per the RFC, automatically redirected requests MUST NOT use other methods than
* GET and HEAD unless it can be confirmed by the user */
if (!redirected
|| (Z_STRLEN_PP(tmpzval) == 3 && memcmp("GET", Z_STRVAL_PP(tmpzval), 3) == 0)
|| (Z_STRLEN_PP(tmpzval) == 4 && memcmp("HEAD",Z_STRVAL_PP(tmpzval), 4) == 0)
) {
scratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval);
scratch = emalloc(scratch_len);
strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1);
strncat(scratch, " ", 1);
}
}
}
if (context && php_stream_context_get_option(context, "http", "protocol_version", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_double_ex(tmpzval);
protocol_version_len = spprintf(&protocol_version, 0, "%.1F", Z_DVAL_PP(tmpzval));
}
if (!scratch) {
scratch_len = strlen(path) + 29 + protocol_version_len;
scratch = emalloc(scratch_len);
strncpy(scratch, "GET ", scratch_len);
}
/* Should we send the entire path in the request line, default to no. */
if (!request_fulluri &&
context &&
php_stream_context_get_option(context, "http", "request_fulluri", &tmpzval) == SUCCESS) {
zval ztmp = **tmpzval;
zval_copy_ctor(&ztmp);
convert_to_boolean(&ztmp);
request_fulluri = Z_BVAL(ztmp) ? 1 : 0;
zval_dtor(&ztmp);
}
if (request_fulluri) {
/* Ask for everything */
strcat(scratch, path);
} else {
/* Send the traditional /path/to/file?query_string */
/* file */
if (resource->path && *resource->path) {
strlcat(scratch, resource->path, scratch_len);
} else {
strlcat(scratch, "/", scratch_len);
}
/* query string */
if (resource->query) {
strlcat(scratch, "?", scratch_len);
strlcat(scratch, resource->query, scratch_len);
}
}
/* protocol version we are speaking */
if (protocol_version) {
strlcat(scratch, " HTTP/", scratch_len);
strlcat(scratch, protocol_version, scratch_len);
strlcat(scratch, "\r\n", scratch_len);
} else {
strlcat(scratch, " HTTP/1.0\r\n", scratch_len);
}
/* send it */
php_stream_write(stream, scratch, strlen(scratch));
if (context && php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS) {
tmp = NULL;
if (Z_TYPE_PP(tmpzval) == IS_ARRAY) {
HashPosition pos;
zval **tmpheader = NULL;
smart_str tmpstr = {0};
for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(tmpzval), &pos);
SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(tmpzval), (void *)&tmpheader, &pos);
zend_hash_move_forward_ex(Z_ARRVAL_PP(tmpzval), &pos)
) {
if (Z_TYPE_PP(tmpheader) == IS_STRING) {
smart_str_appendl(&tmpstr, Z_STRVAL_PP(tmpheader), Z_STRLEN_PP(tmpheader));
smart_str_appendl(&tmpstr, "\r\n", sizeof("\r\n") - 1);
}
}
smart_str_0(&tmpstr);
/* Remove newlines and spaces from start and end. there's at least one extra \r\n at the end that needs to go. */
if (tmpstr.c) {
tmp = php_trim(tmpstr.c, strlen(tmpstr.c), NULL, 0, NULL, 3 TSRMLS_CC);
smart_str_free(&tmpstr);
}
}
if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) {
/* Remove newlines and spaces from start and end php_trim will estrndup() */
tmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC);
}
if (tmp && strlen(tmp) > 0) {
char *s;
user_headers = estrdup(tmp);
/* Make lowercase for easy comparison against 'standard' headers */
php_strtolower(tmp, strlen(tmp));
if (!header_init) {
/* strip POST headers on redirect */
strip_header(user_headers, tmp, "content-length:");
strip_header(user_headers, tmp, "content-type:");
}
if ((s = strstr(tmp, "user-agent:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_USER_AGENT;
}
if ((s = strstr(tmp, "host:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_HOST;
}
if ((s = strstr(tmp, "from:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_FROM;
}
if ((s = strstr(tmp, "authorization:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_AUTH;
}
if ((s = strstr(tmp, "content-length:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_CONTENT_LENGTH;
}
if ((s = strstr(tmp, "content-type:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_TYPE;
}
if ((s = strstr(tmp, "connection:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
have_header |= HTTP_HEADER_CONNECTION;
}
/* remove Proxy-Authorization header */
if (use_proxy && use_ssl && (s = strstr(tmp, "proxy-authorization:")) &&
(s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
*(s-1) == '\t' || *(s-1) == ' ')) {
char *p = s + sizeof("proxy-authorization:") - 1;
while (s > tmp && (*(s-1) == ' ' || *(s-1) == '\t')) s--;
while (*p != 0 && *p != '\r' && *p != '\n') p++;
while (*p == '\r' || *p == '\n') p++;
if (*p == 0) {
if (s == tmp) {
efree(user_headers);
user_headers = NULL;
} else {
while (s > tmp && (*(s-1) == '\r' || *(s-1) == '\n')) s--;
user_headers[s - tmp] = 0;
}
} else {
memmove(user_headers + (s - tmp), user_headers + (p - tmp), strlen(p) + 1);
}
}
}
if (tmp) {
efree(tmp);
}
}
/* auth header if it was specified */
if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user) {
/* decode the strings first */
php_url_decode(resource->user, strlen(resource->user));
/* scratch is large enough, since it was made large enough for the whole URL */
strcpy(scratch, resource->user);
strcat(scratch, ":");
/* Note: password is optional! */
if (resource->pass) {
php_url_decode(resource->pass, strlen(resource->pass));
strcat(scratch, resource->pass);
}
tmp = (char*)php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL);
if (snprintf(scratch, scratch_len, "Authorization: Basic %s\r\n", tmp) > 0) {
php_stream_write(stream, scratch, strlen(scratch));
php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0);
}
efree(tmp);
tmp = NULL;
}
/* if the user has configured who they are, send a From: line */
if (((have_header & HTTP_HEADER_FROM) == 0) && FG(from_address)) {
if (snprintf(scratch, scratch_len, "From: %s\r\n", FG(from_address)) > 0)
php_stream_write(stream, scratch, strlen(scratch));
}
/* Send Host: header so name-based virtual hosts work */
if ((have_header & HTTP_HEADER_HOST) == 0) {
if ((use_ssl && resource->port != 443 && resource->port != 0) ||
(!use_ssl && resource->port != 80 && resource->port != 0)) {
if (snprintf(scratch, scratch_len, "Host: %s:%i\r\n", resource->host, resource->port) > 0)
php_stream_write(stream, scratch, strlen(scratch));
} else {
if (snprintf(scratch, scratch_len, "Host: %s\r\n", resource->host) > 0) {
php_stream_write(stream, scratch, strlen(scratch));
}
}
}
/* Send a Connection: close header to avoid hanging when the server
* interprets the RFC literally and establishes a keep-alive connection,
* unless the user specifically requests something else by specifying a
* Connection header in the context options. Send that header even for
* HTTP/1.0 to avoid issues when the server respond with a HTTP/1.1
* keep-alive response, which is the preferred response type. */
if ((have_header & HTTP_HEADER_CONNECTION) == 0) {
php_stream_write_string(stream, "Connection: close\r\n");
}
if (context &&
php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS &&
Z_TYPE_PP(ua_zval) == IS_STRING) {
ua_str = Z_STRVAL_PP(ua_zval);
} else if (FG(user_agent)) {
ua_str = FG(user_agent);
}
if (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) {
#define _UA_HEADER "User-Agent: %s\r\n"
char *ua;
size_t ua_len;
ua_len = sizeof(_UA_HEADER) + strlen(ua_str);
/* ensure the header is only sent if user_agent is not blank */
if (ua_len > sizeof(_UA_HEADER)) {
ua = emalloc(ua_len + 1);
if ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) {
ua[ua_len] = 0;
php_stream_write(stream, ua, ua_len);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot construct User-agent header");
}
if (ua) {
efree(ua);
}
}
}
if (user_headers) {
/* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST
* see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first.
*/
if (
header_init &&
context &&
!(have_header & HTTP_HEADER_CONTENT_LENGTH) &&
php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS &&
Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0
) {
scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval));
php_stream_write(stream, scratch, scratch_len);
have_header |= HTTP_HEADER_CONTENT_LENGTH;
}
php_stream_write(stream, user_headers, strlen(user_headers));
php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
efree(user_headers);
}
/* Request content, such as for POST requests */
if (header_init && context &&
php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS &&
Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {
if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) {
scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval));
php_stream_write(stream, scratch, scratch_len);
}
if (!(have_header & HTTP_HEADER_TYPE)) {
php_stream_write(stream, "Content-Type: application/x-www-form-urlencoded\r\n",
sizeof("Content-Type: application/x-www-form-urlencoded\r\n") - 1);
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Content-type not specified assuming application/x-www-form-urlencoded");
}
php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
php_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
} else {
php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
}
location[0] = '\0';
if (!EG(active_symbol_table)) {
zend_rebuild_symbol_table(TSRMLS_C);
}
if (header_init) {
zval *ztmp;
MAKE_STD_ZVAL(ztmp);
array_init(ztmp);
ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", ztmp);
}
{
zval **rh;
if(zend_hash_find(EG(active_symbol_table), "http_response_header", sizeof("http_response_header"), (void **) &rh) != SUCCESS || Z_TYPE_PP(rh) != IS_ARRAY) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, http_response_header overwritten");
goto out;
}
response_header = *rh;
Z_ADDREF_P(response_header);
}
if (!php_stream_eof(stream)) {
size_t tmp_line_len;
/* get response header */
if (php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) {
zval *http_response;
if (tmp_line_len > 9) {
response_code = atoi(tmp_line + 9);
} else {
response_code = 0;
}
if (context && SUCCESS==php_stream_context_get_option(context, "http", "ignore_errors", &tmpzval)) {
ignore_errors = zend_is_true(*tmpzval);
}
/* when we request only the header, don't fail even on error codes */
if ((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) {
reqok = 1;
}
/* status codes of 1xx are "informational", and will be followed by a real response
* e.g "100 Continue". RFC 7231 states that unexpected 1xx status MUST be parsed,
* and MAY be ignored. As such, we need to skip ahead to the "real" status*/
if (response_code >= 100 && response_code < 200) {
/* consume lines until we find a line starting 'HTTP/1' */
while (
!php_stream_eof(stream)
&& php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL
&& ( tmp_line_len < sizeof("HTTP/1") - 1 || strncasecmp(tmp_line, "HTTP/1", sizeof("HTTP/1") - 1) )
);
if (tmp_line_len > 9) {
response_code = atoi(tmp_line + 9);
} else {
response_code = 0;
}
}
/* all status codes in the 2xx range are defined by the specification as successful;
* all status codes in the 3xx range are for redirection, and so also should never
* fail */
if (response_code >= 200 && response_code < 400) {
reqok = 1;
} else {
switch(response_code) {
case 403:
php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT,
tmp_line, response_code);
break;
default:
/* safety net in the event tmp_line == NULL */
if (!tmp_line_len) {
tmp_line[0] = '\0';
}
php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE,
tmp_line, response_code);
}
}
if (tmp_line_len >= 1 && tmp_line[tmp_line_len - 1] == '\n') {
--tmp_line_len;
if (tmp_line_len >= 1 &&tmp_line[tmp_line_len - 1] == '\r') {
--tmp_line_len;
}
}
MAKE_STD_ZVAL(http_response);
ZVAL_STRINGL(http_response, tmp_line, tmp_line_len, 1);
zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL);
}
} else {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, unexpected end of socket!");
goto out;
}
/* read past HTTP headers */
http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE);
while (!body && !php_stream_eof(stream)) {
size_t http_header_line_length;
if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\n' && *http_header_line != '\r') {
char *e = http_header_line + http_header_line_length - 1;
if (*e != '\n') {
do { /* partial header */
if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) == NULL) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Failed to read HTTP headers");
goto out;
}
e = http_header_line + http_header_line_length - 1;
} while (*e != '\n');
continue;
}
while (*e == '\n' || *e == '\r') {
e--;
}
http_header_line_length = e - http_header_line + 1;
http_header_line[http_header_line_length] = '\0';
if (!strncasecmp(http_header_line, "Location: ", 10)) {
if (context && php_stream_context_get_option(context, "http", "follow_location", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_long_ex(tmpzval);
follow_location = Z_LVAL_PP(tmpzval);
} else if (!(response_code >= 300 && response_code < 304 || 307 == response_code || 308 == response_code)) {
/* we shouldn't redirect automatically
if follow_location isn't set and response_code not in (300, 301, 302, 303 and 307)
see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1
RFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */
follow_location = 0;
}
strlcpy(location, http_header_line + 10, sizeof(location));
} else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) {
php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0);
} else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) {
file_size = atoi(http_header_line + 16);
php_stream_notify_file_size(context, file_size, http_header_line, 0);
} else if (!strncasecmp(http_header_line, "Transfer-Encoding: chunked", sizeof("Transfer-Encoding: chunked"))) {
/* create filter to decode response body */
if (!(options & STREAM_ONLY_GET_HEADERS)) {
long decode = 1;
if (context && php_stream_context_get_option(context, "http", "auto_decode", &tmpzval) == SUCCESS) {
SEPARATE_ZVAL(tmpzval);
convert_to_boolean(*tmpzval);
decode = Z_LVAL_PP(tmpzval);
}
if (decode) {
transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream) TSRMLS_CC);
if (transfer_encoding) {
/* don't store transfer-encodeing header */
continue;
}
}
}
}
if (http_header_line[0] == '\0') {
body = 1;
} else {
zval *http_header;
MAKE_STD_ZVAL(http_header);
ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1);
zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL);
}
} else {
break;
}
}
if (!reqok || (location[0] != '\0' && follow_location)) {
if (!follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) {
goto out;
}
if (location[0] != '\0')
php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0);
php_stream_close(stream);
stream = NULL;
if (location[0] != '\0') {
char new_path[HTTP_HEADER_BLOCK_SIZE];
char loc_path[HTTP_HEADER_BLOCK_SIZE];
*new_path='\0';
if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) &&
strncasecmp(location, "https://", sizeof("https://")-1) &&
strncasecmp(location, "ftp://", sizeof("ftp://")-1) &&
strncasecmp(location, "ftps://", sizeof("ftps://")-1)))
{
if (*location != '/') {
if (*(location+1) != '\0' && resource->path) {
char *s = strrchr(resource->path, '/');
if (!s) {
s = resource->path;
if (!s[0]) {
efree(s);
s = resource->path = estrdup("/");
} else {
*s = '/';
}
}
s[1] = '\0';
if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') {
snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location);
} else {
snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location);
}
} else {
snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location);
}
} else {
strlcpy(loc_path, location, sizeof(loc_path));
}
if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) {
snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path);
} else {
snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path);
}
} else {
strlcpy(new_path, location, sizeof(new_path));
}
php_url_free(resource);
/* check for invalid redirection URLs */
if ((resource = php_url_parse(new_path)) == NULL) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path);
goto out;
}
#define CHECK_FOR_CNTRL_CHARS(val) { \
if (val) { \
unsigned char *s, *e; \
int l; \
l = php_url_decode(val, strlen(val)); \
s = (unsigned char*)val; e = s + l; \
while (s < e) { \
if (iscntrl(*s)) { \
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); \
goto out; \
} \
s++; \
} \
} \
}
/* check for control characters in login, password & path */
if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) {
CHECK_FOR_CNTRL_CHARS(resource->user)
CHECK_FOR_CNTRL_CHARS(resource->pass)
CHECK_FOR_CNTRL_CHARS(resource->path)
}
stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, HTTP_WRAPPER_REDIRECTED STREAMS_CC TSRMLS_CC);
} else {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed! %s", tmp_line);
}
}
out:
if (protocol_version) {
efree(protocol_version);
}
if (http_header_line) {
efree(http_header_line);
}
if (scratch) {
efree(scratch);
}
if (resource) {
php_url_free(resource);
}
if (stream) {
if (header_init) {
stream->wrapperdata = response_header;
} else {
if(response_header) {
Z_DELREF_P(response_header);
}
}
php_stream_notify_progress_init(context, 0, file_size);
/* Restore original chunk size now that we're done with headers */
if (options & STREAM_WILL_CAST)
php_stream_set_chunk_size(stream, chunk_size);
/* restore the users auto-detect-line-endings setting */
stream->flags |= eol_detect;
/* as far as streams are concerned, we are now at the start of
* the stream */
stream->position = 0;
/* restore mode */
strlcpy(stream->mode, mode, sizeof(stream->mode));
if (transfer_encoding) {
php_stream_filter_append(&stream->readfilters, transfer_encoding);
}
} else {
if(response_header) {
Z_DELREF_P(response_header);
}
if (transfer_encoding) {
php_stream_filter_free(transfer_encoding TSRMLS_CC);
}
}
return stream;
}
/* }}} */
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,896 |
linux | dea37a97265588da604c6ba80160a287b72c7bfd | static int __init cpia2_init(void)
{
LOG("%s v%s\n",
ABOUT, CPIA_VERSION);
check_parameters();
cpia2_usb_init();
return 0;
} | 1 | CVE-2019-19966 | 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,150 |
libxslt | 7ca19df892ca22d9314e95d59ce2abdeff46b617 | xsltCheckParentElement(xsltStylesheetPtr style, xmlNodePtr inst,
const xmlChar *allow1, const xmlChar *allow2) {
xmlNodePtr parent;
if ((style == NULL) || (inst == NULL) || (inst->ns == NULL) ||
(style->literal_result))
return;
parent = inst->parent;
if (parent == NULL) {
xsltTransformError(NULL, style, inst,
"internal problem: element has no parent\n");
style->errors++;
return;
}
if (((parent->ns == inst->ns) ||
((parent->ns != NULL) &&
(xmlStrEqual(parent->ns->href, inst->ns->href)))) &&
((xmlStrEqual(parent->name, allow1)) ||
(xmlStrEqual(parent->name, allow2)))) {
return;
}
if (style->extInfos != NULL) {
while ((parent != NULL) && (parent->type != XML_DOCUMENT_NODE)) {
/*
* if we are within an extension element all bets are off
* about the semantic there e.g. xsl:param within func:function
*/
if ((parent->ns != NULL) &&
(xmlHashLookup(style->extInfos, parent->ns->href) != NULL))
return;
parent = parent->parent;
}
}
xsltTransformError(NULL, style, inst,
"element %s is not allowed within that context\n",
inst->name);
style->errors++;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,270 |
linux | afca6c5b2595fc44383919fba740c194b0b76aff | xfs_iget_cache_miss(
struct xfs_mount *mp,
struct xfs_perag *pag,
xfs_trans_t *tp,
xfs_ino_t ino,
struct xfs_inode **ipp,
int flags,
int lock_flags)
{
struct xfs_inode *ip;
int error;
xfs_agino_t agino = XFS_INO_TO_AGINO(mp, ino);
int iflags;
ip = xfs_inode_alloc(mp, ino);
if (!ip)
return -ENOMEM;
error = xfs_iread(mp, tp, ip, flags);
if (error)
goto out_destroy;
if (!xfs_inode_verify_forks(ip)) {
error = -EFSCORRUPTED;
goto out_destroy;
}
trace_xfs_iget_miss(ip);
/*
* If we are allocating a new inode, then check what was returned is
* actually a free, empty inode. If we are not allocating an inode,
* the check we didn't find a free inode.
*/
if (flags & XFS_IGET_CREATE) {
if (VFS_I(ip)->i_mode != 0) {
xfs_warn(mp,
"Corruption detected! Free inode 0x%llx not marked free on disk",
ino);
error = -EFSCORRUPTED;
goto out_destroy;
}
if (ip->i_d.di_nblocks != 0) {
xfs_warn(mp,
"Corruption detected! Free inode 0x%llx has blocks allocated!",
ino);
error = -EFSCORRUPTED;
goto out_destroy;
}
} else if (VFS_I(ip)->i_mode == 0) {
error = -ENOENT;
goto out_destroy;
}
/*
* Preload the radix tree so we can insert safely under the
* write spinlock. Note that we cannot sleep inside the preload
* region. Since we can be called from transaction context, don't
* recurse into the file system.
*/
if (radix_tree_preload(GFP_NOFS)) {
error = -EAGAIN;
goto out_destroy;
}
/*
* Because the inode hasn't been added to the radix-tree yet it can't
* be found by another thread, so we can do the non-sleeping lock here.
*/
if (lock_flags) {
if (!xfs_ilock_nowait(ip, lock_flags))
BUG();
}
/*
* These values must be set before inserting the inode into the radix
* tree as the moment it is inserted a concurrent lookup (allowed by the
* RCU locking mechanism) can find it and that lookup must see that this
* is an inode currently under construction (i.e. that XFS_INEW is set).
* The ip->i_flags_lock that protects the XFS_INEW flag forms the
* memory barrier that ensures this detection works correctly at lookup
* time.
*/
iflags = XFS_INEW;
if (flags & XFS_IGET_DONTCACHE)
iflags |= XFS_IDONTCACHE;
ip->i_udquot = NULL;
ip->i_gdquot = NULL;
ip->i_pdquot = NULL;
xfs_iflags_set(ip, iflags);
/* insert the new inode */
spin_lock(&pag->pag_ici_lock);
error = radix_tree_insert(&pag->pag_ici_root, agino, ip);
if (unlikely(error)) {
WARN_ON(error != -EEXIST);
XFS_STATS_INC(mp, xs_ig_dup);
error = -EAGAIN;
goto out_preload_end;
}
spin_unlock(&pag->pag_ici_lock);
radix_tree_preload_end();
*ipp = ip;
return 0;
out_preload_end:
spin_unlock(&pag->pag_ici_lock);
radix_tree_preload_end();
if (lock_flags)
xfs_iunlock(ip, lock_flags);
out_destroy:
__destroy_inode(VFS_I(ip));
xfs_inode_free(ip);
return error;
}
| 1 | CVE-2018-13093 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 5,307 |
linux-2.6 | 8a47077a0b5aa2649751c46e7a27884e6686ccbf | static int rsvp_dump(struct tcf_proto *tp, unsigned long fh,
struct sk_buff *skb, struct tcmsg *t)
{
struct rsvp_filter *f = (struct rsvp_filter*)fh;
struct rsvp_session *s;
unsigned char *b = skb->tail;
struct rtattr *rta;
struct tc_rsvp_pinfo pinfo;
if (f == NULL)
return skb->len;
s = f->sess;
t->tcm_handle = f->handle;
rta = (struct rtattr*)b;
RTA_PUT(skb, TCA_OPTIONS, 0, NULL);
RTA_PUT(skb, TCA_RSVP_DST, sizeof(s->dst), &s->dst);
pinfo.dpi = s->dpi;
pinfo.spi = f->spi;
pinfo.protocol = s->protocol;
pinfo.tunnelid = s->tunnelid;
pinfo.tunnelhdr = f->tunnelhdr;
RTA_PUT(skb, TCA_RSVP_PINFO, sizeof(pinfo), &pinfo);
if (f->res.classid)
RTA_PUT(skb, TCA_RSVP_CLASSID, 4, &f->res.classid);
if (((f->handle>>8)&0xFF) != 16)
RTA_PUT(skb, TCA_RSVP_SRC, sizeof(f->src), f->src);
if (tcf_exts_dump(skb, &f->exts, &rsvp_ext_map) < 0)
goto rtattr_failure;
rta->rta_len = skb->tail - b;
if (tcf_exts_dump_stats(skb, &f->exts, &rsvp_ext_map) < 0)
goto rtattr_failure;
return skb->len;
rtattr_failure:
skb_trim(skb, b - skb->data);
return -1;
} | 1 | CVE-2005-4881 | 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. | 5,463 |
linux | df453700e8d81b1bdafdf684365ee2b9431fb702 | static u32 __ipv6_select_ident(struct net *net, u32 hashrnd,
const struct in6_addr *dst,
const struct in6_addr *src)
{
u32 hash, id;
hash = __ipv6_addr_jhash(dst, hashrnd);
hash = __ipv6_addr_jhash(src, hash);
hash ^= net_hash_mix(net);
/* Treat id of 0 as unset and if we get 0 back from ip_idents_reserve,
* set the hight order instead thus minimizing possible future
* collisions.
*/
id = ip_idents_reserve(hash, 1);
if (unlikely(!id))
id = 1 << 31;
return id;
}
| 1 | CVE-2019-10638 | 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. | 5,720 |
ipsec | 7bab09631c2a303f87a7eb7e3d69e888673b9b7e | static int xfrm_policy_flo_check(struct flow_cache_object *flo)
{
struct xfrm_policy *pol = container_of(flo, struct xfrm_policy, flo);
return !pol->walk.dead;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,366 |
Chrome | 673ce95d481ea9368c4d4d43ac756ba1d6d9e608 | void MojoAudioInputIPC::StreamCreated(
media::mojom::AudioInputStreamPtr stream,
media::mojom::AudioInputStreamClientRequest stream_client_request,
mojo::ScopedSharedBufferHandle shared_memory,
mojo::ScopedHandle socket,
bool initially_muted) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(delegate_);
DCHECK(socket.is_valid());
DCHECK(shared_memory.is_valid());
DCHECK(!stream_);
DCHECK(!stream_client_binding_.is_bound());
stream_ = std::move(stream);
stream_client_binding_.Bind(std::move(stream_client_request));
base::PlatformFile socket_handle;
auto result = mojo::UnwrapPlatformFile(std::move(socket), &socket_handle);
DCHECK_EQ(result, MOJO_RESULT_OK);
base::SharedMemoryHandle memory_handle;
bool read_only = true;
result = mojo::UnwrapSharedMemoryHandle(std::move(shared_memory),
&memory_handle, nullptr, &read_only);
DCHECK_EQ(result, MOJO_RESULT_OK);
DCHECK(read_only);
delegate_->OnStreamCreated(memory_handle, socket_handle, initially_muted);
}
| 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). | 611 |
linux | bbf26183b7a6236ba602f4d6a2f7cade35bba043 | static int uwbd(void *param)
{
struct uwb_rc *rc = param;
unsigned long flags;
struct uwb_event *evt;
int should_stop = 0;
while (1) {
wait_event_interruptible_timeout(
rc->uwbd.wq,
!list_empty(&rc->uwbd.event_list)
|| (should_stop = kthread_should_stop()),
HZ);
if (should_stop)
break;
spin_lock_irqsave(&rc->uwbd.event_list_lock, flags);
if (!list_empty(&rc->uwbd.event_list)) {
evt = list_first_entry(&rc->uwbd.event_list, struct uwb_event, list_node);
list_del(&evt->list_node);
} else
evt = NULL;
spin_unlock_irqrestore(&rc->uwbd.event_list_lock, flags);
if (evt) {
uwbd_event_handle(evt);
kfree(evt);
}
uwb_beca_purge(rc); /* Purge devices that left */
}
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,264 |
infradead | a9f437119d79a438cb12e510f3cadd4060102c9f | svc_dg_enable_pktinfo(int fd, const struct __rpc_sockinfo *si)
{
int val = 1;
switch (si->si_af) {
case AF_INET:
(void) setsockopt(fd, SOL_IP, IP_PKTINFO, &val, sizeof(val));
break;
#ifdef INET6
case AF_INET6:
(void) setsockopt(fd, SOL_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val));
break;
#endif
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,753 |
linux | 6fcca0fa48118e6d63733eb4644c6cd880c15b8f | static ssize_t psi_write(struct file *file, const char __user *user_buf,
size_t nbytes, enum psi_res res)
{
char buf[32];
size_t buf_size;
struct seq_file *seq;
struct psi_trigger *new;
if (static_branch_likely(&psi_disabled))
return -EOPNOTSUPP;
buf_size = min(nbytes, sizeof(buf));
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
buf[buf_size - 1] = '\0';
new = psi_trigger_create(&psi_system, buf, nbytes, res);
if (IS_ERR(new))
return PTR_ERR(new);
seq = file->private_data;
/* Take seq->lock to protect seq->private from concurrent writes */
mutex_lock(&seq->lock);
psi_trigger_replace(&seq->private, new);
mutex_unlock(&seq->lock);
return nbytes;
} | 1 | CVE-2020-0110 | 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,535 |
linux-2.6 | e84e2e132c9c66d8498e7710d4ea532d1feaaac5 | static int shmem_map_and_free_swp(struct page *subdir, int offset,
int limit, struct page ***dir, spinlock_t *punch_lock)
{
swp_entry_t *ptr;
int freed = 0;
ptr = shmem_swp_map(subdir);
for (; offset < limit; offset += LATENCY_LIMIT) {
int size = limit - offset;
if (size > LATENCY_LIMIT)
size = LATENCY_LIMIT;
freed += shmem_free_swp(ptr+offset, ptr+offset+size,
punch_lock);
if (need_resched()) {
shmem_swp_unmap(ptr);
if (*dir) {
shmem_dir_unmap(*dir);
*dir = NULL;
}
cond_resched();
ptr = shmem_swp_map(subdir);
}
}
shmem_swp_unmap(ptr);
return freed;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,956 |
bootstrap-dht | bbc0b7191e3f48461ca6e5b1b34bdf4b3f1e79a9 | boost::int64_t lazy_entry::dict_find_int_value(char const* name, boost::int64_t default_val) const
{
lazy_entry const* e = dict_find(name);
if (e == 0 || e->type() != lazy_entry::int_t) return default_val;
return e->int_value();
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,944 |
Chrome | 3f71619ec516f553c69a08bf373dcde14e86d08f | void ZeroSuggestProvider::Start(const AutocompleteInput& input,
bool minimal_changes) {
TRACE_EVENT0("omnibox", "ZeroSuggestProvider::Start");
matches_.clear();
if (!input.from_omnibox_focus() || client()->IsOffTheRecord() ||
input.type() == metrics::OmniboxInputType::INVALID)
return;
Stop(true, false);
set_field_trial_triggered(false);
set_field_trial_triggered_in_session(false);
results_from_cache_ = false;
permanent_text_ = input.text();
current_query_ = input.current_url().spec();
current_title_ = input.current_title();
current_page_classification_ = input.current_page_classification();
current_url_match_ = MatchForCurrentURL();
GURL suggest_url(GetContextualSuggestionsUrl());
if (!suggest_url.is_valid())
return;
const TemplateURLService* template_url_service =
client()->GetTemplateURLService();
const TemplateURL* default_provider =
template_url_service->GetDefaultSearchProvider();
const bool can_send_current_url =
CanSendURL(input.current_url(), suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
GURL arbitrary_insecure_url(kArbitraryInsecureUrlString);
ZeroSuggestEligibility eligibility = ZeroSuggestEligibility::ELIGIBLE;
if (!can_send_current_url) {
const bool can_send_ordinary_url =
CanSendURL(arbitrary_insecure_url, suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
eligibility = can_send_ordinary_url
? ZeroSuggestEligibility::URL_INELIGIBLE
: ZeroSuggestEligibility::GENERALLY_INELIGIBLE;
}
UMA_HISTOGRAM_ENUMERATION(
"Omnibox.ZeroSuggest.Eligible.OnFocus", static_cast<int>(eligibility),
static_cast<int>(ZeroSuggestEligibility::ELIGIBLE_MAX_VALUE));
if (can_send_current_url &&
!OmniboxFieldTrial::InZeroSuggestPersonalizedFieldTrial() &&
!OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial()) {
if (UseExperimentalSuggestService(*template_url_service)) {
suggest_url = GURL(
OmniboxFieldTrial::ZeroSuggestRedirectToChromeServerAddress() +
"/url=" + net::EscapePath(current_query_) +
OmniboxFieldTrial::ZeroSuggestRedirectToChromeAdditionalFields());
} else {
base::string16 prefix;
TemplateURLRef::SearchTermsArgs search_term_args(prefix);
search_term_args.current_page_url = current_query_;
suggest_url =
GURL(default_provider->suggestions_url_ref().ReplaceSearchTerms(
search_term_args, template_url_service->search_terms_data()));
}
} else if (!ShouldShowNonContextualZeroSuggest(input.current_url())) {
return;
}
done_ = false;
MaybeUseCachedSuggestions();
Run(suggest_url);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,941 |
php-src | 3b8d4de300854b3517c7acb239b84f7726c1353c?w=1 | static zend_object *php_zip_object_new(zend_class_entry *class_type) /* {{{ */
{
ze_zip_object *intern;
intern = ecalloc(1, sizeof(ze_zip_object) + zend_object_properties_size(class_type));
intern->prop_handler = &zip_prop_handlers;
zend_object_std_init(&intern->zo, class_type);
object_properties_init(&intern->zo, class_type);
intern->zo.handlers = &zip_object_handlers;
return &intern->zo;
}
/* }}} */
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,933 |
qemu | 65a8e1f6413a0f6f79894da710b5d6d43361d27d | size_t mptsas_config_manufacturing_1(MPTSASState *s, uint8_t **data, int address)
{
/* VPD - all zeros */
return MPTSAS_CONFIG_PACK(1, MPI_CONFIG_PAGETYPE_MANUFACTURING, 0x00,
"*s256");
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,354 |
libtiff | 1044b43637fa7f70fb19b93593777b78bd20da86 | LogLuvEncodeStrip(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s)
{
tmsize_t rowlen = TIFFScanlineSize(tif);
if (rowlen == 0)
return 0;
assert(cc%rowlen == 0);
while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1) {
bp += rowlen;
cc -= rowlen;
}
return (cc == 0);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,364 |
Android | a30d7d90c4f718e46fb41a99b3d52800e1011b73 | virtual status_t setTransformHint(uint32_t hint) {
Parcel data, reply;
data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
data.writeUint32(hint);
status_t result = remote()->transact(SET_TRANSFORM_HINT, data, &reply);
if (result != NO_ERROR) {
return result;
}
return reply.readInt32();
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,140 |
linux | c4baad50297d84bde1a7ad45e50c73adae4a2192 | static void virtcons_remove(struct virtio_device *vdev)
{
struct ports_device *portdev;
struct port *port, *port2;
portdev = vdev->priv;
spin_lock_irq(&pdrvdata_lock);
list_del(&portdev->list);
spin_unlock_irq(&pdrvdata_lock);
/* Disable interrupts for vqs */
vdev->config->reset(vdev);
/* Finish up work that's lined up */
if (use_multiport(portdev))
cancel_work_sync(&portdev->control_work);
else
cancel_work_sync(&portdev->config_work);
list_for_each_entry_safe(port, port2, &portdev->ports, list)
unplug_port(port);
unregister_chrdev(portdev->chr_major, "virtio-portsdev");
/*
* When yanking out a device, we immediately lose the
* (device-side) queues. So there's no point in keeping the
* guest side around till we drop our final reference. This
* also means that any ports which are in an open state will
* have to just stop using the port, as the vqs are going
* away.
*/
remove_controlq_data(portdev);
remove_vqs(portdev);
kfree(portdev);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,924 |
linux | f6d8bd051c391c1c0458a30b2a7abcd939329259 | int cipso_v4_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr)
{
struct ip_options *opt;
opt = inet_sk(sk)->opt;
if (opt == NULL || opt->cipso == 0)
return -ENOMSG;
return cipso_v4_getattr(opt->__data + opt->cipso - sizeof(struct iphdr),
secattr);
}
| 1 | CVE-2012-3552 | 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 | 476 |
FFmpeg | 2080bc33717955a0e4268e738acf8c1eeddbf8cb | static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
{
if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
int i;
int num_planes = av_pix_fmt_count_planes(frame->format);
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
int flags = desc ? desc->flags : 0;
if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
num_planes = 2;
for (i = 0; i < num_planes; i++) {
av_assert0(frame->data[i]);
}
if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
num_planes = 2;
for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
if (frame->data[i])
av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
frame->data[i] = NULL;
}
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,810 |
linux | 6062a8dc0517bce23e3c2f7d2fea5e22411269a3 | void ipc_rcu_getref(void *ptr)
{
container_of(ptr, struct ipc_rcu_hdr, data)->refcount++;
}
| 1 | CVE-2013-4483 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 1,201 |
linux | a8c1f65c79cbbb2f7da782d4c9d15639a9b94b27 | static void igmp_start_timer(struct ip_mc_list *im, int max_delay)
{
int tv = net_random() % max_delay;
im->tm_running = 1;
if (!mod_timer(&im->timer, jiffies+tv+2))
atomic_inc(&im->refcnt);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,513 |
linux | 8835ba4a39cf53f705417b3b3a94eb067673f2c9 | static void acm_write_buffers_free(struct acm *acm)
{
int i;
struct acm_wb *wb;
struct usb_device *usb_dev = interface_to_usbdev(acm->control);
for (wb = &acm->wb[0], i = 0; i < ACM_NW; i++, wb++)
usb_free_coherent(usb_dev, acm->writesize, wb->buf, wb->dmah);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,443 |
tcpdump | d7505276842e85bfd067fa21cdb32b8a2dc3c5e4 | mldv2_query_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int mrc;
int mrt, qqi;
u_int nsrcs;
register u_int i;
/* Minimum len is 28 */
if (len < 28) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[0]);
mrc = EXTRACT_16BITS(&icp->icmp6_data16[0]);
if (mrc < 32768) {
mrt = mrc;
} else {
mrt = ((mrc & 0x0fff) | 0x1000) << (((mrc & 0x7000) >> 12) + 3);
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo," [max resp delay=%d]", mrt));
}
ND_TCHECK2(bp[8], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[8])));
if (ndo->ndo_vflag) {
ND_TCHECK(bp[25]);
if (bp[24] & 0x08) {
ND_PRINT((ndo," sflag"));
}
if (bp[24] & 0x07) {
ND_PRINT((ndo," robustness=%d", bp[24] & 0x07));
}
if (bp[25] < 128) {
qqi = bp[25];
} else {
qqi = ((bp[25] & 0x0f) | 0x10) << (((bp[25] & 0x70) >> 4) + 3);
}
ND_PRINT((ndo," qqi=%d", qqi));
}
ND_TCHECK2(bp[26], 2);
nsrcs = EXTRACT_16BITS(&bp[26]);
if (nsrcs > 0) {
if (len < 28 + nsrcs * sizeof(struct in6_addr))
ND_PRINT((ndo," [invalid number of sources]"));
else if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo," {"));
for (i = 0; i < nsrcs; i++) {
ND_TCHECK2(bp[28 + i * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[28 + i * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
} else
ND_PRINT((ndo,", %d source(s)", nsrcs));
}
ND_PRINT((ndo,"]"));
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
}
| 1 | CVE-2018-14882 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 7,599 |
kvm | e42d9b8141d1f54ff72ad3850bb110c95a5f3b88 | static int do_insn_fetch(struct x86_emulate_ctxt *ctxt,
struct x86_emulate_ops *ops,
unsigned long eip, void *dest, unsigned size)
{
int rc = 0;
eip += ctxt->cs_base;
while (size--) {
rc = do_fetch_insn_byte(ctxt, ops, eip++, dest++);
if (rc)
return rc;
}
return 0;
} | 1 | CVE-2009-4031 | 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,253 |
Chrome | d66c757a9a434f48069b114fb49191e4790f9038 | void InputMethodBase::OnFocus() {
DCHECK(!system_toplevel_window_focused_);
system_toplevel_window_focused_ = true;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,091 |
FFmpeg | cdd5df8189ff1537f7abe8defe971f80602cc2d2 | static void flush_fifo(AVFifoBuffer *fifo)
{
while (av_fifo_size(fifo)) {
AVFrame *tmp;
av_fifo_generic_read(fifo, &tmp, sizeof(tmp), NULL);
av_frame_free(&tmp);
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,211 |
linux | a399b29dfbaaaf91162b2dc5a5875dd51bbfa2a1 | static inline void shm_lock_by_ptr(struct shmid_kernel *ipcp)
{
rcu_read_lock();
ipc_lock_object(&ipcp->shm_perm);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,315 |
linux-2.6 | 9ef1d4c7c7aca1cd436612b6ca785b726ffb8ed8 | tca_get_fill(struct sk_buff *skb, struct tc_action *a, u32 pid, u32 seq,
u16 flags, int event, int bind, int ref)
{
struct tcamsg *t;
struct nlmsghdr *nlh;
unsigned char *b = skb->tail;
struct rtattr *x;
nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*t), flags);
t = NLMSG_DATA(nlh);
t->tca_family = AF_UNSPEC;
x = (struct rtattr*) skb->tail;
RTA_PUT(skb, TCA_ACT_TAB, 0, NULL);
if (tcf_action_dump(skb, a, bind, ref) < 0)
goto rtattr_failure;
x->rta_len = skb->tail - (u8*)x;
nlh->nlmsg_len = skb->tail - b;
return skb->len;
rtattr_failure:
nlmsg_failure:
skb_trim(skb, b - skb->data);
return -1;
} | 1 | CVE-2005-4881 | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. |
Phase: Architecture and Design
Strategy: Separation of Privilege
Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area.
Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges. | 8,191 |
linux | 19d1532a187669ce86d5a2696eb7275310070793 | static void sp_setup(struct net_device *dev)
{
/* Finish setting up the DEVICE info. */
dev->netdev_ops = &sp_netdev_ops;
dev->needs_free_netdev = true;
dev->mtu = SIXP_MTU;
dev->hard_header_len = AX25_MAX_HEADER_LEN;
dev->header_ops = &ax25_header_ops;
dev->addr_len = AX25_ADDR_LEN;
dev->type = ARPHRD_AX25;
dev->tx_queue_len = 10;
/* Only activated in AX.25 mode */
memcpy(dev->broadcast, &ax25_bcast, AX25_ADDR_LEN);
memcpy(dev->dev_addr, &ax25_defaddr, AX25_ADDR_LEN);
dev->flags = 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,510 |
FreeRDP | 0d79670a28c0ab049af08613621aa0c267f977e9 | static UINT wf_cliprdr_server_capabilities(CliprdrClientContext* context,
const CLIPRDR_CAPABILITIES* capabilities)
{
UINT32 index;
CLIPRDR_CAPABILITY_SET* capabilitySet;
wfClipboard* clipboard = (wfClipboard*)context->custom;
if (!context || !capabilities)
return ERROR_INTERNAL_ERROR;
for (index = 0; index < capabilities->cCapabilitiesSets; index++)
{
capabilitySet = &(capabilities->capabilitySets[index]);
if ((capabilitySet->capabilitySetType == CB_CAPSTYPE_GENERAL) &&
(capabilitySet->capabilitySetLength >= CB_CAPSTYPE_GENERAL_LEN))
{
CLIPRDR_GENERAL_CAPABILITY_SET* generalCapabilitySet =
(CLIPRDR_GENERAL_CAPABILITY_SET*)capabilitySet;
clipboard->capabilities = generalCapabilitySet->generalFlags;
break;
}
}
return CHANNEL_RC_OK;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,849 |
virglrenderer | 48f67f60967f963b698ec8df57ec6912a43d6282 | void vrend_clear(struct vrend_context *ctx,
unsigned buffers,
const union pipe_color_union *color,
double depth, unsigned stencil)
{
GLbitfield bits = 0;
if (ctx->in_error)
return;
if (ctx->ctx_switch_pending)
vrend_finish_context_switch(ctx);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->sub->fb_id);
vrend_update_frontface_state(ctx);
if (ctx->sub->stencil_state_dirty)
vrend_update_stencil_state(ctx);
if (ctx->sub->scissor_state_dirty)
vrend_update_scissor_state(ctx);
if (ctx->sub->viewport_state_dirty)
vrend_update_viewport_state(ctx);
vrend_use_program(ctx, 0);
if (buffers & PIPE_CLEAR_COLOR) {
if (ctx->sub->nr_cbufs && ctx->sub->surf[0] && vrend_format_is_emulated_alpha(ctx->sub->surf[0]->format)) {
glClearColor(color->f[3], 0.0, 0.0, 0.0);
} else {
glClearColor(color->f[0], color->f[1], color->f[2], color->f[3]);
}
}
if (buffers & PIPE_CLEAR_DEPTH) {
/* gallium clears don't respect depth mask */
glDepthMask(GL_TRUE);
glClearDepth(depth);
}
if (buffers & PIPE_CLEAR_STENCIL)
glClearStencil(stencil);
if (buffers & PIPE_CLEAR_COLOR) {
uint32_t mask = 0;
int i;
for (i = 0; i < ctx->sub->nr_cbufs; i++) {
if (ctx->sub->surf[i])
mask |= (1 << i);
}
if (mask != (buffers >> 2)) {
mask = buffers >> 2;
while (mask) {
i = u_bit_scan(&mask);
if (util_format_is_pure_uint(ctx->sub->surf[i]->format))
glClearBufferuiv(GL_COLOR,
i, (GLuint *)color);
else if (util_format_is_pure_sint(ctx->sub->surf[i]->format))
glClearBufferiv(GL_COLOR,
i, (GLint *)color);
else
glClearBufferfv(GL_COLOR,
i, (GLfloat *)color);
}
}
else
bits |= GL_COLOR_BUFFER_BIT;
}
if (buffers & PIPE_CLEAR_DEPTH)
bits |= GL_DEPTH_BUFFER_BIT;
if (buffers & PIPE_CLEAR_STENCIL)
bits |= GL_STENCIL_BUFFER_BIT;
if (bits)
glClear(bits);
if (buffers & PIPE_CLEAR_DEPTH)
if (!ctx->sub->dsa_state.depth.writemask)
glDepthMask(GL_FALSE);
}
| 1 | CVE-2017-5937 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 2,058 |
linux | b769f49463711205d57286e64cf535ed4daf59e9 | int sequencer_open(int dev, struct file *file)
{
int retval, mode, i;
int level, tmp;
if (!sequencer_ok)
sequencer_init();
level = ((dev & 0x0f) == SND_DEV_SEQ2) ? 2 : 1;
dev = dev >> 4;
mode = translate_mode(file);
DEB(printk("sequencer_open(dev=%d)\n", dev));
if (!sequencer_ok)
{
/* printk("Sound card: sequencer not initialized\n");*/
return -ENXIO;
}
if (dev) /* Patch manager device (obsolete) */
return -ENXIO;
if(synth_devs[dev] == NULL)
request_module("synth0");
if (mode == OPEN_READ)
{
if (!num_midis)
{
/*printk("Sequencer: No MIDI devices. Input not possible\n");*/
sequencer_busy = 0;
return -ENXIO;
}
}
if (sequencer_busy)
{
return -EBUSY;
}
sequencer_busy = 1;
obsolete_api_used = 0;
max_mididev = num_midis;
max_synthdev = num_synths;
pre_event_timeout = MAX_SCHEDULE_TIMEOUT;
seq_mode = SEQ_1;
if (pending_timer != -1)
{
tmr_no = pending_timer;
pending_timer = -1;
}
if (tmr_no == -1) /* Not selected yet */
{
int i, best;
best = -1;
for (i = 0; i < num_sound_timers; i++)
if (sound_timer_devs[i] && sound_timer_devs[i]->priority > best)
{
tmr_no = i;
best = sound_timer_devs[i]->priority;
}
if (tmr_no == -1) /* Should not be */
tmr_no = 0;
}
tmr = sound_timer_devs[tmr_no];
if (level == 2)
{
if (tmr == NULL)
{
/*printk("sequencer: No timer for level 2\n");*/
sequencer_busy = 0;
return -ENXIO;
}
setup_mode2();
}
if (!max_synthdev && !max_mididev)
{
sequencer_busy=0;
return -ENXIO;
}
synth_open_mask = 0;
for (i = 0; i < max_mididev; i++)
{
midi_opened[i] = 0;
midi_written[i] = 0;
}
for (i = 0; i < max_synthdev; i++)
{
if (synth_devs[i]==NULL)
continue;
if (!try_module_get(synth_devs[i]->owner))
continue;
if ((tmp = synth_devs[i]->open(i, mode)) < 0)
{
printk(KERN_WARNING "Sequencer: Warning! Cannot open synth device #%d (%d)\n", i, tmp);
if (synth_devs[i]->midi_dev)
printk(KERN_WARNING "(Maps to MIDI dev #%d)\n", synth_devs[i]->midi_dev);
}
else
{
synth_open_mask |= (1 << i);
if (synth_devs[i]->midi_dev)
midi_opened[synth_devs[i]->midi_dev] = 1;
}
}
seq_time = jiffies;
prev_input_time = 0;
prev_event_time = 0;
if (seq_mode == SEQ_1 && (mode == OPEN_READ || mode == OPEN_READWRITE))
{
/*
* Initialize midi input devices
*/
for (i = 0; i < max_mididev; i++)
if (!midi_opened[i] && midi_devs[i])
{
if (!try_module_get(midi_devs[i]->owner))
continue;
if ((retval = midi_devs[i]->open(i, mode,
sequencer_midi_input, sequencer_midi_output)) >= 0)
{
midi_opened[i] = 1;
}
}
}
if (seq_mode == SEQ_2) {
if (try_module_get(tmr->owner))
tmr->open(tmr_no, seq_mode);
}
init_waitqueue_head(&seq_sleeper);
init_waitqueue_head(&midi_sleeper);
output_threshold = SEQ_MAX_QUEUE / 2;
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,378 |
ImageMagick6 | 553054c1cb1e4e05ec86237afef76a32cd7c464d | static void ExportRedQuantum(QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const PixelPacket *magick_restrict p,
unsigned char *magick_restrict q)
{
QuantumAny
range;
ssize_t
x;
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
pixel=ScaleQuantumToChar(GetPixelRed(p));
q=PopCharPixel(pixel,q);
p++;
q+=quantum_info->pad;
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
pixel=SinglePrecisionToHalf(QuantumScale*GetPixelRed(p));
q=PopShortPixel(quantum_info->endian,pixel,q);
p++;
q+=quantum_info->pad;
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
pixel=ScaleQuantumToShort(GetPixelRed(p));
q=PopShortPixel(quantum_info->endian,pixel,q);
p++;
q+=quantum_info->pad;
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
q=PopFloatPixel(quantum_info,(float) GetPixelRed(p),q);
p++;
q+=quantum_info->pad;
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
pixel=ScaleQuantumToLong(GetPixelRed(p));
q=PopLongPixel(quantum_info->endian,pixel,q);
p++;
q+=quantum_info->pad;
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
q=PopDoublePixel(quantum_info,(double) GetPixelRed(p),q);
p++;
q+=quantum_info->pad;
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
q=PopQuantumPixel(quantum_info,ScaleQuantumToAny(GetPixelRed(p),range),
q);
p++;
q+=quantum_info->pad;
}
break;
}
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,423 |
Chrome | f03ea5a5c2ff26e239dfd23e263b15da2d9cee93 | explicit FrameURLLoaderFactory(base::WeakPtr<RenderFrameImpl> frame)
: frame_(std::move(frame)) {}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,516 |
Chrome | 2ad6b02cbf13d8f9dce50340e966ba413cb66b1c | void InputEngine::ProcessText(const std::string& message,
ProcessTextCallback callback) {
NOTIMPLEMENTED(); // Text message not used in the rulebased engine.
}
| 1 | CVE-2017-5056 | 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,488 |
php-src | 0d822f6df946764f3f0348b82efae2e1eaa83aa0 | PHPAPI char * _php_math_longtobase(zval *arg, int base)
{
static char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
char buf[(sizeof(unsigned long) << 3) + 1];
char *ptr, *end;
unsigned long value;
if (Z_TYPE_P(arg) != IS_LONG || base < 2 || base > 36) {
return STR_EMPTY_ALLOC();
}
value = Z_LVAL_P(arg);
end = ptr = buf + sizeof(buf) - 1;
*ptr = '\0';
do {
*--ptr = digits[value % base];
value /= base;
} while (ptr > buf && value);
return estrndup(ptr, end - ptr);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,191 |
Android | 659030a2e80c38fb8da0a4eb68695349eec6778b | int res_inverse(vorbis_dsp_state *vd,vorbis_info_residue *info,
ogg_int32_t **in,int *nonzero,int ch){
int i,j,k,s,used=0;
codec_setup_info *ci=(codec_setup_info *)vd->vi->codec_setup;
codebook *phrasebook=ci->book_param+info->groupbook;
int samples_per_partition=info->grouping;
int partitions_per_word=phrasebook->dim;
int pcmend=ci->blocksizes[vd->W];
if(info->type<2){
int max=pcmend>>1;
int end=(info->end<max?info->end:max);
int n=end-info->begin;
if(n>0){
int partvals=n/samples_per_partition;
int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
for(i=0;i<ch;i++)
if(nonzero[i])
in[used++]=in[i];
ch=used;
if(used){
char **partword=(char **)alloca(ch*sizeof(*partword));
for(j=0;j<ch;j++)
partword[j]=(char *)alloca(partwords*partitions_per_word*
sizeof(*partword[j]));
for(s=0;s<info->stages;s++){
for(i=0;i<partvals;){
if(s==0){
/* fetch the partition word for each channel */
partword[0][i+partitions_per_word-1]=1;
for(k=partitions_per_word-2;k>=0;k--)
partword[0][i+k]=partword[0][i+k+1]*info->partitions;
for(j=1;j<ch;j++)
for(k=partitions_per_word-1;k>=0;k--)
partword[j][i+k]=partword[j-1][i+k];
for(j=0;j<ch;j++){
int temp=vorbis_book_decode(phrasebook,&vd->opb);
if(temp==-1)goto eopbreak;
/* this can be done quickly in assembly due to the quotient
always being at most six bits */
for(k=0;k<partitions_per_word;k++){
ogg_uint32_t div=partword[j][i+k];
partword[j][i+k]=temp/div;
temp-=partword[j][i+k]*div;
}
}
}
/* now we decode residual values for the partitions */
for(k=0;k<partitions_per_word && i<partvals;k++,i++)
for(j=0;j<ch;j++){
long offset=info->begin+i*samples_per_partition;
int idx = (int)partword[j][i];
if(idx < info->partitions && info->stagemasks[idx]&(1<<s)){
codebook *stagebook=ci->book_param+
info->stagebooks[(partword[j][i]<<3)+s];
if(info->type){
if(vorbis_book_decodev_add(stagebook,in[j]+offset,&vd->opb,
samples_per_partition,-8)==-1)
goto eopbreak;
}else{
if(vorbis_book_decodevs_add(stagebook,in[j]+offset,&vd->opb,
samples_per_partition,-8)==-1)
goto eopbreak;
}
}
}
}
}
}
}
}else{
int max=(pcmend*ch)>>1;
int end=(info->end<max?info->end:max);
int n=end-info->begin;
if(n>0){
int partvals=n/samples_per_partition;
int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
char *partword=
(char *)alloca(partwords*partitions_per_word*sizeof(*partword));
int beginoff=info->begin/ch;
for(i=0;i<ch;i++)if(nonzero[i])break;
if(i==ch)return(0); /* no nonzero vectors */
samples_per_partition/=ch;
for(s=0;s<info->stages;s++){
for(i=0;i<partvals;){
if(s==0){
int temp;
partword[i+partitions_per_word-1]=1;
for(k=partitions_per_word-2;k>=0;k--)
partword[i+k]=partword[i+k+1]*info->partitions;
/* fetch the partition word */
temp=vorbis_book_decode(phrasebook,&vd->opb);
if(temp==-1)goto eopbreak;
/* this can be done quickly in assembly due to the quotient
always being at most six bits */
for(k=0;k<partitions_per_word;k++){
ogg_uint32_t div=partword[i+k];
partword[i+k]=temp/div;
temp-=partword[i+k]*div;
}
}
/* now we decode residual values for the partitions */
for(k=0;k<partitions_per_word && i<partvals;k++,i++)
if(info->stagemasks[(int)partword[i]]&(1<<s)){
codebook *stagebook=ci->book_param+
info->stagebooks[(partword[i]<<3)+s];
if(vorbis_book_decodevv_add(stagebook,in,
i*samples_per_partition+beginoff,ch,
&vd->opb,
samples_per_partition,-8)==-1)
goto eopbreak;
}
}
}
}
}
eopbreak:
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,575 |
freeradius-server | 1b1ec5ce75e224bd1755650c18ccdaa6dc53e605 | static int unix_authorize(void *instance, REQUEST *request)
{
return unix_getpw(instance, request, &request->config_items);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,881 |
Android | f81038006b4c59a5a148dcad887371206033c28f | sp<MediaSource> MPEG4Extractor::getTrack(size_t index) {
status_t err;
if ((err = readMetaData()) != OK) {
return NULL;
}
Track *track = mFirstTrack;
while (index > 0) {
if (track == NULL) {
return NULL;
}
track = track->next;
--index;
}
if (track == NULL) {
return NULL;
}
Trex *trex = NULL;
int32_t trackId;
if (track->meta->findInt32(kKeyTrackID, &trackId)) {
for (size_t i = 0; i < mTrex.size(); i++) {
Trex *t = &mTrex.editItemAt(index);
if (t->track_ID == (uint32_t) trackId) {
trex = t;
break;
}
}
}
ALOGV("getTrack called, pssh: %zu", mPssh.size());
return new MPEG4Source(this,
track->meta, mDataSource, track->timescale, track->sampleTable,
mSidxEntries, trex, mMoofOffset);
}
| 1 | CVE-2016-2508 | 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,613 |
Chrome | c21d7ac13d69cbadbbb5b2dc147be1933d52147a | void ScreenPositionController::ConvertHostPointToRelativeToRootWindow(
aura::Window* root_window,
const aura::Window::Windows& root_windows,
gfx::Point* point,
aura::Window** target_root) {
DCHECK(!root_window->parent());
gfx::Point point_in_root(*point);
root_window->GetHost()->ConvertPointFromHost(&point_in_root);
*target_root = root_window;
*point = point_in_root;
#if defined(USE_X11) || defined(USE_OZONE)
if (!root_window->GetHost()->GetBounds().Contains(*point)) {
gfx::Point location_in_native(point_in_root);
root_window->GetHost()->ConvertPointToNativeScreen(&location_in_native);
for (size_t i = 0; i < root_windows.size(); ++i) {
aura::WindowTreeHost* host = root_windows[i]->GetHost();
const gfx::Rect native_bounds = host->GetBounds();
if (native_bounds.Contains(location_in_native)) {
*target_root = root_windows[i];
*point = location_in_native;
host->ConvertPointFromNativeScreen(point);
break;
}
}
}
#else
NOTIMPLEMENTED();
#endif
}
| 1 | CVE-2013-6663 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 6,793 |
Chrome | 6d9425ec7badda912555d46ea7abcfab81fdd9b9 | scoped_ptr<cc::CompositorFrame> SynchronousCompositorImpl::DemandDrawHw(
gfx::Size surface_size,
const gfx::Transform& transform,
gfx::Rect viewport,
gfx::Rect clip,
gfx::Rect viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority) {
DCHECK(CalledOnValidThread());
DCHECK(output_surface_);
DCHECK(begin_frame_source_);
scoped_ptr<cc::CompositorFrame> frame =
output_surface_->DemandDrawHw(surface_size,
transform,
viewport,
clip,
viewport_rect_for_tile_priority,
transform_for_tile_priority);
if (frame.get())
UpdateFrameMetaData(frame->metadata);
return frame.Pass();
}
| 1 | CVE-2014-1743 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 8,644 |
Subsets and Splits