text
stringlengths 478
483k
|
---|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: charclass_index (charclass const s)
{
int i;
for (i = 0; i < dfa->cindex; ++i)
if (equal(s, dfa->charclasses[i]))
return i;
REALLOC_IF_NECESSARY(dfa->charclasses, dfa->calloc, dfa->cindex + 1);
++dfa->cindex;
copyset(s, dfa->charclasses[i]);
return i;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: check_matching_with_multibyte_ops (struct dfa *d, int s, int idx)
{
int i;
int* rarray;
MALLOC(rarray, d->states[s].mbps.nelem);
for (i = 0; i < d->states[s].mbps.nelem; ++i)
{
position pos = d->states[s].mbps.elems[i];
switch(d->tokens[pos.index])
{
case ANYCHAR:
rarray[i] = match_anychar(d, s, pos, idx);
break;
case MBCSET:
rarray[i] = match_mb_charset(d, s, pos, idx);
break;
default:
break; /* cannot happen. */
}
}
return rarray;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: match_mb_charset (struct dfa *d, int s, position pos, int idx)
{
int i;
int match; /* Flag which represent that matching succeed. */
int match_len; /* Length of the character (or collating element)
with which this operator match. */
int op_len; /* Length of the operator. */
char buffer[128];
wchar_t wcbuf[6];
/* Pointer to the structure to which we are currently refering. */
struct mb_char_classes *work_mbc;
int context;
wchar_t wc; /* Current refering character. */
wc = inputwcs[idx];
/* Check syntax bits. */
if (wc == (wchar_t)eolbyte)
{
if (!(syntax_bits & RE_DOT_NEWLINE))
return 0;
}
else if (wc == (wchar_t)'\0')
{
if (syntax_bits & RE_DOT_NOT_NULL)
return 0;
}
context = wchar_context(wc);
if (!SUCCEEDS_IN_CONTEXT(pos.constraint, d->states[s].context, context))
return 0;
/* Assign the current refering operator to work_mbc. */
work_mbc = &(d->mbcsets[(d->multibyte_prop[pos.index]) >> 2]);
match = !work_mbc->invert;
match_len = (mblen_buf[idx] == 0)? 1 : mblen_buf[idx];
/* Match in range 0-255? */
if (wc < NOTCHAR && work_mbc->cset != -1
&& tstbit((unsigned char)wc, d->charclasses[work_mbc->cset]))
goto charset_matched;
/* match with a character class? */
for (i = 0; i<work_mbc->nch_classes; i++)
{
if (iswctype((wint_t)wc, work_mbc->ch_classes[i]))
goto charset_matched;
}
strncpy(buffer, (char const *) buf_begin + idx, match_len);
buffer[match_len] = '\0';
/* match with an equivalent class? */
for (i = 0; i<work_mbc->nequivs; i++)
{
op_len = strlen(work_mbc->equivs[i]);
strncpy(buffer, (char const *) buf_begin + idx, op_len);
buffer[op_len] = '\0';
if (strcoll(work_mbc->equivs[i], buffer) == 0)
{
match_len = op_len;
goto charset_matched;
}
}
/* match with a collating element? */
for (i = 0; i<work_mbc->ncoll_elems; i++)
{
op_len = strlen(work_mbc->coll_elems[i]);
strncpy(buffer, (char const *) buf_begin + idx, op_len);
buffer[op_len] = '\0';
if (strcoll(work_mbc->coll_elems[i], buffer) == 0)
{
match_len = op_len;
goto charset_matched;
}
}
wcbuf[0] = wc;
wcbuf[1] = wcbuf[3] = wcbuf[5] = '\0';
/* match with a range? */
for (i = 0; i<work_mbc->nranges; i++)
{
wcbuf[2] = work_mbc->range_sts[i];
wcbuf[4] = work_mbc->range_ends[i];
if (wcscoll(wcbuf, wcbuf+2) >= 0 &&
wcscoll(wcbuf+4, wcbuf) >= 0)
goto charset_matched;
}
/* match with a character? */
for (i = 0; i<work_mbc->nchars; i++)
{
if (wc == work_mbc->chars[i])
goto charset_matched;
}
match = !match;
charset_matched:
return match ? match_len : 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: build_state (int s, struct dfa *d)
{
int *trans; /* The new transition table. */
int i;
/* Set an upper limit on the number of transition tables that will ever
exist at once. 1024 is arbitrary. The idea is that the frequently
used transition tables will be quickly rebuilt, whereas the ones that
were only needed once or twice will be cleared away. */
if (d->trcount >= 1024)
{
for (i = 0; i < d->tralloc; ++i)
{
free(d->trans[i]);
free(d->fails[i]);
d->trans[i] = d->fails[i] = NULL;
}
d->trcount = 0;
}
++d->trcount;
/* Set up the success bits for this state. */
d->success[s] = 0;
if (ACCEPTS_IN_CONTEXT(d->states[s].context, CTX_NEWLINE, s, *d))
d->success[s] |= CTX_NEWLINE;
if (ACCEPTS_IN_CONTEXT(d->states[s].context, CTX_LETTER, s, *d))
d->success[s] |= CTX_LETTER;
if (ACCEPTS_IN_CONTEXT(d->states[s].context, CTX_NONE, s, *d))
d->success[s] |= CTX_NONE;
MALLOC(trans, NOTCHAR);
dfastate(s, d, trans);
/* Now go through the new transition table, and make sure that the trans
and fail arrays are allocated large enough to hold a pointer for the
largest state mentioned in the table. */
for (i = 0; i < NOTCHAR; ++i)
if (trans[i] >= d->tralloc)
{
int oldalloc = d->tralloc;
while (trans[i] >= d->tralloc)
d->tralloc *= 2;
REALLOC(d->realtrans, d->tralloc + 1);
d->trans = d->realtrans + 1;
REALLOC(d->fails, d->tralloc);
REALLOC(d->success, d->tralloc);
REALLOC(d->newlines, d->tralloc);
while (oldalloc < d->tralloc)
{
d->trans[oldalloc] = NULL;
d->fails[oldalloc++] = NULL;
}
}
/* Keep the newline transition in a special place so we can use it as
a sentinel. */
d->newlines[s] = trans[eolbyte];
trans[eolbyte] = -1;
if (ACCEPTING(s, *d))
d->fails[s] = trans;
else
d->trans[s] = trans;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: copytoks (int tindex, int ntokens)
{
int i;
for (i = 0; i < ntokens; ++i)
{
addtok(dfa->tokens[tindex + i]);
/* Update index into multibyte csets. */
if (MB_CUR_MAX > 1 && dfa->tokens[tindex + i] == MBCSET)
dfa->multibyte_prop[dfa->tindex - 1] = dfa->multibyte_prop[tindex + i];
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: match_anychar (struct dfa *d, int s, position pos, int idx)
{
int context;
wchar_t wc;
int mbclen;
wc = inputwcs[idx];
mbclen = (mblen_buf[idx] == 0)? 1 : mblen_buf[idx];
/* Check syntax bits. */
if (wc == (wchar_t)eolbyte)
{
if (!(syntax_bits & RE_DOT_NEWLINE))
return 0;
}
else if (wc == (wchar_t)'\0')
{
if (syntax_bits & RE_DOT_NOT_NULL)
return 0;
}
context = wchar_context(wc);
if (!SUCCEEDS_IN_CONTEXT(pos.constraint, d->states[s].context, context))
return 0;
return mbclen;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: transit_state_singlebyte (struct dfa *d, int s, unsigned char const *p,
int *next_state)
{
int *t;
int works = s;
status_transit_state rval = TRANSIT_STATE_IN_PROGRESS;
while (rval == TRANSIT_STATE_IN_PROGRESS)
{
if ((t = d->trans[works]) != NULL)
{
works = t[*p];
rval = TRANSIT_STATE_DONE;
if (works < 0)
works = 0;
}
else if (works < 0)
{
if (p == buf_end)
{
/* At the moment, it must not happen. */
abort ();
}
works = 0;
}
else if (d->fails[works])
{
works = d->fails[works][*p];
rval = TRANSIT_STATE_DONE;
}
else
{
build_state(works, d);
}
}
*next_state = works;
return rval;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: merge (position_set const *s1, position_set const *s2, position_set *m)
{
int i = 0, j = 0;
REALLOC_IF_NECESSARY(m->elems, m->alloc, s1->nelem + s2->nelem);
m->nelem = 0;
while (i < s1->nelem && j < s2->nelem)
if (s1->elems[i].index > s2->elems[j].index)
m->elems[m->nelem++] = s1->elems[i++];
else if (s1->elems[i].index < s2->elems[j].index)
m->elems[m->nelem++] = s2->elems[j++];
else
{
m->elems[m->nelem] = s1->elems[i++];
m->elems[m->nelem++].constraint |= s2->elems[j++].constraint;
}
while (i < s1->nelem)
m->elems[m->nelem++] = s1->elems[i++];
while (j < s2->nelem)
m->elems[m->nelem++] = s2->elems[j++];
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: addlists (char **old, char **new)
{
int i;
if (old == NULL || new == NULL)
return NULL;
for (i = 0; new[i] != NULL; ++i)
{
old = enlist(old, new[i], strlen(new[i]));
if (old == NULL)
break;
}
return old;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: state_separate_contexts (position_set const *s)
{
int separate_contexts = 0;
unsigned int j;
for (j = 0; j < s->nelem; ++j)
{
if (PREV_NEWLINE_DEPENDENT (s->elems[j].constraint))
separate_contexts |= CTX_NEWLINE;
if (PREV_LETTER_DEPENDENT (s->elems[j].constraint))
separate_contexts |= CTX_LETTER;
}
return separate_contexts;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: EGexecute (char const *buf, size_t size, size_t *match_size,
char const *start_ptr)
{
char const *buflim, *beg, *end, *match, *best_match, *mb_start;
char eol = eolbyte;
int backref, start, len, best_len;
struct kwsmatch kwsm;
size_t i, ret_val;
if (MB_CUR_MAX > 1)
{
if (match_icase)
{
/* mbtolower adds a NUL byte at the end. That will provide
space for the sentinel byte dfaexec may add. */
char *case_buf = mbtolower (buf, &size);
if (start_ptr)
start_ptr = case_buf + (start_ptr - buf);
buf = case_buf;
}
}
mb_start = buf;
buflim = buf + size;
for (beg = end = buf; end < buflim; beg = end)
{
if (!start_ptr)
{
/* We don't care about an exact match. */
if (kwset)
{
/* Find a possible match using the KWset matcher. */
size_t offset = kwsexec (kwset, beg, buflim - beg, &kwsm);
if (offset == (size_t) -1)
goto failure;
beg += offset;
/* Narrow down to the line containing the candidate, and
run it through DFA. */
if ((end = memchr(beg, eol, buflim - beg)) != NULL)
end++;
else
end = buflim;
match = beg;
while (beg > buf && beg[-1] != eol)
--beg;
if (kwsm.index < kwset_exact_matches)
{
if (!MBS_SUPPORT)
goto success;
if (mb_start < beg)
mb_start = beg;
if (MB_CUR_MAX == 1
|| !is_mb_middle (&mb_start, match, buflim,
kwsm.size[0]))
goto success;
}
if (dfaexec (dfa, beg, (char *) end, 0, NULL, &backref) == NULL)
continue;
}
else
{
/* No good fixed strings; start with DFA. */
char const *next_beg = dfaexec (dfa, beg, (char *) buflim,
0, NULL, &backref);
if (next_beg == NULL)
break;
/* Narrow down to the line we've found. */
beg = next_beg;
if ((end = memchr(beg, eol, buflim - beg)) != NULL)
end++;
else
end = buflim;
while (beg > buf && beg[-1] != eol)
--beg;
}
/* Successful, no backreferences encountered! */
if (!backref)
goto success;
}
else
{
/* We are looking for the leftmost (then longest) exact match.
We will go through the outer loop only once. */
beg = start_ptr;
end = buflim;
}
/* If we've made it to this point, this means DFA has seen
a probable match, and we need to run it through Regex. */
best_match = end;
best_len = 0;
for (i = 0; i < pcount; i++)
{
patterns[i].regexbuf.not_eol = 0;
if (0 <= (start = re_search (&(patterns[i].regexbuf),
buf, end - buf - 1,
beg - buf, end - beg - 1,
&(patterns[i].regs))))
{
len = patterns[i].regs.end[0] - start;
match = buf + start;
if (match > best_match)
continue;
if (start_ptr && !match_words)
goto assess_pattern_match;
if ((!match_lines && !match_words)
|| (match_lines && len == end - beg - 1))
{
match = beg;
len = end - beg;
goto assess_pattern_match;
}
/* If -w, check if the match aligns with word boundaries.
We do this iteratively because:
(a) the line may contain more than one occurence of the
pattern, and
(b) Several alternatives in the pattern might be valid at a
given point, and we may need to consider a shorter one to
find a word boundary. */
if (match_words)
while (match <= best_match)
{
if ((match == buf || !WCHAR ((unsigned char) match[-1]))
&& (start + len == end - buf - 1
|| !WCHAR ((unsigned char) match[len])))
goto assess_pattern_match;
if (len > 0)
{
/* Try a shorter length anchored at the same place. */
--len;
patterns[i].regexbuf.not_eol = 1;
len = re_match (&(patterns[i].regexbuf),
buf, match + len - beg, match - buf,
&(patterns[i].regs));
}
if (len <= 0)
{
/* Try looking further on. */
if (match == end - 1)
break;
match++;
patterns[i].regexbuf.not_eol = 0;
start = re_search (&(patterns[i].regexbuf),
buf, end - buf - 1,
match - buf, end - match - 1,
&(patterns[i].regs));
if (start < 0)
break;
len = patterns[i].regs.end[0] - start;
match = buf + start;
}
} /* while (match <= best_match) */
continue;
assess_pattern_match:
if (!start_ptr)
{
/* Good enough for a non-exact match.
No need to look at further patterns, if any. */
goto success;
}
if (match < best_match || (match == best_match && len > best_len))
{
/* Best exact match: leftmost, then longest. */
best_match = match;
best_len = len;
}
} /* if re_search >= 0 */
} /* for Regex patterns. */
if (best_match < end)
{
/* We have found an exact match. We were just
waiting for the best one (leftmost then longest). */
beg = best_match;
len = best_len;
goto success_in_len;
}
} /* for (beg = end ..) */
failure:
ret_val = -1;
goto out;
success:
len = end - beg;
success_in_len:
*match_size = len;
ret_val = beg - buf;
out:
return ret_val;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: dfaexec (struct dfa *d, char const *begin, char *end,
int allow_nl, int *count, int *backref)
{
int s, s1; /* Current state. */
unsigned char const *p; /* Current input character. */
int **trans, *t; /* Copy of d->trans so it can be optimized
into a register. */
unsigned char eol = eolbyte; /* Likewise for eolbyte. */
unsigned char saved_end;
if (! d->tralloc)
build_state_zero(d);
s = s1 = 0;
p = (unsigned char const *) begin;
trans = d->trans;
saved_end = *(unsigned char *) end;
*end = eol;
if (d->mb_cur_max > 1)
{
MALLOC(mblen_buf, end - begin + 2);
MALLOC(inputwcs, end - begin + 2);
memset(&mbs, 0, sizeof(mbstate_t));
prepare_wc_buf ((const char *) p, end);
}
for (;;)
{
if (d->mb_cur_max > 1)
while ((t = trans[s]) != NULL)
{
if (p > buf_end)
break;
s1 = s;
SKIP_REMAINS_MB_IF_INITIAL_STATE(s, p);
if (d->states[s].mbps.nelem == 0)
{
s = t[*p++];
continue;
}
/* Falling back to the glibc matcher in this case gives
better performance (up to 25% better on [a-z], for
example) and enables support for collating symbols and
equivalence classes. */
if (backref)
{
*backref = 1;
free(mblen_buf);
free(inputwcs);
*end = saved_end;
return (char *) p;
}
/* Can match with a multibyte character (and multi character
collating element). Transition table might be updated. */
s = transit_state(d, s, &p);
trans = d->trans;
}
else
{
while ((t = trans[s]) != NULL)
{
s1 = t[*p++];
if ((t = trans[s1]) == NULL)
{
int tmp = s; s = s1; s1 = tmp; /* swap */
break;
}
s = t[*p++];
}
}
if (s >= 0 && (char *) p <= end && d->fails[s])
{
if (d->success[s] & sbit[*p])
{
if (backref)
*backref = (d->states[s].backref != 0);
if (d->mb_cur_max > 1)
{
free(mblen_buf);
free(inputwcs);
}
*end = saved_end;
return (char *) p;
}
s1 = s;
if (d->mb_cur_max > 1)
{
/* Can match with a multibyte character (and multicharacter
collating element). Transition table might be updated. */
s = transit_state(d, s, &p);
trans = d->trans;
}
else
s = d->fails[s][*p++];
continue;
}
/* If the previous character was a newline, count it. */
if ((char *) p <= end && p[-1] == eol)
{
if (count)
++*count;
if (d->mb_cur_max > 1)
prepare_wc_buf ((const char *) p, end);
}
/* Check if we've run off the end of the buffer. */
if ((char *) p > end)
{
if (d->mb_cur_max > 1)
{
free(mblen_buf);
free(inputwcs);
}
*end = saved_end;
return NULL;
}
if (s >= 0)
{
build_state(s, d);
trans = d->trans;
continue;
}
if (p[-1] == eol && allow_nl)
{
s = d->newlines[s1];
continue;
}
s = 0;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: closure (void)
{
int tindex, ntokens, i;
atom();
while (tok == QMARK || tok == STAR || tok == PLUS || tok == REPMN)
if (tok == REPMN && (minrep || maxrep))
{
ntokens = nsubtoks(dfa->tindex);
tindex = dfa->tindex - ntokens;
if (maxrep < 0)
addtok(PLUS);
if (minrep == 0)
addtok(QMARK);
for (i = 1; i < minrep; ++i)
{
copytoks(tindex, ntokens);
addtok(CAT);
}
for (; i < maxrep; ++i)
{
copytoks(tindex, ntokens);
addtok(QMARK);
addtok(CAT);
}
tok = lex();
}
else if (tok == REPMN)
{
dfa->tindex -= nsubtoks(dfa->tindex);
tok = lex();
closure();
}
else
{
addtok(tok);
tok = lex();
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix some core dumps with long lines etc.
These problems mostly occur because the code attempts to stuff
sizes into int or into unsigned int; this doesn't work on most
64-bit hosts and the errors can lead to core dumps.
* NEWS: Document this.
* src/dfa.c (token): Typedef to ptrdiff_t, since the enum's
range could be as small as -128 .. 127 on practical hosts.
(position.index): Now size_t, not unsigned int.
(leaf_set.elems): Now size_t *, not unsigned int *.
(dfa_state.hash, struct mb_char_classes.nchars, .nch_classes)
(.nranges, .nequivs, .ncoll_elems, struct dfa.cindex, .calloc, .tindex)
(.talloc, .depth, .nleaves, .nregexps, .nmultibyte_prop, .nmbcsets):
(.mbcsets_alloc): Now size_t, not int.
(dfa_state.first_end): Now token, not int.
(state_num): New type.
(struct mb_char_classes.cset): Now ptrdiff_t, not int.
(struct dfa.utf8_anychar_classes): Now token[5], not int[5].
(struct dfa.sindex, .salloc, .tralloc): Now state_num, not int.
(struct dfa.trans, .realtrans, .fails): Now state_num **, not int **.
(struct dfa.newlines): Now state_num *, not int *.
(prtok): Don't assume 'token' is no wider than int.
(lexleft, parens, depth): Now size_t, not int.
(charclass_index, nsubtoks)
(parse_bracket_exp, addtok, copytoks, closure, insert, merge, delete)
(state_index, epsclosure, state_separate_contexts)
(dfaanalyze, dfastate, build_state, realloc_trans_if_necessary)
(transit_state_singlebyte, match_anychar, match_mb_charset)
(check_matching_with_multibyte_ops, transit_state_consume_1char)
(transit_state, dfaexec, free_mbdata, dfaoptimize, dfafree)
(freelist, enlist, addlists, inboth, dfamust):
Don't assume indexes fit in 'int'.
(lex): Avoid overflow in string-to-{hi,lo} conversions.
(dfaanalyze): Redo indexing so that it works with size_t values,
which cannot go negative.
* src/dfa.h (dfaexec): Count argument is now size_t *, not int *.
(dfastate): State numbers are now ptrdiff_t, not int.
* src/dfasearch.c: Include "intprops.h", for TYPE_MAXIMUM.
(kwset_exact_matches): Now size_t, not int.
(EGexecute): Don't assume indexes fit in 'int'.
Check for overflow before converting a ptrdiff_t to a regoff_t,
as regoff_t is narrower than ptrdiff_t in 64-bit glibc (contra POSIX).
Check for memory exhaustion in re_search rather than treating
it merely as failure to match; use xalloc_die () to report any error.
* src/kwset.c (struct trie.accepting): Now size_t, not unsigned int.
(struct kwset.words): Now ptrdiff_t, not int.
* src/kwset.h (struct kwsmatch.index): Now size_t, not int.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: grepfile (char const *file, struct stats *stats)
{
int desc;
int count;
int status;
filename = (file ? file : label ? label : _("(standard input)"));
if (! file)
desc = STDIN_FILENO;
else if (devices == SKIP_DEVICES)
{
/* Don't open yet, since that might have side effects on a device. */
desc = -1;
}
else
{
/* When skipping directories, don't worry about directories
that can't be opened. */
desc = open (file, O_RDONLY);
if (desc < 0 && directories != SKIP_DIRECTORIES)
{
suppressible_error (file, errno);
return 1;
}
}
if (desc < 0
? stat (file, &stats->stat) != 0
: fstat (desc, &stats->stat) != 0)
{
suppressible_error (filename, errno);
if (file)
close (desc);
return 1;
}
if ((directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode))
|| (devices == SKIP_DEVICES && (S_ISCHR (stats->stat.st_mode)
|| S_ISBLK (stats->stat.st_mode)
|| S_ISSOCK (stats->stat.st_mode)
|| S_ISFIFO (stats->stat.st_mode))))
{
if (file)
close (desc);
return 1;
}
/* If there is a regular file on stdout and the current file refers
to the same i-node, we have to report the problem and skip it.
Otherwise when matching lines from some other input reach the
disk before we open this file, we can end up reading and matching
those lines and appending them to the file from which we're reading.
Then we'd have what appears to be an infinite loop that'd terminate
only upon filling the output file system or reaching a quota.
However, there is no risk of an infinite loop if grep is generating
no output, i.e., with --silent, --quiet, -q.
Similarly, with any of these:
--max-count=N (-m) (for N >= 2)
--files-with-matches (-l)
--files-without-match (-L)
there is no risk of trouble.
For --max-count=1, grep stops after printing the first match,
so there is no risk of malfunction. But even --max-count=2, with
input==output, while there is no risk of infloop, there is a race
condition that could result in "alternate" output. */
if (!out_quiet && list_files == 0 && 1 < max_count
&& S_ISREG (out_stat.st_mode) && out_stat.st_ino
&& SAME_INODE (stats->stat, out_stat))
{
if (! suppress_errors)
error (0, 0, _("input file %s is also the output"), quote (filename));
errseen = 1;
if (file)
close (desc);
return 1;
}
if (desc < 0)
{
desc = open (file, O_RDONLY);
if (desc < 0)
{
suppressible_error (file, errno);
return 1;
}
}
#if defined SET_BINARY
/* Set input to binary mode. Pipes are simulated with files
on DOS, so this includes the case of "foo | grep bar". */
if (!isatty (desc))
SET_BINARY (desc);
#endif
count = grep (desc, file, stats);
if (count < 0)
status = count + 2;
else
{
if (count_matches)
{
if (out_file)
{
print_filename ();
if (filename_mask)
print_sep (SEP_CHAR_SELECTED);
else
fputc (0, stdout);
}
printf ("%d\n", count);
}
status = !count;
if (list_files == 1 - 2 * status)
{
print_filename ();
fputc ('\n' & filename_mask, stdout);
}
if (! file)
{
off_t required_offset = outleft ? bufoffset : after_last_match;
if (required_offset != bufoffset
&& lseek (desc, required_offset, SEEK_SET) < 0
&& S_ISREG (stats->stat.st_mode))
suppressible_error (filename, errno);
}
else
while (close (desc) != 0)
if (errno != EINTR)
{
suppressible_error (file, errno);
break;
}
}
return status;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix integer-overflow issues in main program
* NEWS: Document this.
* bootstrap.conf (gnulib_modules): Add inttypes, xstrtoimax.
Remove xstrtoumax.
* src/main.c: Include <inttypes.h>, for INTMAX_MAX, PRIdMAX.
(context_length_arg, prtext, grepbuf, grep, grepfile)
(get_nondigit_option, main):
Use intmax_t, not int, for line counts.
(context_length_arg, main): Silently ceiling line counts
to maximum value, since there's no practical difference between
doing that and using infinite-precision arithmetic.
(out_before, out_after, pending): Now intmax_t, not int.
(max_count, outleft): Now intmax_t, not off_t.
(prepend_args, prepend_default_options, main):
Use size_t, not int, for sizes.
(prepend_default_options): Check for int and size_t overflow.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: prepend_args (char const *options, char *buf, char **argv)
{
char const *o = options;
char *b = buf;
int n = 0;
for (;;)
{
while (c_isspace ((unsigned char) *o))
o++;
if (!*o)
return n;
if (argv)
argv[n] = b;
n++;
do
if ((*b++ = *o++) == '\\' && *o)
b[-1] = *o++;
while (*o && ! c_isspace ((unsigned char) *o));
*b++ = '\0';
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix integer-overflow issues in main program
* NEWS: Document this.
* bootstrap.conf (gnulib_modules): Add inttypes, xstrtoimax.
Remove xstrtoumax.
* src/main.c: Include <inttypes.h>, for INTMAX_MAX, PRIdMAX.
(context_length_arg, prtext, grepbuf, grep, grepfile)
(get_nondigit_option, main):
Use intmax_t, not int, for line counts.
(context_length_arg, main): Silently ceiling line counts
to maximum value, since there's no practical difference between
doing that and using infinite-precision arithmetic.
(out_before, out_after, pending): Now intmax_t, not int.
(max_count, outleft): Now intmax_t, not off_t.
(prepend_args, prepend_default_options, main):
Use size_t, not int, for sizes.
(prepend_default_options): Check for int and size_t overflow.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: prtext (char const *beg, char const *lim, int *nlinesp)
{
static int used; /* avoid printing SEP_STR_GROUP before any output */
char const *bp, *p;
char eol = eolbyte;
int i, n;
if (!out_quiet && pending > 0)
prpending (beg);
p = beg;
if (!out_quiet)
{
/* Deal with leading context crap. */
bp = lastout ? lastout : bufbeg;
for (i = 0; i < out_before; ++i)
if (p > bp)
do
--p;
while (p[-1] != eol);
/* We print the SEP_STR_GROUP separator only if our output is
discontiguous from the last output in the file. */
if ((out_before || out_after) && used && p != lastout && group_separator)
{
pr_sgr_start_if (sep_color);
fputs (group_separator, stdout);
pr_sgr_end_if (sep_color);
fputc ('\n', stdout);
}
while (p < beg)
{
char const *nl = memchr (p, eol, beg - p);
nl++;
prline (p, nl, SEP_CHAR_REJECTED);
p = nl;
}
}
if (nlinesp)
{
/* Caller wants a line count. */
for (n = 0; p < lim && n < outleft; n++)
{
char const *nl = memchr (p, eol, lim - p);
nl++;
if (!out_quiet)
prline (p, nl, SEP_CHAR_SELECTED);
p = nl;
}
*nlinesp = n;
/* relying on it that this function is never called when outleft = 0. */
after_last_match = bufoffset - (buflim - p);
}
else if (!out_quiet)
prline (beg, lim, SEP_CHAR_SELECTED);
pending = out_quiet ? 0 : out_after;
used = 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix integer-overflow issues in main program
* NEWS: Document this.
* bootstrap.conf (gnulib_modules): Add inttypes, xstrtoimax.
Remove xstrtoumax.
* src/main.c: Include <inttypes.h>, for INTMAX_MAX, PRIdMAX.
(context_length_arg, prtext, grepbuf, grep, grepfile)
(get_nondigit_option, main):
Use intmax_t, not int, for line counts.
(context_length_arg, main): Silently ceiling line counts
to maximum value, since there's no practical difference between
doing that and using infinite-precision arithmetic.
(out_before, out_after, pending): Now intmax_t, not int.
(max_count, outleft): Now intmax_t, not off_t.
(prepend_args, prepend_default_options, main):
Use size_t, not int, for sizes.
(prepend_default_options): Check for int and size_t overflow.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: get_nondigit_option (int argc, char *const *argv, int *default_context)
{
static int prev_digit_optind = -1;
int opt, this_digit_optind, was_digit;
char buf[sizeof (uintmax_t) * CHAR_BIT + 4];
char *p = buf;
was_digit = 0;
this_digit_optind = optind;
while (opt = getopt_long (argc, (char **) argv, short_options, long_options,
NULL),
'0' <= opt && opt <= '9')
{
if (prev_digit_optind != this_digit_optind || !was_digit)
{
/* Reset to start another context length argument. */
p = buf;
}
else
{
/* Suppress trivial leading zeros, to avoid incorrect
diagnostic on strings like 00000000000. */
p -= buf[0] == '0';
}
if (p == buf + sizeof buf - 4)
{
/* Too many digits. Append "..." to make context_length_arg
complain about "X...", where X contains the digits seen
so far. */
strcpy (p, "...");
p += 3;
break;
}
*p++ = opt;
was_digit = 1;
prev_digit_optind = this_digit_optind;
this_digit_optind = optind;
}
if (p != buf)
{
*p = '\0';
context_length_arg (buf, default_context);
}
return opt;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'grep: fix integer-overflow issues in main program
* NEWS: Document this.
* bootstrap.conf (gnulib_modules): Add inttypes, xstrtoimax.
Remove xstrtoumax.
* src/main.c: Include <inttypes.h>, for INTMAX_MAX, PRIdMAX.
(context_length_arg, prtext, grepbuf, grep, grepfile)
(get_nondigit_option, main):
Use intmax_t, not int, for line counts.
(context_length_arg, main): Silently ceiling line counts
to maximum value, since there's no practical difference between
doing that and using infinite-precision arithmetic.
(out_before, out_after, pending): Now intmax_t, not int.
(max_count, outleft): Now intmax_t, not off_t.
(prepend_args, prepend_default_options, main):
Use size_t, not int, for sizes.
(prepend_default_options): Check for int and size_t overflow.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: read_block( IOBUF a, PACKET **pending_pkt, KBNODE *ret_root )
{
int rc;
PACKET *pkt;
KBNODE root = NULL;
int in_cert;
if( *pending_pkt ) {
root = new_kbnode( *pending_pkt );
*pending_pkt = NULL;
in_cert = 1;
}
else
in_cert = 0;
pkt = xmalloc( sizeof *pkt );
init_packet(pkt);
while( (rc=parse_packet(a, pkt)) != -1 ) {
if( rc ) { /* ignore errors */
if( rc != G10ERR_UNKNOWN_PACKET ) {
log_error("read_block: read error: %s\n", g10_errstr(rc) );
rc = G10ERR_INV_KEYRING;
goto ready;
}
free_packet( pkt );
init_packet(pkt);
continue;
}
if( !root && pkt->pkttype == PKT_SIGNATURE
&& pkt->pkt.signature->sig_class == 0x20 ) {
/* this is a revocation certificate which is handled
* in a special way */
root = new_kbnode( pkt );
pkt = NULL;
goto ready;
}
/* make a linked list of all packets */
switch( pkt->pkttype ) {
case PKT_COMPRESSED:
if(check_compress_algo(pkt->pkt.compressed->algorithm))
{
rc = G10ERR_COMPR_ALGO;
goto ready;
}
else
{
compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
pkt->pkt.compressed->buf = NULL;
push_compress_filter2(a,cfx,pkt->pkt.compressed->algorithm,1);
}
free_packet( pkt );
init_packet(pkt);
break;
case PKT_RING_TRUST:
/* skip those packets */
free_packet( pkt );
init_packet(pkt);
break;
case PKT_PUBLIC_KEY:
case PKT_SECRET_KEY:
if( in_cert ) { /* store this packet */
*pending_pkt = pkt;
pkt = NULL;
goto ready;
}
in_cert = 1;
default:
if( in_cert ) {
if( !root )
root = new_kbnode( pkt );
else
add_kbnode( root, new_kbnode( pkt ) );
pkt = xmalloc( sizeof *pkt );
}
init_packet(pkt);
break;
}
}
ready:
if( rc == -1 && root )
rc = 0;
if( rc )
release_kbnode( root );
else
*ret_root = root;
free_packet( pkt );
xfree( pkt );
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'gpg: Import only packets which are allowed in a keyblock.
* g10/import.c (valid_keyblock_packet): New.
(read_block): Store only valid packets.
--
A corrupted key, which for example included a mangled public key
encrypted packet, used to corrupt the keyring. This change skips all
packets which are not allowed in a keyblock.
GnuPG-bug-id: 1455
(cherry-picked from commit f795a0d59e197455f8723c300eebf59e09853efa)'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: cib_remote_perform_op(cib_t * cib, const char *op, const char *host, const char *section,
xmlNode * data, xmlNode ** output_data, int call_options, const char *name)
{
int rc = pcmk_ok;
xmlNode *op_msg = NULL;
xmlNode *op_reply = NULL;
cib_remote_opaque_t *private = cib->variant_opaque;
if (sync_timer == NULL) {
sync_timer = calloc(1, sizeof(struct timer_rec_s));
}
if (cib->state == cib_disconnected) {
return -ENOTCONN;
}
if (output_data != NULL) {
*output_data = NULL;
}
if (op == NULL) {
crm_err("No operation specified");
return -EINVAL;
}
cib->call_id++;
/* prevent call_id from being negative (or zero) and conflicting
* with the cib_errors enum
* use 2 because we use it as (cib->call_id - 1) below
*/
if (cib->call_id < 1) {
cib->call_id = 1;
}
op_msg =
cib_create_op(cib->call_id, private->callback.token, op, host, section, data, call_options,
NULL);
if (op_msg == NULL) {
return -EPROTO;
}
crm_trace("Sending %s message to CIB service", op);
crm_send_remote_msg(private->command.session, op_msg, private->command.encrypted);
free_xml(op_msg);
if ((call_options & cib_discard_reply)) {
crm_trace("Discarding reply");
return pcmk_ok;
} else if (!(call_options & cib_sync_call)) {
return cib->call_id;
}
crm_trace("Waiting for a syncronous reply");
if (cib->call_timeout > 0) {
/* We need this, even with msgfromIPC_timeout(), because we might
* get other/older replies that don't match the active request
*/
timer_expired = FALSE;
sync_timer->call_id = cib->call_id;
sync_timer->timeout = cib->call_timeout * 1000;
sync_timer->ref = g_timeout_add(sync_timer->timeout, cib_timeout_handler, sync_timer);
}
while (timer_expired == FALSE) {
int reply_id = -1;
int msg_id = cib->call_id;
op_reply = crm_recv_remote_msg(private->command.session, private->command.encrypted);
if (op_reply == NULL) {
break;
}
crm_element_value_int(op_reply, F_CIB_CALLID, &reply_id);
CRM_CHECK(reply_id > 0, free_xml(op_reply);
if (sync_timer->ref > 0) {
g_source_remove(sync_timer->ref); sync_timer->ref = 0;}
return -ENOMSG) ;
if (reply_id == msg_id) {
break;
} else if (reply_id < msg_id) {
crm_debug("Received old reply: %d (wanted %d)", reply_id, msg_id);
crm_log_xml_trace(op_reply, "Old reply");
} else if ((reply_id - 10000) > msg_id) {
/* wrap-around case */
crm_debug("Received old reply: %d (wanted %d)", reply_id, msg_id);
crm_log_xml_trace(op_reply, "Old reply");
} else {
crm_err("Received a __future__ reply:" " %d (wanted %d)", reply_id, msg_id);
}
free_xml(op_reply);
op_reply = NULL;
}
if (sync_timer->ref > 0) {
g_source_remove(sync_timer->ref);
sync_timer->ref = 0;
}
if (timer_expired) {
return -ETIME;
}
/* if(IPC_ISRCONN(native->command_channel) == FALSE) { */
/* crm_err("CIB disconnected: %d", */
/* native->command_channel->ch_status); */
/* cib->state = cib_disconnected; */
/* } */
if (op_reply == NULL) {
crm_err("No reply message - empty");
return -ENOMSG;
}
crm_trace("Syncronous reply received");
/* Start processing the reply... */
if (crm_element_value_int(op_reply, F_CIB_RC, &rc) != 0) {
rc = -EPROTO;
}
if (rc == -pcmk_err_diff_resync) {
/* This is an internal value that clients do not and should not care about */
rc = pcmk_ok;
}
if (rc == pcmk_ok || rc == -EPERM) {
crm_log_xml_debug(op_reply, "passed");
} else {
/* } else if(rc == -ETIME) { */
crm_err("Call failed: %s", pcmk_strerror(rc));
crm_log_xml_warn(op_reply, "failed");
}
if (output_data == NULL) {
/* do nothing more */
} else if (!(call_options & cib_discard_reply)) {
xmlNode *tmp = get_message_xml(op_reply, F_CIB_CALLDATA);
if (tmp == NULL) {
crm_trace("No output in reply to \"%s\" command %d", op, cib->call_id - 1);
} else {
*output_data = copy_xml(tmp);
}
}
free_xml(op_reply);
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: do_local_notify(xmlNode * notify_src, const char *client_id,
gboolean sync_reply, gboolean from_peer)
{
/* send callback to originating child */
cib_client_t *client_obj = NULL;
int local_rc = pcmk_ok;
if (client_id != NULL) {
client_obj = g_hash_table_lookup(client_list, client_id);
} else {
crm_trace("No client to sent the response to. F_CIB_CLIENTID not set.");
}
if (client_obj == NULL) {
local_rc = -ECONNRESET;
} else {
int rid = 0;
if(sync_reply) {
CRM_LOG_ASSERT(client_obj->request_id);
rid = client_obj->request_id;
client_obj->request_id = 0;
crm_trace("Sending response %d to %s %s",
rid, client_obj->name, from_peer?"(originator of delegated request)":"");
} else {
crm_trace("Sending an event to %s %s",
client_obj->name, from_peer?"(originator of delegated request)":"");
}
if (client_obj->ipc && crm_ipcs_send(client_obj->ipc, rid, notify_src, !sync_reply) < 0) {
local_rc = -ENOMSG;
#ifdef HAVE_GNUTLS_GNUTLS_H
} else if (client_obj->session) {
crm_send_remote_msg(client_obj->session, notify_src, client_obj->encrypted);
#endif
} else if(client_obj->ipc == NULL) {
crm_err("Unknown transport for %s", client_obj->name);
}
}
if (local_rc != pcmk_ok && client_obj != NULL) {
crm_warn("%sSync reply to %s failed: %s",
sync_reply ? "" : "A-",
client_obj ? client_obj->name : "<unknown>", pcmk_strerror(local_rc));
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: cib_remote_connection_destroy(gpointer user_data)
{
cib_client_t *client = user_data;
if (client == NULL) {
return;
}
crm_trace("Cleaning up after client disconnect: %s/%s",
crm_str(client->name), client->id);
if (client->id != NULL) {
if (!g_hash_table_remove(client_list, client->id)) {
crm_err("Client %s not found in the hashtable", client->name);
}
}
crm_trace("Destroying %s (%p)", client->name, user_data);
num_clients--;
crm_trace("Num unfree'd clients: %d", num_clients);
free(client->name);
free(client->callback_id);
free(client->id);
free(client->user);
free(client);
crm_trace("Freed the cib client");
if (cib_shutdown_flag) {
cib_shutdown(0);
}
return;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: cib_tls_close(cib_t * cib)
{
cib_remote_opaque_t *private = cib->variant_opaque;
shutdown(private->command.socket, SHUT_RDWR); /* no more receptions */
shutdown(private->callback.socket, SHUT_RDWR); /* no more receptions */
close(private->command.socket);
close(private->callback.socket);
#ifdef HAVE_GNUTLS_GNUTLS_H
if (private->command.encrypted) {
gnutls_bye(*(private->command.session), GNUTLS_SHUT_RDWR);
gnutls_deinit(*(private->command.session));
gnutls_free(private->command.session);
gnutls_bye(*(private->callback.session), GNUTLS_SHUT_RDWR);
gnutls_deinit(*(private->callback.session));
gnutls_free(private->callback.session);
gnutls_anon_free_client_credentials(anon_cred_c);
gnutls_global_deinit();
}
#endif
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: cib_remote_dispatch(gpointer user_data)
{
cib_t *cib = user_data;
cib_remote_opaque_t *private = cib->variant_opaque;
xmlNode *msg = NULL;
const char *type = NULL;
crm_info("Message on callback channel");
msg = crm_recv_remote_msg(private->callback.session, private->callback.encrypted);
type = crm_element_value(msg, F_TYPE);
crm_trace("Activating %s callbacks...", type);
if (safe_str_eq(type, T_CIB)) {
cib_native_callback(cib, msg, 0, 0);
} else if (safe_str_eq(type, T_CIB_NOTIFY)) {
g_list_foreach(cib->notify_list, cib_native_notify, msg);
} else {
crm_err("Unknown message type: %s", type);
}
if (msg != NULL) {
free_xml(msg);
return 0;
}
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: cib_send_plaintext(int sock, xmlNode * msg)
{
char *xml_text = dump_xml_unformatted(msg);
if (xml_text != NULL) {
int rc = 0;
char *unsent = xml_text;
int len = strlen(xml_text);
len++; /* null char */
crm_trace("Message on socket %d: size=%d", sock, len);
retry:
rc = write(sock, unsent, len);
if (rc < 0) {
switch (errno) {
case EINTR:
case EAGAIN:
crm_trace("Retry");
goto retry;
default:
crm_perror(LOG_ERR, "Could only write %d of the remaining %d bytes", rc, len);
break;
}
} else if (rc < len) {
crm_trace("Only sent %d of %d remaining bytes", rc, len);
len -= rc;
unsent += rc;
goto retry;
} else {
crm_trace("Sent %d bytes: %.100s", rc, xml_text);
}
}
free(xml_text);
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: cib_connect(gboolean full)
{
int rc = pcmk_ok;
static gboolean need_pass = TRUE;
CRM_CHECK(cib != NULL, return -EINVAL);
if (getenv("CIB_passwd") != NULL) {
need_pass = FALSE;
}
if(watch_fencing && st == NULL) {
st = stonith_api_new();
}
if(watch_fencing && st->state == stonith_disconnected) {
crm_trace("Connecting to stonith");
rc = st->cmds->connect(st, crm_system_name, NULL);
if(rc == pcmk_ok) {
crm_trace("Setting up stonith callbacks");
st->cmds->register_notification(st, T_STONITH_NOTIFY_FENCE, mon_st_callback);
}
}
if (cib->state != cib_connected_query && cib->state != cib_connected_command) {
crm_trace("Connecting to the CIB");
if (as_console && need_pass && cib->variant == cib_remote) {
need_pass = FALSE;
print_as("Password:");
}
rc = cib->cmds->signon(cib, crm_system_name, cib_query);
if (rc != pcmk_ok) {
return rc;
}
current_cib = get_cib_copy(cib);
mon_refresh_display(NULL);
if (full) {
if (rc == pcmk_ok) {
rc = cib->cmds->set_connection_dnotify(cib, mon_cib_connection_destroy);
if (rc == -EPROTONOSUPPORT) {
print_as("Notification setup failed, won't be able to reconnect after failure");
if (as_console) {
sleep(2);
}
rc = pcmk_ok;
}
}
if (rc == pcmk_ok) {
cib->cmds->del_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update);
rc = cib->cmds->add_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update);
}
if (rc != pcmk_ok) {
print_as("Notification setup failed, could not monitor CIB actions");
if (as_console) {
sleep(2);
}
clean_up(-rc);
}
}
}
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: cib_timeout_handler(gpointer data)
{
struct timer_rec_s *timer = data;
timer_expired = TRUE;
crm_err("Call %d timed out after %ds", timer->call_id, timer->timeout);
/* Always return TRUE, never remove the handler
* We do that after the while-loop in cib_native_perform_op()
*/
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: cib_tls_signon(cib_t * cib, struct remote_connection_s *connection)
{
int sock;
cib_remote_opaque_t *private = cib->variant_opaque;
struct sockaddr_in addr;
int rc = 0;
char *server = private->server;
int ret_ga;
struct addrinfo *res;
struct addrinfo hints;
xmlNode *answer = NULL;
xmlNode *login = NULL;
static struct mainloop_fd_callbacks cib_fd_callbacks =
{
.dispatch = cib_remote_dispatch,
.destroy = cib_remote_connection_destroy,
};
connection->socket = 0;
connection->session = NULL;
/* create socket */
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == -1) {
crm_perror(LOG_ERR, "Socket creation failed");
return -1;
}
/* getaddrinfo */
bzero(&hints, sizeof(struct addrinfo));
hints.ai_flags = AI_CANONNAME;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_RAW;
if (hints.ai_family == AF_INET6) {
hints.ai_protocol = IPPROTO_ICMPV6;
} else {
hints.ai_protocol = IPPROTO_ICMP;
}
crm_debug("Looking up %s", server);
ret_ga = getaddrinfo(server, NULL, &hints, &res);
if (ret_ga) {
crm_err("getaddrinfo: %s", gai_strerror(ret_ga));
close(sock);
return -1;
}
if (res->ai_canonname) {
server = res->ai_canonname;
}
crm_debug("Got address %s for %s", server, private->server);
if (!res->ai_addr) {
fprintf(stderr, "getaddrinfo failed");
crm_exit(1);
}
#if 1
memcpy(&addr, res->ai_addr, res->ai_addrlen);
#else
/* connect to server */
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(server);
#endif
addr.sin_port = htons(private->port);
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
crm_perror(LOG_ERR, "Connection to %s:%d failed", server, private->port);
close(sock);
return -1;
}
if (connection->encrypted) {
/* initialize GnuTls lib */
#ifdef HAVE_GNUTLS_GNUTLS_H
gnutls_global_init();
gnutls_anon_allocate_client_credentials(&anon_cred_c);
/* bind the socket to GnuTls lib */
connection->session = create_tls_session(sock, GNUTLS_CLIENT);
if (connection->session == NULL) {
crm_perror(LOG_ERR, "Session creation for %s:%d failed", server, private->port);
close(sock);
cib_tls_close(cib);
return -1;
}
#else
return -EPROTONOSUPPORT;
#endif
} else {
connection->session = GUINT_TO_POINTER(sock);
}
/* login to server */
login = create_xml_node(NULL, "cib_command");
crm_xml_add(login, "op", "authenticate");
crm_xml_add(login, "user", private->user);
crm_xml_add(login, "password", private->passwd);
crm_xml_add(login, "hidden", "password");
crm_send_remote_msg(connection->session, login, connection->encrypted);
free_xml(login);
answer = crm_recv_remote_msg(connection->session, connection->encrypted);
crm_log_xml_trace(answer, "Reply");
if (answer == NULL) {
rc = -EPROTO;
} else {
/* grab the token */
const char *msg_type = crm_element_value(answer, F_CIB_OPERATION);
const char *tmp_ticket = crm_element_value(answer, F_CIB_CLIENTID);
if (safe_str_neq(msg_type, CRM_OP_REGISTER)) {
crm_err("Invalid registration message: %s", msg_type);
rc = -EPROTO;
} else if (tmp_ticket == NULL) {
rc = -EPROTO;
} else {
connection->token = strdup(tmp_ticket);
}
}
if (rc != 0) {
cib_tls_close(cib);
}
connection->socket = sock;
connection->source = mainloop_add_fd("cib-remote", G_PRIORITY_HIGH, connection->socket, cib, &cib_fd_callbacks);
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: create_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */ )
{
int rc = 0;
gnutls_session *session = gnutls_malloc(sizeof(gnutls_session));
gnutls_init(session, type);
# ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT
/* http://www.manpagez.com/info/gnutls/gnutls-2.10.4/gnutls_81.php#Echo-Server-with-anonymous-authentication */
gnutls_priority_set_direct(*session, "NORMAL:+ANON-DH", NULL);
/* gnutls_priority_set_direct (*session, "NONE:+VERS-TLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH", NULL); */
# else
gnutls_set_default_priority(*session);
gnutls_kx_set_priority(*session, tls_kx_order);
# endif
gnutls_transport_set_ptr(*session, (gnutls_transport_ptr) GINT_TO_POINTER(csock));
switch (type) {
case GNUTLS_SERVER:
gnutls_credentials_set(*session, GNUTLS_CRD_ANON, anon_cred_s);
break;
case GNUTLS_CLIENT:
gnutls_credentials_set(*session, GNUTLS_CRD_ANON, anon_cred_c);
break;
}
do {
rc = gnutls_handshake(*session);
} while (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN);
if (rc < 0) {
crm_err("Handshake failed: %s", gnutls_strerror(rc));
gnutls_deinit(*session);
gnutls_free(session);
return NULL;
}
return session;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'High: core: Internal tls api improvements for reuse with future LRMD tls backend.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc, char **argv)
{
int c, rc = MOUNT_EX_SUCCESS, all = 0, show_labels = 0;
struct libmnt_context *cxt;
struct libmnt_table *fstab = NULL;
char *srcbuf = NULL;
char *types = NULL;
unsigned long oper = 0;
enum {
MOUNT_OPT_SHARED = CHAR_MAX + 1,
MOUNT_OPT_SLAVE,
MOUNT_OPT_PRIVATE,
MOUNT_OPT_UNBINDABLE,
MOUNT_OPT_RSHARED,
MOUNT_OPT_RSLAVE,
MOUNT_OPT_RPRIVATE,
MOUNT_OPT_RUNBINDABLE,
MOUNT_OPT_TARGET,
MOUNT_OPT_SOURCE
};
static const struct option longopts[] = {
{ "all", 0, 0, 'a' },
{ "fake", 0, 0, 'f' },
{ "fstab", 1, 0, 'T' },
{ "fork", 0, 0, 'F' },
{ "help", 0, 0, 'h' },
{ "no-mtab", 0, 0, 'n' },
{ "read-only", 0, 0, 'r' },
{ "ro", 0, 0, 'r' },
{ "verbose", 0, 0, 'v' },
{ "version", 0, 0, 'V' },
{ "read-write", 0, 0, 'w' },
{ "rw", 0, 0, 'w' },
{ "options", 1, 0, 'o' },
{ "test-opts", 1, 0, 'O' },
{ "pass-fd", 1, 0, 'p' },
{ "types", 1, 0, 't' },
{ "uuid", 1, 0, 'U' },
{ "label", 1, 0, 'L'},
{ "bind", 0, 0, 'B' },
{ "move", 0, 0, 'M' },
{ "rbind", 0, 0, 'R' },
{ "make-shared", 0, 0, MOUNT_OPT_SHARED },
{ "make-slave", 0, 0, MOUNT_OPT_SLAVE },
{ "make-private", 0, 0, MOUNT_OPT_PRIVATE },
{ "make-unbindable", 0, 0, MOUNT_OPT_UNBINDABLE },
{ "make-rshared", 0, 0, MOUNT_OPT_RSHARED },
{ "make-rslave", 0, 0, MOUNT_OPT_RSLAVE },
{ "make-rprivate", 0, 0, MOUNT_OPT_RPRIVATE },
{ "make-runbindable", 0, 0, MOUNT_OPT_RUNBINDABLE },
{ "no-canonicalize", 0, 0, 'c' },
{ "internal-only", 0, 0, 'i' },
{ "show-labels", 0, 0, 'l' },
{ "target", 1, 0, MOUNT_OPT_TARGET },
{ "source", 1, 0, MOUNT_OPT_SOURCE },
{ NULL, 0, 0, 0 }
};
static const ul_excl_t excl[] = { /* rows and cols in in ASCII order */
{ 'B','M','R', /* bind,move,rbind */
MOUNT_OPT_SHARED, MOUNT_OPT_SLAVE,
MOUNT_OPT_PRIVATE, MOUNT_OPT_UNBINDABLE,
MOUNT_OPT_RSHARED, MOUNT_OPT_RSLAVE,
MOUNT_OPT_RPRIVATE, MOUNT_OPT_RUNBINDABLE },
{ 'L','U', MOUNT_OPT_SOURCE }, /* label,uuid,source */
{ 0 }
};
int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
sanitize_env();
setlocale(LC_ALL, "");
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
atexit(close_stdout);
mnt_init_debug(0);
cxt = mnt_new_context();
if (!cxt)
err(MOUNT_EX_SYSERR, _("libmount context allocation failed"));
mnt_context_set_tables_errcb(cxt, table_parser_errcb);
while ((c = getopt_long(argc, argv, "aBcfFhilL:Mno:O:p:rRsU:vVwt:T:",
longopts, NULL)) != -1) {
/* only few options are allowed for non-root users */
if (mnt_context_is_restricted(cxt) &&
!strchr("hlLUVvpris", c) &&
c != MOUNT_OPT_TARGET &&
c != MOUNT_OPT_SOURCE)
exit_non_root(option_to_longopt(c, longopts));
err_exclusive_options(c, longopts, excl, excl_st);
switch(c) {
case 'a':
all = 1;
break;
case 'c':
mnt_context_disable_canonicalize(cxt, TRUE);
break;
case 'f':
mnt_context_enable_fake(cxt, TRUE);
break;
case 'F':
mnt_context_enable_fork(cxt, TRUE);
break;
case 'h':
usage(stdout);
break;
case 'i':
mnt_context_disable_helpers(cxt, TRUE);
break;
case 'n':
mnt_context_disable_mtab(cxt, TRUE);
break;
case 'r':
if (mnt_context_append_options(cxt, "ro"))
err(MOUNT_EX_SYSERR, _("failed to append options"));
readwrite = 0;
break;
case 'v':
mnt_context_enable_verbose(cxt, TRUE);
break;
case 'V':
print_version();
break;
case 'w':
if (mnt_context_append_options(cxt, "rw"))
err(MOUNT_EX_SYSERR, _("failed to append options"));
readwrite = 1;
break;
case 'o':
if (mnt_context_append_options(cxt, optarg))
err(MOUNT_EX_SYSERR, _("failed to append options"));
break;
case 'O':
if (mnt_context_set_options_pattern(cxt, optarg))
err(MOUNT_EX_SYSERR, _("failed to set options pattern"));
break;
case 'p':
warnx(_("--pass-fd is no longer supported"));
break;
case 'L':
xasprintf(&srcbuf, "LABEL=\"%s\"", optarg);
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_source(cxt, srcbuf);
free(srcbuf);
break;
case 'U':
xasprintf(&srcbuf, "UUID=\"%s\"", optarg);
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_source(cxt, srcbuf);
free(srcbuf);
break;
case 'l':
show_labels = 1;
break;
case 't':
types = optarg;
break;
case 'T':
fstab = append_fstab(cxt, fstab, optarg);
break;
case 's':
mnt_context_enable_sloppy(cxt, TRUE);
break;
case 'B':
oper |= MS_BIND;
break;
case 'M':
oper |= MS_MOVE;
break;
case 'R':
oper |= (MS_BIND | MS_REC);
break;
case MOUNT_OPT_SHARED:
oper |= MS_SHARED;
break;
case MOUNT_OPT_SLAVE:
oper |= MS_SLAVE;
break;
case MOUNT_OPT_PRIVATE:
oper |= MS_PRIVATE;
break;
case MOUNT_OPT_UNBINDABLE:
oper |= MS_UNBINDABLE;
break;
case MOUNT_OPT_RSHARED:
oper |= (MS_SHARED | MS_REC);
break;
case MOUNT_OPT_RSLAVE:
oper |= (MS_SLAVE | MS_REC);
break;
case MOUNT_OPT_RPRIVATE:
oper |= (MS_PRIVATE | MS_REC);
break;
case MOUNT_OPT_RUNBINDABLE:
oper |= (MS_UNBINDABLE | MS_REC);
break;
case MOUNT_OPT_TARGET:
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_target(cxt, optarg);
break;
case MOUNT_OPT_SOURCE:
mnt_context_disable_swapmatch(cxt, 1);
mnt_context_set_source(cxt, optarg);
break;
default:
usage(stderr);
break;
}
}
argc -= optind;
argv += optind;
if (fstab && !mnt_context_is_nocanonicalize(cxt)) {
/*
* We have external (context independent) fstab instance, let's
* make a connection between the fstab and the canonicalization
* cache.
*/
struct libmnt_cache *cache = mnt_context_get_cache(cxt);
mnt_table_set_cache(fstab, cache);
}
if (!mnt_context_get_source(cxt) &&
!mnt_context_get_target(cxt) &&
!argc &&
!all) {
if (oper)
usage(stderr);
print_all(cxt, types, show_labels);
goto done;
}
if (oper && (types || all || mnt_context_get_source(cxt)))
usage(stderr);
if (types && (all || strchr(types, ',') ||
strncmp(types, "no", 2) == 0))
mnt_context_set_fstype_pattern(cxt, types);
else if (types)
mnt_context_set_fstype(cxt, types);
if (all) {
/*
* A) Mount all
*/
rc = mount_all(cxt);
goto done;
} else if (argc == 0 && (mnt_context_get_source(cxt) ||
mnt_context_get_target(cxt))) {
/*
* B) mount -L|-U|--source|--target
*/
if (mnt_context_is_restricted(cxt) &&
mnt_context_get_source(cxt) &&
mnt_context_get_target(cxt))
exit_non_root(NULL);
} else if (argc == 1) {
/*
* C) mount [-L|-U|--source] <target>
* mount <source|target>
*
* non-root may specify source *or* target, but not both
*/
if (mnt_context_is_restricted(cxt) &&
mnt_context_get_source(cxt))
exit_non_root(NULL);
mnt_context_set_target(cxt, argv[0]);
} else if (argc == 2 && !mnt_context_get_source(cxt)
&& !mnt_context_get_target(cxt)) {
/*
* D) mount <source> <target>
*/
if (mnt_context_is_restricted(cxt))
exit_non_root(NULL);
mnt_context_set_source(cxt, argv[0]);
mnt_context_set_target(cxt, argv[1]);
} else
usage(stderr);
if (oper) {
/* MS_PROPAGATION operations, let's set the mount flags */
mnt_context_set_mflags(cxt, oper);
/* For -make* or --bind is fstab unnecessary */
mnt_context_set_optsmode(cxt, MNT_OMODE_NOTAB);
}
rc = mnt_context_mount(cxt);
rc = mk_exit_code(cxt, rc);
if (rc == MOUNT_EX_SUCCESS && mnt_context_is_verbose(cxt))
success_message(cxt);
done:
mnt_free_context(cxt);
mnt_free_table(fstab);
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'mount: sanitize paths from non-root users
$ mount /root/.ssh/../../dev/sda2
mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot
this is too promiscuous. It seems better to ignore on command line
specified paths which are not resolve-able for non-root users.
Fixed version:
$ mount /root/.ssh/../../dev/sda2
mount: /root/.ssh/../../dev/sda2: Permission denied
$ mount /dev/sda2
mount: only root can mount UUID=17bc65ec-4125-4e7c-8a7d-e2795064c736 on /boot
Note that this bug has no relation to mount(2) permissions evaluation
in suid mode. The way how non-root user specifies paths on command
line is completely irrelevant for comparison with fstab entries.
Signed-off-by: Karel Zak <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: main(int argc, char *argv[]) {
int c, result = 0, specseen;
char *options = NULL, *test_opts = NULL, *node;
const char *spec = NULL;
char *label = NULL;
char *uuid = NULL;
char *types = NULL;
char *p;
struct mntentchn *mc;
int fd;
sanitize_env();
setlocale(LC_ALL, "");
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
atexit(close_stdout);
progname = argv[0];
if ((p = strrchr(progname, '/')) != NULL)
progname = p+1;
umask(022);
/* People report that a mount called from init without console
writes error messages to /etc/mtab
Let us try to avoid getting fd's 0,1,2 */
while((fd = open("/dev/null", O_RDWR)) == 0 || fd == 1 || fd == 2) ;
if (fd > 2)
close(fd);
fsprobe_init();
#ifdef DO_PS_FIDDLING
initproctitle(argc, argv);
#endif
while ((c = getopt_long (argc, argv, "aBfFhilL:Mno:O:p:rRsU:vVwt:",
longopts, NULL)) != -1) {
switch (c) {
case 'a': /* mount everything in fstab */
++mount_all;
break;
case 'B': /* bind */
mounttype = MS_BIND;
break;
case 'f': /* fake: don't actually call mount(2) */
++fake;
break;
case 'F':
++optfork;
break;
case 'h': /* help */
usage (stdout, 0);
break;
case 'i':
external_allowed = 0;
break;
case 'l':
list_with_volumelabel = 1;
break;
case 'L':
label = optarg;
break;
case 'M': /* move */
mounttype = MS_MOVE;
break;
case 'n': /* do not write /etc/mtab */
++nomtab;
break;
case 'o': /* specify mount options */
options = append_opt(options, optarg, NULL);
break;
case 'O': /* with -t: mount only if (not) opt */
test_opts = append_opt(test_opts, optarg, NULL);
break;
case 'p': /* fd on which to read passwd */
error("mount: %s", _("--pass-fd is no longer supported"));
break;
case 'r': /* mount readonly */
readonly = 1;
readwrite = 0;
break;
case 'R': /* rbind */
mounttype = (MS_BIND | MS_REC);
break;
case 's': /* allow sloppy mount options */
sloppy = 1;
break;
case 't': /* specify file system types */
types = optarg;
break;
case 'U':
uuid = optarg;
break;
case 'v': /* be chatty - more so if repeated */
++verbose;
break;
case 'V': /* version */
print_version(EXIT_SUCCESS);
break;
case 'w': /* mount read/write */
readwrite = 1;
readonly = 0;
break;
case 0:
break;
case 134:
/* undocumented, may go away again:
call: mount --guess-fstype device
use only for testing purposes -
the guessing is not reliable at all */
{
const char *fstype;
fstype = fsprobe_get_fstype_by_devname(optarg);
printf("%s\n", fstype ? fstype : "unknown");
exit(fstype ? 0 : EX_FAIL);
}
case 136:
mounttype = MS_SHARED;
break;
case 137:
mounttype = MS_SLAVE;
break;
case 138:
mounttype = MS_PRIVATE;
break;
case 139:
mounttype = MS_UNBINDABLE;
break;
case 140:
mounttype = (MS_SHARED | MS_REC);
break;
case 141:
mounttype = (MS_SLAVE | MS_REC);
break;
case 142:
mounttype = (MS_PRIVATE | MS_REC);
break;
case 143:
mounttype = (MS_UNBINDABLE | MS_REC);
break;
case 144:
nocanonicalize = 1;
break;
case '?':
default:
usage (stderr, EX_USAGE);
}
}
if (verbose > 2) {
printf("mount: fstab path: \"%s\"\n", _PATH_MNTTAB);
printf("mount: mtab path: \"%s\"\n", _PATH_MOUNTED);
printf("mount: lock path: \"%s\"\n", _PATH_MOUNTED_LOCK);
printf("mount: temp path: \"%s\"\n", _PATH_MOUNTED_TMP);
printf("mount: UID: %u\n", getuid());
printf("mount: eUID: %u\n", geteuid());
}
argc -= optind;
argv += optind;
specseen = (uuid || label) ? 1 : 0; /* yes, .. i know */
if (argc+specseen == 0 && !mount_all) {
if (options || mounttype)
usage (stderr, EX_USAGE);
return print_all (types);
}
{
const uid_t ruid = getuid();
const uid_t euid = geteuid();
/* if we're really root and aren't running setuid */
if (((uid_t)0 == ruid) && (ruid == euid)) {
restricted = 0;
}
if (restricted &&
(types || options || readwrite || nomtab || mount_all ||
nocanonicalize || fake || mounttype ||
(argc + specseen) != 1)) {
if (ruid == 0 && euid != 0)
/* user is root, but setuid to non-root */
die (EX_USAGE, _("mount: only root can do that "
"(effective UID is %u)"), euid);
die (EX_USAGE, _("mount: only root can do that"));
}
}
atexit(unlock_mtab);
switch (argc+specseen) {
case 0:
/* mount -a */
result = do_mount_all (types, options, test_opts);
if (result == 0 && verbose && !fake)
error(_("nothing was mounted"));
break;
case 1:
/* mount [-nfrvw] [-o options] special | node
* mount -L label (or -U uuid)
* (/etc/fstab is necessary)
*/
if (types != NULL)
usage (stderr, EX_USAGE);
if (uuid || label)
mc = getfs(NULL, uuid, label);
else
mc = getfs(*argv, NULL, NULL);
if (!mc) {
if (uuid || label)
die (EX_USAGE, _("mount: no such partition found"));
die (EX_USAGE,
_("mount: can't find %s in %s or %s"),
*argv, _PATH_MNTTAB, _PATH_MOUNTED);
}
result = mount_one (xstrdup (mc->m.mnt_fsname),
xstrdup (mc->m.mnt_dir),
xstrdup (mc->m.mnt_type),
mc->m.mnt_opts, options, 0, 0);
break;
case 2:
/* mount special node (/etc/fstab is not necessary) */
if (specseen) {
/* mount -L label node (or -U uuid) */
spec = uuid ? fsprobe_get_devname_by_uuid(uuid) :
fsprobe_get_devname_by_label(label);
node = argv[0];
} else {
/* mount special node */
spec = argv[0];
node = argv[1];
}
if (!spec)
die (EX_USAGE, _("mount: no such partition found"));
result = mount_one (spec, node, types, NULL, options, 0, 0);
break;
default:
usage (stderr, EX_USAGE);
}
if (result == EX_SOMEOK)
result = 0;
fsprobe_exit();
exit (result);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'mount: (deprecated) drop --guess-fstype
The option is undocumented and unnecessary.
Signed-off-by: Karel Zak <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void set_cron_watched(int fd) {
pid_t pid = getpid();
int i;
if (fd < 0) {
inotify_enabled = 0;
return;
}
for (i = 0; i < sizeof (wd) / sizeof (wd[0]); ++i) {
int w;
if (open(watchpaths[i], O_RDONLY | O_NONBLOCK, 0) != -1) {
w = inotify_add_watch(fd, watchpaths[i],
IN_CREATE | IN_CLOSE_WRITE | IN_ATTRIB | IN_MODIFY | IN_MOVED_TO |
IN_MOVED_FROM | IN_MOVE_SELF | IN_DELETE | IN_DELETE_SELF);
if (w < 0) {
if (wd[i] != -1) {
log_it("CRON", pid, "This directory or file can't be watched",
watchpaths[i], errno);
log_it("CRON", pid, "INFO", "running without inotify support", 0);
}
inotify_enabled = 0;
set_cron_unwatched(fd);
return;
}
wd[i] = w;
}
}
if (!inotify_enabled) {
log_it("CRON", pid, "INFO", "running with inotify support", 0);
}
inotify_enabled = 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Revert "Cronie disables inotify support when the /etc/crontab file does not exist at startup."
This reverts commit acdf4ae8456888ed78201906ef528f4c28f54582 as it introduces
fd leaks.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: build_object (GoaProvider *provider,
GoaObjectSkeleton *object,
GKeyFile *key_file,
const gchar *group,
GDBusConnection *connection,
gboolean just_added,
GError **error)
{
GoaAccount *account;
GoaCalendar *calendar;
GoaContacts *contacts;
GoaFiles *files;
GoaPasswordBased *password_based;
SoupURI *uri;
gboolean calendar_enabled;
gboolean contacts_enabled;
gboolean files_enabled;
gboolean ret;
const gchar *identity;
gchar *uri_string;
account = NULL;
calendar = NULL;
contacts = NULL;
files = NULL;
password_based = NULL;
uri = NULL;
uri_string = NULL;
ret = FALSE;
/* Chain up */
if (!GOA_PROVIDER_CLASS (goa_owncloud_provider_parent_class)->build_object (provider,
object,
key_file,
group,
connection,
just_added,
error))
goto out;
password_based = goa_object_get_password_based (GOA_OBJECT (object));
if (password_based == NULL)
{
password_based = goa_password_based_skeleton_new ();
/* Ensure D-Bus method invocations run in their own thread */
g_dbus_interface_skeleton_set_flags (G_DBUS_INTERFACE_SKELETON (password_based),
G_DBUS_INTERFACE_SKELETON_FLAGS_HANDLE_METHOD_INVOCATIONS_IN_THREAD);
goa_object_skeleton_set_password_based (object, password_based);
g_signal_connect (password_based,
"handle-get-password",
G_CALLBACK (on_handle_get_password),
NULL);
}
account = goa_object_get_account (GOA_OBJECT (object));
identity = goa_account_get_identity (account);
uri_string = g_key_file_get_string (key_file, group, "Uri", NULL);
uri = soup_uri_new (uri_string);
if (uri != NULL)
soup_uri_set_user (uri, identity);
/* Calendar */
calendar = goa_object_get_calendar (GOA_OBJECT (object));
calendar_enabled = g_key_file_get_boolean (key_file, group, "CalendarEnabled", NULL);
if (calendar_enabled)
{
if (calendar == NULL)
{
gchar *uri_caldav;
uri_caldav = NULL;
if (uri != NULL)
{
gchar *uri_tmp;
uri_tmp = soup_uri_to_string (uri, FALSE);
uri_caldav = g_strconcat (uri_tmp, CALDAV_ENDPOINT, NULL);
g_free (uri_tmp);
}
calendar = goa_calendar_skeleton_new ();
g_object_set (G_OBJECT (calendar), "uri", uri_caldav, NULL);
goa_object_skeleton_set_calendar (object, calendar);
g_free (uri_caldav);
}
}
else
{
if (calendar != NULL)
goa_object_skeleton_set_calendar (object, NULL);
}
/* Contacts */
contacts = goa_object_get_contacts (GOA_OBJECT (object));
contacts_enabled = g_key_file_get_boolean (key_file, group, "ContactsEnabled", NULL);
if (contacts_enabled)
{
if (contacts == NULL)
{
gchar *uri_carddav;
uri_carddav = NULL;
if (uri != NULL)
{
gchar *uri_tmp;
uri_tmp = soup_uri_to_string (uri, FALSE);
uri_carddav = g_strconcat (uri_tmp, CARDDAV_ENDPOINT, NULL);
g_free (uri_tmp);
}
contacts = goa_contacts_skeleton_new ();
g_object_set (G_OBJECT (contacts), "uri", uri_carddav, NULL);
goa_object_skeleton_set_contacts (object, contacts);
g_free (uri_carddav);
}
}
else
{
if (contacts != NULL)
goa_object_skeleton_set_contacts (object, NULL);
}
/* Files */
files = goa_object_get_files (GOA_OBJECT (object));
files_enabled = g_key_file_get_boolean (key_file, group, "FilesEnabled", NULL);
if (files_enabled)
{
if (files == NULL)
{
gchar *uri_webdav;
uri_webdav = NULL;
if (uri != NULL)
{
const gchar *scheme;
gchar *uri_tmp;
scheme = soup_uri_get_scheme (uri);
if (g_strcmp0 (scheme, SOUP_URI_SCHEME_HTTPS) == 0)
soup_uri_set_scheme (uri, "davs");
else
soup_uri_set_scheme (uri, "dav");
uri_tmp = soup_uri_to_string (uri, FALSE);
uri_webdav = g_strconcat (uri_tmp, WEBDAV_ENDPOINT, NULL);
g_free (uri_tmp);
}
files = goa_files_skeleton_new ();
g_object_set (G_OBJECT (files), "uri", uri_webdav, NULL);
goa_object_skeleton_set_files (object, files);
g_free (uri_webdav);
}
}
else
{
if (files != NULL)
goa_object_skeleton_set_files (object, NULL);
}
if (just_added)
{
goa_account_set_calendar_disabled (account, !calendar_enabled);
goa_account_set_contacts_disabled (account, !contacts_enabled);
goa_account_set_files_disabled (account, !files_enabled);
g_signal_connect (account,
"notify::calendar-disabled",
G_CALLBACK (goa_util_account_notify_property_cb),
"CalendarEnabled");
g_signal_connect (account,
"notify::contacts-disabled",
G_CALLBACK (goa_util_account_notify_property_cb),
"ContactsEnabled");
g_signal_connect (account,
"notify::files-disabled",
G_CALLBACK (goa_util_account_notify_property_cb),
"FilesEnabled");
}
ret = TRUE;
out:
g_clear_object (&calendar);
g_clear_object (&contacts);
g_clear_object (&files);
g_clear_object (&password_based);
g_clear_pointer (&uri, (GDestroyNotify *) soup_uri_free);
g_free (uri_string);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
None of the branded providers (eg., Google, Facebook and Windows Live)
should ever have an invalid certificate. So set "ssl-strict" on the
SoupSession object being used by GoaWebView.
Providers like ownCloud and Exchange might have to deal with
certificates that are not up to the mark. eg., self-signed
certificates. For those, show a warning when the account is being
created, and only proceed if the user decides to ignore it. In any
case, save the status of the certificate that was used to create the
account. So an account created with a valid certificate will never
work with an invalid one, and one created with an invalid certificate
will not throw any further warnings.
Fixes: CVE-2013-0240'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: http_client_check_response_cb (SoupSession *session, SoupMessage *msg, gpointer user_data)
{
GError *error;
CheckData *data = user_data;
gboolean op_res;
error = NULL;
op_res = FALSE;
if (msg->status_code == SOUP_STATUS_CANCELLED)
goto out;
else if (msg->status_code != SOUP_STATUS_OK)
{
g_set_error (&error,
GOA_ERROR,
GOA_ERROR_FAILED, /* TODO: more specific */
_("Code: %u - Unexpected response from server"),
msg->status_code);
goto out;
}
op_res = TRUE;
out:
g_simple_async_result_set_op_res_gboolean (data->res, op_res);
if (error != NULL)
g_simple_async_result_take_error (data->res, error);
g_simple_async_result_complete_in_idle (data->res);
g_idle_add (http_client_check_data_free, data);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
None of the branded providers (eg., Google, Facebook and Windows Live)
should ever have an invalid certificate. So set "ssl-strict" on the
SoupSession object being used by GoaWebView.
Providers like ownCloud and Exchange might have to deal with
certificates that are not up to the mark. eg., self-signed
certificates. For those, show a warning when the account is being
created, and only proceed if the user decides to ignore it. In any
case, save the status of the certificate that was used to create the
account. So an account created with a valid certificate will never
work with an invalid one, and one created with an invalid certificate
will not throw any further warnings.
Fixes: CVE-2013-0240'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: refresh_account (GoaProvider *provider,
GoaClient *client,
GoaObject *object,
GtkWindow *parent,
GError **error)
{
AddAccountData data;
GVariantBuilder builder;
GoaAccount *account;
GoaHttpClient *http_client;
GtkWidget *dialog;
GtkWidget *vbox;
gboolean ret;
const gchar *password;
const gchar *username;
gchar *uri;
gchar *uri_webdav;
gint response;
g_return_val_if_fail (GOA_IS_OWNCLOUD_PROVIDER (provider), FALSE);
g_return_val_if_fail (GOA_IS_CLIENT (client), FALSE);
g_return_val_if_fail (GOA_IS_OBJECT (object), FALSE);
g_return_val_if_fail (parent == NULL || GTK_IS_WINDOW (parent), FALSE);
g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
http_client = NULL;
uri = NULL;
uri_webdav = NULL;
ret = FALSE;
dialog = gtk_dialog_new_with_buttons (NULL,
parent,
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
NULL);
gtk_container_set_border_width (GTK_CONTAINER (dialog), 12);
gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);
gtk_window_set_resizable (GTK_WINDOW (dialog), FALSE);
vbox = gtk_dialog_get_content_area (GTK_DIALOG (dialog));
gtk_box_set_spacing (GTK_BOX (vbox), 12);
memset (&data, 0, sizeof (AddAccountData));
data.cancellable = g_cancellable_new ();
data.loop = g_main_loop_new (NULL, FALSE);
data.dialog = GTK_DIALOG (dialog);
data.error = NULL;
create_account_details_ui (provider, GTK_DIALOG (dialog), GTK_BOX (vbox), FALSE, &data);
uri = goa_util_lookup_keyfile_string (object, "Uri");
gtk_entry_set_text (GTK_ENTRY (data.uri), uri);
gtk_editable_set_editable (GTK_EDITABLE (data.uri), FALSE);
account = goa_object_peek_account (object);
username = goa_account_get_identity (account);
gtk_entry_set_text (GTK_ENTRY (data.username), username);
gtk_editable_set_editable (GTK_EDITABLE (data.username), FALSE);
gtk_widget_show_all (dialog);
g_signal_connect (dialog, "response", G_CALLBACK (dialog_response_cb), &data);
http_client = goa_http_client_new ();
uri_webdav = g_strconcat (uri, WEBDAV_ENDPOINT, NULL);
http_again:
response = gtk_dialog_run (GTK_DIALOG (dialog));
if (response != GTK_RESPONSE_OK)
{
g_set_error (&data.error,
GOA_ERROR,
GOA_ERROR_DIALOG_DISMISSED,
_("Dialog was dismissed"));
goto out;
}
password = gtk_entry_get_text (GTK_ENTRY (data.password));
g_cancellable_reset (data.cancellable);
goa_http_client_check (http_client,
uri_webdav,
username,
password,
data.cancellable,
check_cb,
&data);
gtk_widget_set_sensitive (data.connect_button, FALSE);
gtk_widget_show (data.progress_grid);
g_main_loop_run (data.loop);
if (g_cancellable_is_cancelled (data.cancellable))
{
g_prefix_error (&data.error,
_("Dialog was dismissed (%s, %d): "),
g_quark_to_string (data.error->domain),
data.error->code);
data.error->domain = GOA_ERROR;
data.error->code = GOA_ERROR_DIALOG_DISMISSED;
goto out;
}
else if (data.error != NULL)
{
gchar *markup;
markup = g_strdup_printf ("<b>%s:</b> %s",
_("Error connecting to ownCloud server"),
data.error->message);
g_clear_error (&data.error);
gtk_label_set_markup (GTK_LABEL (data.cluebar_label), markup);
g_free (markup);
gtk_button_set_label (GTK_BUTTON (data.connect_button), _("_Try Again"));
gtk_widget_set_no_show_all (data.cluebar, FALSE);
gtk_widget_show_all (data.cluebar);
goto http_again;
}
/* TODO: run in worker thread */
g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add (&builder, "{sv}", "password", g_variant_new_string (password));
if (!goa_utils_store_credentials_for_object_sync (provider,
object,
g_variant_builder_end (&builder),
NULL, /* GCancellable */
&data.error))
goto out;
goa_account_call_ensure_credentials (account,
NULL, /* GCancellable */
NULL, NULL); /* callback, user_data */
ret = TRUE;
out:
if (data.error != NULL)
g_propagate_error (error, data.error);
gtk_widget_destroy (dialog);
g_free (uri);
g_free (uri_webdav);
if (data.loop != NULL)
g_main_loop_unref (data.loop);
g_clear_object (&data.cancellable);
g_clear_object (&http_client);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
None of the branded providers (eg., Google, Facebook and Windows Live)
should ever have an invalid certificate. So set "ssl-strict" on the
SoupSession object being used by GoaWebView.
Providers like ownCloud and Exchange might have to deal with
certificates that are not up to the mark. eg., self-signed
certificates. For those, show a warning when the account is being
created, and only proceed if the user decides to ignore it. In any
case, save the status of the certificate that was used to create the
account. So an account created with a valid certificate will never
work with an invalid one, and one created with an invalid certificate
will not throw any further warnings.
Fixes: CVE-2013-0240'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: build_object (GoaProvider *provider,
GoaObjectSkeleton *object,
GKeyFile *key_file,
const gchar *group,
GDBusConnection *connection,
gboolean just_added,
GError **error)
{
GoaAccount *account;
GoaCalendar *calendar;
GoaContacts *contacts;
GoaExchange *exchange;
GoaMail *mail;
GoaPasswordBased *password_based;
gboolean calendar_enabled;
gboolean contacts_enabled;
gboolean mail_enabled;
gboolean ret;
account = NULL;
calendar = NULL;
contacts = NULL;
exchange = NULL;
mail = NULL;
password_based = NULL;
ret = FALSE;
/* Chain up */
if (!GOA_PROVIDER_CLASS (goa_exchange_provider_parent_class)->build_object (provider,
object,
key_file,
group,
connection,
just_added,
error))
goto out;
password_based = goa_object_get_password_based (GOA_OBJECT (object));
if (password_based == NULL)
{
password_based = goa_password_based_skeleton_new ();
/* Ensure D-Bus method invocations run in their own thread */
g_dbus_interface_skeleton_set_flags (G_DBUS_INTERFACE_SKELETON (password_based),
G_DBUS_INTERFACE_SKELETON_FLAGS_HANDLE_METHOD_INVOCATIONS_IN_THREAD);
goa_object_skeleton_set_password_based (object, password_based);
g_signal_connect (password_based,
"handle-get-password",
G_CALLBACK (on_handle_get_password),
NULL);
}
account = goa_object_get_account (GOA_OBJECT (object));
/* Email */
mail = goa_object_get_mail (GOA_OBJECT (object));
mail_enabled = g_key_file_get_boolean (key_file, group, "MailEnabled", NULL);
if (mail_enabled)
{
if (mail == NULL)
{
const gchar *email_address;
email_address = goa_account_get_presentation_identity (account);
mail = goa_mail_skeleton_new ();
g_object_set (G_OBJECT (mail), "email-address", email_address, NULL);
goa_object_skeleton_set_mail (object, mail);
}
}
else
{
if (mail != NULL)
goa_object_skeleton_set_mail (object, NULL);
}
/* Calendar */
calendar = goa_object_get_calendar (GOA_OBJECT (object));
calendar_enabled = g_key_file_get_boolean (key_file, group, "CalendarEnabled", NULL);
if (calendar_enabled)
{
if (calendar == NULL)
{
calendar = goa_calendar_skeleton_new ();
goa_object_skeleton_set_calendar (object, calendar);
}
}
else
{
if (calendar != NULL)
goa_object_skeleton_set_calendar (object, NULL);
}
/* Contacts */
contacts = goa_object_get_contacts (GOA_OBJECT (object));
contacts_enabled = g_key_file_get_boolean (key_file, group, "ContactsEnabled", NULL);
if (contacts_enabled)
{
if (contacts == NULL)
{
contacts = goa_contacts_skeleton_new ();
goa_object_skeleton_set_contacts (object, contacts);
}
}
else
{
if (contacts != NULL)
goa_object_skeleton_set_contacts (object, NULL);
}
/* Exchange */
exchange = goa_object_get_exchange (GOA_OBJECT (object));
if (exchange == NULL)
{
gchar *host;
host = g_key_file_get_string (key_file, group, "Host", NULL);
exchange = goa_exchange_skeleton_new ();
g_object_set (G_OBJECT (exchange), "host", host, NULL);
goa_object_skeleton_set_exchange (object, exchange);
g_free (host);
}
if (just_added)
{
goa_account_set_mail_disabled (account, !mail_enabled);
goa_account_set_calendar_disabled (account, !calendar_enabled);
goa_account_set_contacts_disabled (account, !contacts_enabled);
g_signal_connect (account,
"notify::mail-disabled",
G_CALLBACK (goa_util_account_notify_property_cb),
"MailEnabled");
g_signal_connect (account,
"notify::calendar-disabled",
G_CALLBACK (goa_util_account_notify_property_cb),
"CalendarEnabled");
g_signal_connect (account,
"notify::contacts-disabled",
G_CALLBACK (goa_util_account_notify_property_cb),
"ContactsEnabled");
}
ret = TRUE;
out:
if (exchange != NULL)
g_object_unref (exchange);
if (contacts != NULL)
g_object_unref (contacts);
if (calendar != NULL)
g_object_unref (calendar);
if (mail != NULL)
g_object_unref (mail);
if (password_based != NULL)
g_object_unref (password_based);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
None of the branded providers (eg., Google, Facebook and Windows Live)
should ever have an invalid certificate. So set "ssl-strict" on the
SoupSession object being used by GoaWebView.
Providers like ownCloud and Exchange might have to deal with
certificates that are not up to the mark. eg., self-signed
certificates. For those, show a warning when the account is being
created, and only proceed if the user decides to ignore it. In any
case, save the status of the certificate that was used to create the
account. So an account created with a valid certificate will never
work with an invalid one, and one created with an invalid certificate
will not throw any further warnings.
Fixes: CVE-2013-0240'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: refresh_account (GoaProvider *provider,
GoaClient *client,
GoaObject *object,
GtkWindow *parent,
GError **error)
{
AddAccountData data;
GVariantBuilder builder;
GoaAccount *account;
GoaEwsClient *ews_client;
GoaExchange *exchange;
GtkWidget *dialog;
GtkWidget *vbox;
gboolean ret;
const gchar *email_address;
const gchar *server;
const gchar *password;
const gchar *username;
gint response;
g_return_val_if_fail (GOA_IS_EXCHANGE_PROVIDER (provider), FALSE);
g_return_val_if_fail (GOA_IS_CLIENT (client), FALSE);
g_return_val_if_fail (GOA_IS_OBJECT (object), FALSE);
g_return_val_if_fail (parent == NULL || GTK_IS_WINDOW (parent), FALSE);
g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
ews_client = NULL;
ret = FALSE;
dialog = gtk_dialog_new_with_buttons (NULL,
parent,
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
NULL);
gtk_container_set_border_width (GTK_CONTAINER (dialog), 12);
gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);
gtk_window_set_resizable (GTK_WINDOW (dialog), FALSE);
vbox = gtk_dialog_get_content_area (GTK_DIALOG (dialog));
gtk_box_set_spacing (GTK_BOX (vbox), 12);
memset (&data, 0, sizeof (AddAccountData));
data.cancellable = g_cancellable_new ();
data.loop = g_main_loop_new (NULL, FALSE);
data.dialog = GTK_DIALOG (dialog);
data.error = NULL;
create_account_details_ui (provider, GTK_DIALOG (dialog), GTK_BOX (vbox), FALSE, &data);
account = goa_object_peek_account (object);
email_address = goa_account_get_presentation_identity (account);
gtk_entry_set_text (GTK_ENTRY (data.email_address), email_address);
gtk_editable_set_editable (GTK_EDITABLE (data.email_address), FALSE);
gtk_widget_show_all (dialog);
g_signal_connect (dialog, "response", G_CALLBACK (dialog_response_cb), &data);
ews_client = goa_ews_client_new ();
ews_again:
response = gtk_dialog_run (GTK_DIALOG (dialog));
if (response != GTK_RESPONSE_OK)
{
g_set_error (&data.error,
GOA_ERROR,
GOA_ERROR_DIALOG_DISMISSED,
_("Dialog was dismissed"));
goto out;
}
password = gtk_entry_get_text (GTK_ENTRY (data.password));
username = goa_account_get_identity (account);
exchange = goa_object_peek_exchange (object);
server = goa_exchange_get_host (exchange);
g_cancellable_reset (data.cancellable);
goa_ews_client_autodiscover (ews_client,
email_address,
password,
username,
server,
data.cancellable,
autodiscover_cb,
&data);
gtk_widget_set_sensitive (data.connect_button, FALSE);
gtk_widget_show (data.progress_grid);
g_main_loop_run (data.loop);
if (g_cancellable_is_cancelled (data.cancellable))
{
g_prefix_error (&data.error,
_("Dialog was dismissed (%s, %d): "),
g_quark_to_string (data.error->domain),
data.error->code);
data.error->domain = GOA_ERROR;
data.error->code = GOA_ERROR_DIALOG_DISMISSED;
goto out;
}
else if (data.error != NULL)
{
gchar *markup;
markup = g_strdup_printf ("<b>%s:</b> %s",
_("Error connecting to Microsoft Exchange server"),
data.error->message);
g_clear_error (&data.error);
gtk_label_set_markup (GTK_LABEL (data.cluebar_label), markup);
g_free (markup);
gtk_button_set_label (GTK_BUTTON (data.connect_button), _("_Try Again"));
gtk_widget_set_no_show_all (data.cluebar, FALSE);
gtk_widget_show_all (data.cluebar);
goto ews_again;
}
/* TODO: run in worker thread */
g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add (&builder, "{sv}", "password", g_variant_new_string (password));
if (!goa_utils_store_credentials_for_object_sync (provider,
object,
g_variant_builder_end (&builder),
NULL, /* GCancellable */
&data.error))
goto out;
goa_account_call_ensure_credentials (account,
NULL, /* GCancellable */
NULL, NULL); /* callback, user_data */
ret = TRUE;
out:
if (data.error != NULL)
g_propagate_error (error, data.error);
gtk_widget_destroy (dialog);
if (data.loop != NULL)
g_main_loop_unref (data.loop);
g_clear_object (&data.cancellable);
if (ews_client != NULL)
g_object_unref (ews_client);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
None of the branded providers (eg., Google, Facebook and Windows Live)
should ever have an invalid certificate. So set "ssl-strict" on the
SoupSession object being used by GoaWebView.
Providers like ownCloud and Exchange might have to deal with
certificates that are not up to the mark. eg., self-signed
certificates. For those, show a warning when the account is being
created, and only proceed if the user decides to ignore it. In any
case, save the status of the certificate that was used to create the
account. So an account created with a valid certificate will never
work with an invalid one, and one created with an invalid certificate
will not throw any further warnings.
Fixes: CVE-2013-0240'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ensure_credentials_sync (GoaProvider *provider,
GoaObject *object,
gint *out_expires_in,
GCancellable *cancellable,
GError **error)
{
GVariant *credentials;
GoaAccount *account;
GoaHttpClient *http_client;
gboolean ret;
const gchar *username;
gchar *password;
gchar *uri_caldav;
credentials = NULL;
http_client = NULL;
password = NULL;
uri_caldav = NULL;
ret = FALSE;
/* Chain up */
if (!GOA_PROVIDER_CLASS (goa_google_provider_parent_class)->ensure_credentials_sync (provider,
object,
out_expires_in,
cancellable,
error))
goto out;
credentials = goa_utils_lookup_credentials_sync (provider,
object,
cancellable,
error);
if (credentials == NULL)
{
if (error != NULL)
{
g_prefix_error (error,
_("Credentials not found in keyring (%s, %d): "),
g_quark_to_string ((*error)->domain),
(*error)->code);
(*error)->domain = GOA_ERROR;
(*error)->code = GOA_ERROR_NOT_AUTHORIZED;
}
goto out;
}
account = goa_object_peek_account (object);
username = goa_account_get_presentation_identity (account);
uri_caldav = g_strdup_printf (CALDAV_ENDPOINT, username);
if (!g_variant_lookup (credentials, "password", "s", &password))
{
if (error != NULL)
{
*error = g_error_new (GOA_ERROR,
GOA_ERROR_NOT_AUTHORIZED,
_("Did not find password with username `%s' in credentials"),
username);
}
goto out;
}
http_client = goa_http_client_new ();
ret = goa_http_client_check_sync (http_client,
uri_caldav,
username,
password,
cancellable,
error);
if (!ret)
{
if (error != NULL)
{
g_prefix_error (error,
/* Translators: the first %s is the username
* (eg., [email protected] or rishi), and the
* (%s, %d) is the error domain and code.
*/
_("Invalid password with username `%s' (%s, %d): "),
username,
g_quark_to_string ((*error)->domain),
(*error)->code);
(*error)->domain = GOA_ERROR;
(*error)->code = GOA_ERROR_NOT_AUTHORIZED;
}
goto out;
}
out:
g_clear_object (&http_client);
g_free (password);
g_free (uri_caldav);
g_clear_pointer (&credentials, (GDestroyNotify) g_variant_unref);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
None of the branded providers (eg., Google, Facebook and Windows Live)
should ever have an invalid certificate. So set "ssl-strict" on the
SoupSession object being used by GoaWebView.
Providers like ownCloud and Exchange might have to deal with
certificates that are not up to the mark. eg., self-signed
certificates. For those, show a warning when the account is being
created, and only proceed if the user decides to ignore it. In any
case, save the status of the certificate that was used to create the
account. So an account created with a valid certificate will never
work with an invalid one, and one created with an invalid certificate
will not throw any further warnings.
Fixes: CVE-2013-0240'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: add_account (GoaProvider *provider,
GoaClient *client,
GtkDialog *dialog,
GtkBox *vbox,
GError **error)
{
AddAccountData data;
GVariantBuilder credentials;
GVariantBuilder details;
GoaEwsClient *ews_client;
GoaObject *ret;
const gchar *email_address;
const gchar *server;
const gchar *password;
const gchar *username;
const gchar *provider_type;
gint response;
ews_client = NULL;
ret = NULL;
memset (&data, 0, sizeof (AddAccountData));
data.cancellable = g_cancellable_new ();
data.loop = g_main_loop_new (NULL, FALSE);
data.dialog = dialog;
data.error = NULL;
create_account_details_ui (provider, dialog, vbox, TRUE, &data);
gtk_widget_show_all (GTK_WIDGET (vbox));
g_signal_connect (dialog, "response", G_CALLBACK (dialog_response_cb), &data);
ews_client = goa_ews_client_new ();
ews_again:
response = gtk_dialog_run (dialog);
if (response != GTK_RESPONSE_OK)
{
g_set_error (&data.error,
GOA_ERROR,
GOA_ERROR_DIALOG_DISMISSED,
_("Dialog was dismissed"));
goto out;
}
email_address = gtk_entry_get_text (GTK_ENTRY (data.email_address));
password = gtk_entry_get_text (GTK_ENTRY (data.password));
username = gtk_entry_get_text (GTK_ENTRY (data.username));
server = gtk_entry_get_text (GTK_ENTRY (data.server));
/* See if there's already an account of this type with the
* given identity
*/
provider_type = goa_provider_get_provider_type (provider);
if (!goa_utils_check_duplicate (client,
username,
provider_type,
(GoaPeekInterfaceFunc) goa_object_peek_password_based,
&data.error))
goto out;
g_cancellable_reset (data.cancellable);
goa_ews_client_autodiscover (ews_client,
email_address,
password,
username,
server,
data.cancellable,
autodiscover_cb,
&data);
gtk_widget_set_sensitive (data.connect_button, FALSE);
gtk_widget_show (data.progress_grid);
g_main_loop_run (data.loop);
if (g_cancellable_is_cancelled (data.cancellable))
{
g_prefix_error (&data.error,
_("Dialog was dismissed (%s, %d): "),
g_quark_to_string (data.error->domain),
data.error->code);
data.error->domain = GOA_ERROR;
data.error->code = GOA_ERROR_DIALOG_DISMISSED;
goto out;
}
else if (data.error != NULL)
{
gchar *markup;
markup = g_strdup_printf ("<b>%s:</b> %s",
_("Error connecting to Microsoft Exchange server"),
data.error->message);
g_clear_error (&data.error);
gtk_label_set_markup (GTK_LABEL (data.cluebar_label), markup);
g_free (markup);
gtk_button_set_label (GTK_BUTTON (data.connect_button), _("_Try Again"));
gtk_expander_set_expanded (GTK_EXPANDER (data.expander), TRUE);
gtk_widget_set_no_show_all (data.cluebar, FALSE);
gtk_widget_show_all (data.cluebar);
goto ews_again;
}
gtk_widget_hide (GTK_WIDGET (dialog));
g_variant_builder_init (&credentials, G_VARIANT_TYPE_VARDICT);
g_variant_builder_add (&credentials, "{sv}", "password", g_variant_new_string (password));
g_variant_builder_init (&details, G_VARIANT_TYPE ("a{ss}"));
g_variant_builder_add (&details, "{ss}", "MailEnabled", "true");
g_variant_builder_add (&details, "{ss}", "CalendarEnabled", "true");
g_variant_builder_add (&details, "{ss}", "ContactsEnabled", "true");
g_variant_builder_add (&details, "{ss}", "Host", server);
/* OK, everything is dandy, add the account */
/* we want the GoaClient to update before this method returns (so it
* can create a proxy for the new object) so run the mainloop while
* waiting for this to complete
*/
goa_manager_call_add_account (goa_client_get_manager (client),
goa_provider_get_provider_type (provider),
username,
email_address,
g_variant_builder_end (&credentials),
g_variant_builder_end (&details),
NULL, /* GCancellable* */
(GAsyncReadyCallback) add_account_cb,
&data);
g_main_loop_run (data.loop);
if (data.error != NULL)
goto out;
ret = GOA_OBJECT (g_dbus_object_manager_get_object (goa_client_get_object_manager (client),
data.account_object_path));
out:
/* We might have an object even when data.error is set.
* eg., if we failed to store the credentials in the keyring.
*/
if (data.error != NULL)
g_propagate_error (error, data.error);
else
g_assert (ret != NULL);
g_free (data.account_object_path);
if (data.loop != NULL)
g_main_loop_unref (data.loop);
g_clear_object (&data.cancellable);
if (ews_client != NULL)
g_object_unref (ews_client);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
None of the branded providers (eg., Google, Facebook and Windows Live)
should ever have an invalid certificate. So set "ssl-strict" on the
SoupSession object being used by GoaWebView.
Providers like ownCloud and Exchange might have to deal with
certificates that are not up to the mark. eg., self-signed
certificates. For those, show a warning when the account is being
created, and only proceed if the user decides to ignore it. In any
case, save the status of the certificate that was used to create the
account. So an account created with a valid certificate will never
work with an invalid one, and one created with an invalid certificate
will not throw any further warnings.
Fixes: CVE-2013-0240'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: goa_web_view_init (GoaWebView *self)
{
GoaWebViewPrivate *priv;
GtkWidget *scrolled_window;
SoupCookieJar *cookie_jar;
SoupSession *session;
WebKitWebSettings *settings;
self->priv = GOA_WEB_VIEW_GET_PRIVATE (self);
priv = self->priv;
session = webkit_get_default_session ();
soup_session_add_feature_by_type (session, SOUP_TYPE_PROXY_RESOLVER_GNOME);
g_object_set (session, "accept-language-auto", TRUE, NULL);
soup_session_remove_feature_by_type (session, SOUP_TYPE_COOKIE_JAR);
cookie_jar = soup_cookie_jar_new ();
soup_session_add_feature (session, SOUP_SESSION_FEATURE (cookie_jar));
g_object_unref (cookie_jar);
gtk_style_context_add_class (gtk_widget_get_style_context (GTK_WIDGET (self)),
GTK_STYLE_CLASS_OSD);
scrolled_window = gtk_scrolled_window_new (NULL, NULL);
gtk_widget_set_size_request (scrolled_window, 500, 400);
gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolled_window), GTK_SHADOW_IN);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
GTK_POLICY_AUTOMATIC,
GTK_POLICY_AUTOMATIC);
gtk_container_add (GTK_CONTAINER (self), scrolled_window);
priv->web_view = webkit_web_view_new ();
priv->status = WEBKIT_LOAD_PROVISIONAL;
gtk_container_add (GTK_CONTAINER (scrolled_window), priv->web_view);
settings = webkit_web_view_get_settings (WEBKIT_WEB_VIEW (priv->web_view));
g_object_set (settings, "user-stylesheet-uri", "file://" PACKAGE_DATA_DIR "/goawebview.css", NULL);
/* statusbar is hidden by default */
priv->floating_bar = nautilus_floating_bar_new (NULL, FALSE);
gtk_widget_set_halign (priv->floating_bar, GTK_ALIGN_START);
gtk_widget_set_valign (priv->floating_bar, GTK_ALIGN_END);
gtk_widget_set_no_show_all (priv->floating_bar, TRUE);
gtk_overlay_add_overlay (GTK_OVERLAY (self), priv->floating_bar);
priv->progress_bar = gtk_progress_bar_new ();
gtk_widget_set_halign (priv->progress_bar, GTK_ALIGN_FILL);
gtk_widget_set_valign (priv->progress_bar, GTK_ALIGN_START);
gtk_overlay_add_overlay (GTK_OVERLAY (self), priv->progress_bar);
priv->notify_progress_id = g_signal_connect (priv->web_view,
"notify::progress",
G_CALLBACK (web_view_notify_progress_cb),
self);
priv->notify_load_status_id = g_signal_connect (priv->web_view,
"notify::load-status",
G_CALLBACK (web_view_notify_load_status_cb),
self);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
None of the branded providers (eg., Google, Facebook and Windows Live)
should ever have an invalid certificate. So set "ssl-strict" on the
SoupSession object being used by GoaWebView.
Providers like ownCloud and Exchange might have to deal with
certificates that are not up to the mark. eg., self-signed
certificates. For those, show a warning when the account is being
created, and only proceed if the user decides to ignore it. In any
case, save the status of the certificate that was used to create the
account. So an account created with a valid certificate will never
work with an invalid one, and one created with an invalid certificate
will not throw any further warnings.
Fixes: CVE-2013-0240'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: http_client_check_response_cb (SoupSession *session, SoupMessage *msg, gpointer user_data)
{
GError *error;
CheckData *data = user_data;
gboolean op_res;
error = NULL;
op_res = FALSE;
if (msg->status_code == SOUP_STATUS_CANCELLED)
goto out;
else if (msg->status_code != SOUP_STATUS_OK)
{
g_set_error (&error,
GOA_ERROR,
GOA_ERROR_FAILED, /* TODO: more specific */
_("Code: %u - Unexpected response from server"),
msg->status_code);
goto out;
}
op_res = TRUE;
out:
g_simple_async_result_set_op_res_gboolean (data->res, op_res);
if (error != NULL)
g_simple_async_result_take_error (data->res, error);
g_simple_async_result_complete_in_idle (data->res);
http_client_check_data_free (data);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
None of the branded providers (eg., Google, Facebook and Windows Live)
should ever have an invalid certificate. So set "ssl-strict" on the
SoupSession object being used by GoaWebView.
Providers like ownCloud and Exchange might have to deal with
certificates that are not up to the mark. eg., self-signed
certificates. For those, show a warning when the account is being
created, and only proceed if the user decides to ignore it. In any
case, save the status of the certificate that was used to create the
account. So an account created with a valid certificate will never
work with an invalid one, and one created with an invalid certificate
will not throw any further warnings.
Fixes: CVE-2013-0240'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: goa_http_client_check (GoaHttpClient *client,
const gchar *uri,
const gchar *username,
const gchar *password,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
CheckData *data;
CheckAuthData *auth;
g_return_if_fail (GOA_IS_HTTP_CLIENT (client));
g_return_if_fail (uri != NULL || uri[0] != '\0');
g_return_if_fail (username != NULL || username[0] != '\0');
g_return_if_fail (password != NULL || password[0] != '\0');
g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
data = g_slice_new0 (CheckData);
data->res = g_simple_async_result_new (G_OBJECT (client), callback, user_data, goa_http_client_check);
data->session = soup_session_async_new_with_options (SOUP_SESSION_USE_THREAD_CONTEXT, TRUE,
NULL);
data->msg = soup_message_new (SOUP_METHOD_GET, uri);
soup_message_headers_append (data->msg->request_headers, "Connection", "close");
if (cancellable != NULL)
{
data->cancellable = g_object_ref (cancellable);
data->cancellable_id = g_cancellable_connect (data->cancellable,
G_CALLBACK (http_client_check_cancelled_cb),
data,
NULL);
g_simple_async_result_set_check_cancellable (data->res, data->cancellable);
}
auth = g_slice_new0 (CheckAuthData);
auth->username = g_strdup (username);
auth->password = g_strdup (password);
g_signal_connect_data (data->session,
"authenticate",
G_CALLBACK (http_client_authenticate),
auth,
http_client_check_auth_data_free,
0);
soup_session_queue_message (data->session, data->msg, http_client_check_response_cb, data);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
None of the branded providers (eg., Google, Facebook and Windows Live)
should ever have an invalid certificate. So set "ssl-strict" on the
SoupSession object being used by GoaWebView.
Providers like ownCloud and Exchange might have to deal with
certificates that are not up to the mark. eg., self-signed
certificates. For those, show a warning when the account is being
created, and only proceed if the user decides to ignore it. In any
case, save the status of the certificate that was used to create the
account. So an account created with a valid certificate will never
work with an invalid one, and one created with an invalid certificate
will not throw any further warnings.
Fixes: CVE-2013-0240'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ews_client_autodiscover_response_cb (SoupSession *session, SoupMessage *msg, gpointer user_data)
{
GError *error;
AutodiscoverData *data = user_data;
gboolean op_res;
guint status;
gint idx;
gsize size;
xmlDoc *doc;
xmlNode *node;
status = msg->status_code;
if (status == SOUP_STATUS_CANCELLED)
return;
error = NULL;
op_res = FALSE;
size = sizeof (data->msgs) / sizeof (data->msgs[0]);
for (idx = 0; idx < size; idx++)
{
if (data->msgs[idx] == msg)
break;
}
if (idx == size)
return;
data->msgs[idx] = NULL;
if (status != SOUP_STATUS_OK)
{
g_set_error (&error,
GOA_ERROR,
GOA_ERROR_FAILED, /* TODO: more specific */
_("Code: %u - Unexpected response from server"),
status);
goto out;
}
soup_buffer_free (soup_message_body_flatten (SOUP_MESSAGE (msg)->response_body));
g_debug ("The response headers");
g_debug ("===================");
g_debug ("%s", SOUP_MESSAGE (msg)->response_body->data);
doc = xmlReadMemory (msg->response_body->data, msg->response_body->length, "autodiscover.xml", NULL, 0);
if (doc == NULL)
{
g_set_error (&error,
GOA_ERROR,
GOA_ERROR_FAILED, /* TODO: more specific */
_("Failed to parse autodiscover response XML"));
goto out;
}
node = xmlDocGetRootElement (doc);
if (g_strcmp0 ((gchar *) node->name, "Autodiscover"))
{
g_set_error (&error,
GOA_ERROR,
GOA_ERROR_FAILED, /* TODO: more specific */
_("Failed to find Autodiscover element"));
goto out;
}
for (node = node->children; node; node = node->next)
{
if (ews_client_check_node (node, "Response"))
break;
}
if (node == NULL)
{
g_set_error (&error,
GOA_ERROR,
GOA_ERROR_FAILED, /* TODO: more specific */
_("Failed to find Response element"));
goto out;
}
for (node = node->children; node; node = node->next)
{
if (ews_client_check_node (node, "Account"))
break;
}
if (node == NULL)
{
g_set_error (&error,
GOA_ERROR,
GOA_ERROR_FAILED, /* TODO: more specific */
_("Failed to find Account element"));
goto out;
}
for (node = node->children; node; node = node->next)
{
if (ews_client_check_node (node, "Protocol"))
{
op_res = ews_client_autodiscover_parse_protocol (node);
break;
}
}
if (!op_res)
{
g_set_error (&error,
GOA_ERROR,
GOA_ERROR_FAILED, /* TODO: more specific*/
_("Failed to find ASUrl and OABUrl in autodiscover response"));
goto out;
}
for (idx = 0; idx < size; idx++)
{
if (data->msgs[idx] != NULL)
{
/* Since we are cancelling from the same thread that we queued the
* message, the callback (ie. this function) will be invoked before
* soup_session_cancel_message returns.
*/
soup_session_cancel_message (data->session, data->msgs[idx], SOUP_STATUS_CANCELLED);
data->msgs[idx] = NULL;
}
}
out:
if (error != NULL)
{
for (idx = 0; idx < size; idx++)
{
if (data->msgs[idx] != NULL)
{
/* There's another request outstanding.
* Hope that it has better luck.
*/
g_clear_error (&error);
return;
}
}
g_simple_async_result_set_from_error (data->res, error);
}
else
g_simple_async_result_set_op_res_gboolean (data->res, op_res);
g_simple_async_result_complete_in_idle (data->res);
ews_client_autodiscover_data_free (data);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
None of the branded providers (eg., Google, Facebook and Windows Live)
should ever have an invalid certificate. So set "ssl-strict" on the
SoupSession object being used by GoaWebView.
Providers like ownCloud and Exchange might have to deal with
certificates that are not up to the mark. eg., self-signed
certificates. For those, show a warning when the account is being
created, and only proceed if the user decides to ignore it. In any
case, save the status of the certificate that was used to create the
account. So an account created with a valid certificate will never
work with an invalid one, and one created with an invalid certificate
will not throw any further warnings.
Fixes: CVE-2013-0240'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: http_client_check_response_cb (SoupSession *session, SoupMessage *msg, gpointer user_data)
{
GError *error;
CheckData *data = user_data;
GTlsCertificateFlags cert_flags;
gboolean op_res;
gboolean using_https;
error = NULL;
op_res = FALSE;
if (msg->status_code == SOUP_STATUS_CANCELLED)
goto out;
else if (msg->status_code != SOUP_STATUS_OK)
{
g_set_error (&error,
GOA_ERROR,
GOA_ERROR_FAILED, /* TODO: more specific */
_("Code: %u - Unexpected response from server"),
msg->status_code);
goto out;
}
if (!data->accept_ssl_errors)
{
using_https = soup_message_get_https_status (msg, NULL, &cert_flags);
if (using_https && cert_flags != 0)
{
goa_utils_set_error_ssl (&error, cert_flags);
goto out;
}
}
op_res = TRUE;
out:
g_simple_async_result_set_op_res_gboolean (data->res, op_res);
if (error != NULL)
g_simple_async_result_take_error (data->res, error);
g_simple_async_result_complete_in_idle (data->res);
g_idle_add (http_client_check_data_free, data);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
For providers like Exchange which use libsoup to talk to a HTTPS
server it is not enough to warn the user about an invalid certificate.
We should make sure that we abort the connection before any
credentials have been sent.
Fixes: CVE-2013-1799'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: goa_http_client_check (GoaHttpClient *client,
const gchar *uri,
const gchar *username,
const gchar *password,
gboolean accept_ssl_errors,
GCancellable *cancellable,
GAsyncReadyCallback callback,
gpointer user_data)
{
CheckData *data;
CheckAuthData *auth;
g_return_if_fail (GOA_IS_HTTP_CLIENT (client));
g_return_if_fail (uri != NULL || uri[0] != '\0');
g_return_if_fail (username != NULL || username[0] != '\0');
g_return_if_fail (password != NULL || password[0] != '\0');
g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
data = g_slice_new0 (CheckData);
data->res = g_simple_async_result_new (G_OBJECT (client), callback, user_data, goa_http_client_check);
data->session = soup_session_async_new_with_options (SOUP_SESSION_SSL_USE_SYSTEM_CA_FILE, TRUE,
SOUP_SESSION_SSL_STRICT, FALSE,
SOUP_SESSION_USE_THREAD_CONTEXT, TRUE,
NULL);
data->accept_ssl_errors = accept_ssl_errors;
data->msg = soup_message_new (SOUP_METHOD_GET, uri);
soup_message_headers_append (data->msg->request_headers, "Connection", "close");
if (cancellable != NULL)
{
data->cancellable = g_object_ref (cancellable);
data->cancellable_id = g_cancellable_connect (data->cancellable,
G_CALLBACK (http_client_check_cancelled_cb),
data,
NULL);
g_simple_async_result_set_check_cancellable (data->res, data->cancellable);
}
auth = g_slice_new0 (CheckAuthData);
auth->username = g_strdup (username);
auth->password = g_strdup (password);
g_signal_connect_data (data->session,
"authenticate",
G_CALLBACK (http_client_authenticate),
auth,
http_client_check_auth_data_free,
0);
soup_session_queue_message (data->session, data->msg, http_client_check_response_cb, data);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Guard against invalid SSL certificates
For providers like Exchange which use libsoup to talk to a HTTPS
server it is not enough to warn the user about an invalid certificate.
We should make sure that we abort the connection before any
credentials have been sent.
Fixes: CVE-2013-1799'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void beforeSleep(struct aeEventLoop *eventLoop) {
REDIS_NOTUSED(eventLoop);
listNode *ln;
redisClient *c;
/* Awake clients that got all the swapped keys they requested */
if (server.vm_enabled && listLength(server.io_ready_clients)) {
listIter li;
listRewind(server.io_ready_clients,&li);
while((ln = listNext(&li))) {
c = ln->value;
struct redisCommand *cmd;
/* Resume the client. */
listDelNode(server.io_ready_clients,ln);
c->flags &= (~REDIS_IO_WAIT);
server.vm_blocked_clients--;
aeCreateFileEvent(server.el, c->fd, AE_READABLE,
readQueryFromClient, c);
cmd = lookupCommand(c->argv[0]->ptr);
redisAssert(cmd != NULL);
call(c,cmd);
resetClient(c);
/* There may be more data to process in the input buffer. */
if (c->querybuf && sdslen(c->querybuf) > 0)
processInputBuffer(c);
}
}
/* Try to process pending commands for clients that were just unblocked. */
while (listLength(server.unblocked_clients)) {
ln = listFirst(server.unblocked_clients);
redisAssert(ln != NULL);
c = ln->value;
listDelNode(server.unblocked_clients,ln);
/* Process remaining data in the input buffer. */
if (c->querybuf && sdslen(c->querybuf) > 0)
processInputBuffer(c);
}
/* Write the AOF buffer on disk */
flushAppendOnlyFile();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'initial changes needed to turn the current VM code into a cache system. Tons of work to do still.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void initServerConfig() {
server.port = REDIS_SERVERPORT;
server.bindaddr = NULL;
server.unixsocket = NULL;
server.ipfd = -1;
server.sofd = -1;
server.dbnum = REDIS_DEFAULT_DBNUM;
server.verbosity = REDIS_VERBOSE;
server.maxidletime = REDIS_MAXIDLETIME;
server.saveparams = NULL;
server.loading = 0;
server.logfile = NULL; /* NULL = log on standard output */
server.syslog_enabled = 0;
server.syslog_ident = zstrdup("redis");
server.syslog_facility = LOG_LOCAL0;
server.glueoutputbuf = 1;
server.daemonize = 0;
server.appendonly = 0;
server.appendfsync = APPENDFSYNC_EVERYSEC;
server.no_appendfsync_on_rewrite = 0;
server.lastfsync = time(NULL);
server.appendfd = -1;
server.appendseldb = -1; /* Make sure the first time will not match */
server.pidfile = zstrdup("/var/run/redis.pid");
server.dbfilename = zstrdup("dump.rdb");
server.appendfilename = zstrdup("appendonly.aof");
server.requirepass = NULL;
server.rdbcompression = 1;
server.activerehashing = 1;
server.maxclients = 0;
server.bpop_blocked_clients = 0;
server.maxmemory = 0;
server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
server.maxmemory_samples = 3;
server.vm_enabled = 0;
server.vm_swap_file = zstrdup("/tmp/redis-%p.vm");
server.vm_page_size = 256; /* 256 bytes per page */
server.vm_pages = 1024*1024*100; /* 104 millions of pages */
server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
server.vm_max_threads = 4;
server.vm_blocked_clients = 0;
server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES;
server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE;
server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES;
server.shutdown_asap = 0;
updateLRUClock();
resetServerSaveParams();
appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
/* Replication related */
server.isslave = 0;
server.masterauth = NULL;
server.masterhost = NULL;
server.masterport = 6379;
server.master = NULL;
server.replstate = REDIS_REPL_NONE;
server.repl_serve_stale_data = 1;
/* Double constants initialization */
R_Zero = 0.0;
R_PosInf = 1.0/R_Zero;
R_NegInf = -1.0/R_Zero;
R_Nan = R_Zero/R_Zero;
/* Command table -- we intiialize it here as it is part of the
* initial configuration, since command names may be changed via
* redis.conf using the rename-command directive. */
server.commands = dictCreate(&commandTableDictType,NULL);
populateCommandTable();
server.delCommand = lookupCommandByCString("del");
server.multiCommand = lookupCommandByCString("multi");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'initial changes needed to turn the current VM code into a cache system. Tons of work to do still.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void freeClient(redisClient *c) {
listNode *ln;
/* Note that if the client we are freeing is blocked into a blocking
* call, we have to set querybuf to NULL *before* to call
* unblockClientWaitingData() to avoid processInputBuffer() will get
* called. Also it is important to remove the file events after
* this, because this call adds the READABLE event. */
sdsfree(c->querybuf);
c->querybuf = NULL;
if (c->flags & REDIS_BLOCKED)
unblockClientWaitingData(c);
/* UNWATCH all the keys */
unwatchAllKeys(c);
listRelease(c->watched_keys);
/* Unsubscribe from all the pubsub channels */
pubsubUnsubscribeAllChannels(c,0);
pubsubUnsubscribeAllPatterns(c,0);
dictRelease(c->pubsub_channels);
listRelease(c->pubsub_patterns);
/* Obvious cleanup */
aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
listRelease(c->reply);
freeClientArgv(c);
close(c->fd);
/* Remove from the list of clients */
ln = listSearchKey(server.clients,c);
redisAssert(ln != NULL);
listDelNode(server.clients,ln);
/* Remove from the list of clients waiting for swapped keys, or ready
* to be restarted, but not yet woken up again. */
if (c->flags & REDIS_IO_WAIT) {
redisAssert(server.vm_enabled);
if (listLength(c->io_keys) == 0) {
ln = listSearchKey(server.io_ready_clients,c);
/* When this client is waiting to be woken up (REDIS_IO_WAIT),
* it should be present in the list io_ready_clients */
redisAssert(ln != NULL);
listDelNode(server.io_ready_clients,ln);
} else {
while (listLength(c->io_keys)) {
ln = listFirst(c->io_keys);
dontWaitForSwappedKey(c,ln->value);
}
}
server.vm_blocked_clients--;
}
listRelease(c->io_keys);
/* Master/slave cleanup.
* Case 1: we lost the connection with a slave. */
if (c->flags & REDIS_SLAVE) {
if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
close(c->repldbfd);
list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
ln = listSearchKey(l,c);
redisAssert(ln != NULL);
listDelNode(l,ln);
}
/* Case 2: we lost the connection with the master. */
if (c->flags & REDIS_MASTER) {
server.master = NULL;
/* FIXME */
server.replstate = REDIS_REPL_CONNECT;
/* Since we lost the connection with the master, we should also
* close the connection with all our slaves if we have any, so
* when we'll resync with the master the other slaves will sync again
* with us as well. Note that also when the slave is not connected
* to the master it will keep refusing connections by other slaves. */
while (listLength(server.slaves)) {
ln = listFirst(server.slaves);
freeClient((redisClient*)ln->value);
}
}
/* Release memory */
zfree(c->argv);
freeClientMultiState(c);
zfree(c);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'initial changes needed to turn the current VM code into a cache system. Tons of work to do still.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int dsOpen(void) {
struct stat sb;
int retval;
char *path = server.diskstore_path;
if ((retval = stat(path,&sb) == -1) && errno != ENOENT) {
redisLog(REDIS_WARNING, "Error opening disk store at %s: %s",
path, strerror(errno));
return REDIS_ERR;
}
/* Directory already in place. Assume everything is ok. */
if (retval == 0 && S_ISDIR(sb.st_mode)) return REDIS_OK;
/* File exists but it's not a directory */
if (retval == 0 && !S_ISDIR(sb.st_mode)) {
redisLog(REDIS_WARNING,"Disk store at %s is not a directory", path);
return REDIS_ERR;
}
/* New disk store, create the directory structure now, as creating
* them in a lazy way is not a good idea, after very few insertions
* we'll need most of the 65536 directories anyway. */
if (mkdir(path) == -1) {
redisLog(REDIS_WARNING,"Disk store init failed creating dir %s: %s",
path, strerror(errno));
return REDIS_ERR;
}
return REDIS_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'initial changes needed to turn the current VM code into a cache system. Tons of work to do still.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void addReply(redisClient *c, robj *obj) {
if (_installWriteEvent(c) != REDIS_OK) return;
redisAssert(!server.vm_enabled || obj->storage == REDIS_VM_MEMORY);
/* This is an important place where we can avoid copy-on-write
* when there is a saving child running, avoiding touching the
* refcount field of the object if it's not needed.
*
* If the encoding is RAW and there is room in the static buffer
* we'll be able to send the object to the client without
* messing with its page. */
if (obj->encoding == REDIS_ENCODING_RAW) {
if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)
_addReplyObjectToList(c,obj);
} else {
/* FIXME: convert the long into string and use _addReplyToBuffer()
* instead of calling getDecodedObject. As this place in the
* code is too performance critical. */
obj = getDecodedObject(obj);
if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)
_addReplyObjectToList(c,obj);
decrRefCount(obj);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'initial changes needed to turn the current VM code into a cache system. Tons of work to do still.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: PHP_FUNCTION(openssl_encrypt)
{
zend_bool raw_output = 0;
char *data, *method, *password, *iv = "";
int data_len, method_len, password_len, iv_len = 0, max_iv_len;
const EVP_CIPHER *cipher_type;
EVP_CIPHER_CTX cipher_ctx;
int i, outlen, keylen;
unsigned char *outbuf, *key;
zend_bool free_iv;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|bs", &data, &data_len, &method, &method_len, &password, &password_len, &raw_output, &iv, &iv_len) == FAILURE) {
return;
}
cipher_type = EVP_get_cipherbyname(method);
if (!cipher_type) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
RETURN_FALSE;
}
keylen = EVP_CIPHER_key_length(cipher_type);
if (keylen > password_len) {
key = emalloc(keylen);
memset(key, 0, keylen);
memcpy(key, password, password_len);
} else {
key = (unsigned char*)password;
}
max_iv_len = EVP_CIPHER_iv_length(cipher_type);
if (iv_len <= 0 && max_iv_len > 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Using an empty Initialization Vector (iv) is potentially insecure and not recommended");
}
free_iv = php_openssl_validate_iv(&iv, &iv_len, max_iv_len TSRMLS_CC);
outlen = data_len + EVP_CIPHER_block_size(cipher_type);
outbuf = emalloc(outlen + 1);
EVP_EncryptInit(&cipher_ctx, cipher_type, NULL, NULL);
if (password_len > keylen) {
EVP_CIPHER_CTX_set_key_length(&cipher_ctx, password_len);
}
EVP_EncryptInit_ex(&cipher_ctx, NULL, NULL, key, (unsigned char *)iv);
EVP_EncryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len);
outlen = i;
if (EVP_EncryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) {
outlen += i;
if (raw_output) {
outbuf[outlen] = '\0';
RETVAL_STRINGL((char *)outbuf, outlen, 0);
} else {
int base64_str_len;
char *base64_str;
base64_str = (char*)php_base64_encode(outbuf, outlen, &base64_str_len);
efree(outbuf);
RETVAL_STRINGL(base64_str, base64_str_len, 0);
}
} else {
efree(outbuf);
RETVAL_FALSE;
}
if (key != (unsigned char*)password) {
efree(key);
}
if (free_iv) {
efree(iv);
}
EVP_CIPHER_CTX_cleanup(&cipher_ctx);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Fix segfault in older versions of OpenSSL (before 0.9.8i)'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: _gnutls_ciphertext2compressed (gnutls_session_t session,
opaque * compress_data,
int compress_size,
gnutls_datum_t ciphertext, uint8_t type,
record_parameters_st * params)
{
uint8_t MAC[MAX_HASH_SIZE];
uint16_t c_length;
unsigned int pad;
int length;
uint16_t blocksize;
int ret, i, pad_failed = 0;
opaque preamble[PREAMBLE_SIZE];
int preamble_size;
int ver = gnutls_protocol_get_version (session);
int hash_size = _gnutls_hash_get_algo_len (params->mac_algorithm);
blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm);
/* actual decryption (inplace)
*/
switch (_gnutls_cipher_is_block (params->cipher_algorithm))
{
case CIPHER_STREAM:
if ((ret =
_gnutls_cipher_decrypt (¶ms->read.cipher_state,
ciphertext.data, ciphertext.size)) < 0)
{
gnutls_assert ();
return ret;
}
length = ciphertext.size - hash_size;
break;
case CIPHER_BLOCK:
if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0))
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
if ((ret =
_gnutls_cipher_decrypt (¶ms->read.cipher_state,
ciphertext.data, ciphertext.size)) < 0)
{
gnutls_assert ();
return ret;
}
/* ignore the IV in TLS 1.1.
*/
if (_gnutls_version_has_explicit_iv
(session->security_parameters.version))
{
ciphertext.size -= blocksize;
ciphertext.data += blocksize;
}
if (ciphertext.size < hash_size)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */
if ((int) pad > (int) ciphertext.size - hash_size)
{
gnutls_assert ();
_gnutls_record_log
("REC[%p]: Short record length %d > %d - %d (under attack?)\n",
session, pad, ciphertext.size, hash_size);
/* We do not fail here. We check below for the
* the pad_failed. If zero means success.
*/
pad_failed = GNUTLS_E_DECRYPTION_FAILED;
}
length = ciphertext.size - hash_size - pad;
/* Check the pading bytes (TLS 1.x)
*/
if (_gnutls_version_has_variable_padding (ver) && pad_failed == 0)
for (i = 2; i <= pad; i++)
{
if (ciphertext.data[ciphertext.size - i] !=
ciphertext.data[ciphertext.size - 1])
pad_failed = GNUTLS_E_DECRYPTION_FAILED;
}
break;
default:
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
if (length < 0)
length = 0;
c_length = _gnutls_conv_uint16 ((uint16_t) length);
/* Pass the type, version, length and compressed through
* MAC.
*/
if (params->mac_algorithm != GNUTLS_MAC_NULL)
{
digest_hd_st td;
ret = mac_init (&td, params->mac_algorithm,
params->read.mac_secret.data,
params->read.mac_secret.size, ver);
if (ret < 0)
{
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
preamble_size =
make_preamble (UINT64DATA
(params->read.sequence_number), type,
c_length, ver, preamble);
mac_hash (&td, preamble, preamble_size, ver);
if (length > 0)
mac_hash (&td, ciphertext.data, length, ver);
mac_deinit (&td, MAC, ver);
}
/* This one was introduced to avoid a timing attack against the TLS
* 1.0 protocol.
*/
if (pad_failed != 0)
{
gnutls_assert ();
return pad_failed;
}
/* HMAC was not the same.
*/
if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
/* copy the decrypted stuff to compress_data.
*/
if (compress_size < length)
{
gnutls_assert ();
return GNUTLS_E_DECOMPRESSION_FAILED;
}
memcpy (compress_data, ciphertext.data, length);
return length;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Fixes to avoid a timing attack in TLS CBC record parsing.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void dummy_wait(record_parameters_st * params, gnutls_datum_t* plaintext,
unsigned pad_failed, unsigned int pad, unsigned total)
{
/* this hack is only needed on CBC ciphers */
if (_gnutls_cipher_is_block (params->cipher_algorithm) == CIPHER_BLOCK)
{
unsigned len;
/* force an additional hash compression function evaluation to prevent timing
* attacks that distinguish between wrong-mac + correct pad, from wrong-mac + incorrect pad.
*/
if (pad_failed == 0 && pad > 0)
{
len = _gnutls_get_hash_block_len(params->mac_algorithm);
if (len > 0)
{
/* This is really specific to the current hash functions.
* It should be removed once a protocol fix is in place.
*/
if ((pad+total) % len > len-9 && total % len <= len-9)
{
if (len < plaintext->size)
_gnutls_auth_cipher_add_auth (¶ms->read.cipher_state, plaintext->data, len);
else
_gnutls_auth_cipher_add_auth (¶ms->read.cipher_state, plaintext->data, plaintext->size);
}
}
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'corrected fix'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: ciphertext_to_compressed (gnutls_session_t session,
gnutls_datum_t *ciphertext,
gnutls_datum_t * compressed,
uint8_t type, record_parameters_st * params,
uint64* sequence)
{
uint8_t tag[MAX_HASH_SIZE];
unsigned int pad, i;
int length, length_to_decrypt;
uint16_t blocksize;
int ret, pad_failed = 0;
uint8_t preamble[MAX_PREAMBLE_SIZE];
unsigned int preamble_size;
unsigned int ver = gnutls_protocol_get_version (session);
unsigned int tag_size = _gnutls_auth_cipher_tag_len (¶ms->read.cipher_state);
unsigned int explicit_iv = _gnutls_version_has_explicit_iv (session->security_parameters.version);
blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm);
/* actual decryption (inplace)
*/
switch (_gnutls_cipher_is_block (params->cipher_algorithm))
{
case CIPHER_STREAM:
/* The way AEAD ciphers are defined in RFC5246, it allows
* only stream ciphers.
*/
if (explicit_iv && _gnutls_auth_cipher_is_aead(¶ms->read.cipher_state))
{
uint8_t nonce[blocksize];
/* Values in AEAD are pretty fixed in TLS 1.2 for 128-bit block
*/
if (params->read.IV.data == NULL || params->read.IV.size != 4)
return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
if (ciphertext->size < tag_size+AEAD_EXPLICIT_DATA_SIZE)
return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
memcpy(nonce, params->read.IV.data, AEAD_IMPLICIT_DATA_SIZE);
memcpy(&nonce[AEAD_IMPLICIT_DATA_SIZE], ciphertext->data, AEAD_EXPLICIT_DATA_SIZE);
_gnutls_auth_cipher_setiv(¶ms->read.cipher_state, nonce, AEAD_EXPLICIT_DATA_SIZE+AEAD_IMPLICIT_DATA_SIZE);
ciphertext->data += AEAD_EXPLICIT_DATA_SIZE;
ciphertext->size -= AEAD_EXPLICIT_DATA_SIZE;
length_to_decrypt = ciphertext->size - tag_size;
}
else
{
if (ciphertext->size < tag_size)
return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
length_to_decrypt = ciphertext->size;
}
length = ciphertext->size - tag_size;
/* Pass the type, version, length and compressed through
* MAC.
*/
preamble_size =
make_preamble (UINT64DATA(*sequence), type,
length, ver, preamble);
ret = _gnutls_auth_cipher_add_auth (¶ms->read.cipher_state, preamble, preamble_size);
if (ret < 0)
return gnutls_assert_val(ret);
if ((ret =
_gnutls_auth_cipher_decrypt2 (¶ms->read.cipher_state,
ciphertext->data, length_to_decrypt,
ciphertext->data, ciphertext->size)) < 0)
return gnutls_assert_val(ret);
break;
case CIPHER_BLOCK:
if (ciphertext->size < blocksize || (ciphertext->size % blocksize != 0))
return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
/* ignore the IV in TLS 1.1+
*/
if (explicit_iv)
{
_gnutls_auth_cipher_setiv(¶ms->read.cipher_state,
ciphertext->data, blocksize);
ciphertext->size -= blocksize;
ciphertext->data += blocksize;
}
if (ciphertext->size < tag_size)
return gnutls_assert_val(GNUTLS_E_DECRYPTION_FAILED);
/* we don't use the auth_cipher interface here, since
* TLS with block ciphers is impossible to be used under such
* an API. (the length of plaintext is required to calculate
* auth_data, but it is not available before decryption).
*/
if ((ret =
_gnutls_cipher_decrypt (¶ms->read.cipher_state.cipher,
ciphertext->data, ciphertext->size)) < 0)
return gnutls_assert_val(ret);
pad = ciphertext->data[ciphertext->size - 1] + 1; /* pad */
if (pad > (int) ciphertext->size - tag_size)
{
gnutls_assert ();
_gnutls_record_log
("REC[%p]: Short record length %d > %d - %d (under attack?)\n",
session, pad, ciphertext->size, tag_size);
/* We do not fail here. We check below for the
* the pad_failed. If zero means success.
*/
pad_failed = GNUTLS_E_DECRYPTION_FAILED;
pad %= blocksize;
}
length = ciphertext->size - tag_size - pad;
/* Check the pading bytes (TLS 1.x)
*/
if (ver != GNUTLS_SSL3)
for (i = 2; i <= pad; i++)
{
if (ciphertext->data[ciphertext->size - i] !=
ciphertext->data[ciphertext->size - 1])
pad_failed = GNUTLS_E_DECRYPTION_FAILED;
}
if (length < 0)
{
/* Setting a proper length to prevent timing differences in
* processing of records with invalid encryption.
*/
length = ciphertext->size - tag_size;
}
/* Pass the type, version, length and compressed through
* MAC.
*/
preamble_size =
make_preamble (UINT64DATA(*sequence), type,
length, ver, preamble);
ret = _gnutls_auth_cipher_add_auth (¶ms->read.cipher_state, preamble, preamble_size);
if (ret < 0)
return gnutls_assert_val(ret);
ret = _gnutls_auth_cipher_add_auth (¶ms->read.cipher_state, ciphertext->data, length);
if (ret < 0)
return gnutls_assert_val(ret);
break;
default:
return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
}
ret = _gnutls_auth_cipher_tag(¶ms->read.cipher_state, tag, tag_size);
if (ret < 0)
return gnutls_assert_val(ret);
/* This one was introduced to avoid a timing attack against the TLS
* 1.0 protocol.
*/
/* HMAC was not the same.
*/
if (memcmp (tag, &ciphertext->data[length], tag_size) != 0 || pad_failed != 0)
return gnutls_assert_val(GNUTLS_E_DECRYPTION_FAILED);
/* copy the decrypted stuff to compress_data.
*/
if (compressed->size < (unsigned)length)
return gnutls_assert_val(GNUTLS_E_DECOMPRESSION_FAILED);
memcpy (compressed->data, ciphertext->data, length);
return length;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Fixes to avoid a timing attack in TLS CBC record parsing.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int ssl_decrypt_buf( ssl_context *ssl )
{
size_t i, padlen = 0, correct = 1;
unsigned char tmp[POLARSSL_SSL_MAX_MAC_SIZE];
SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
if( ssl->in_msglen < ssl->transform_in->minlen )
{
SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)",
ssl->in_msglen, ssl->transform_in->minlen ) );
return( POLARSSL_ERR_SSL_INVALID_MAC );
}
if( ssl->transform_in->ivlen == 0 )
{
#if defined(POLARSSL_ARC4_C)
if( ssl->session_in->ciphersuite == TLS_RSA_WITH_RC4_128_MD5 ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_RC4_128_SHA )
{
arc4_crypt( (arc4_context *) ssl->transform_in->ctx_dec,
ssl->in_msglen, ssl->in_msg,
ssl->in_msg );
} else
#endif
#if defined(POLARSSL_CIPHER_NULL_CIPHER)
if( ssl->session_in->ciphersuite == TLS_RSA_WITH_NULL_MD5 ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_NULL_SHA ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_NULL_SHA256 )
{
} else
#endif
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
else if( ssl->transform_in->ivlen == 12 )
{
unsigned char *dec_msg;
unsigned char *dec_msg_result;
size_t dec_msglen;
unsigned char add_data[13];
int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE;
#if defined(POLARSSL_AES_C) && defined(POLARSSL_GCM_C)
if( ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_128_GCM_SHA256 ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_256_GCM_SHA384 ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 )
{
dec_msglen = ssl->in_msglen - ( ssl->transform_in->ivlen -
ssl->transform_in->fixed_ivlen );
dec_msglen -= 16;
dec_msg = ssl->in_msg + ( ssl->transform_in->ivlen -
ssl->transform_in->fixed_ivlen );
dec_msg_result = ssl->in_msg;
ssl->in_msglen = dec_msglen;
memcpy( add_data, ssl->in_ctr, 8 );
add_data[8] = ssl->in_msgtype;
add_data[9] = ssl->major_ver;
add_data[10] = ssl->minor_ver;
add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;
add_data[12] = ssl->in_msglen & 0xFF;
SSL_DEBUG_BUF( 4, "additional data used for AEAD",
add_data, 13 );
memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen,
ssl->in_msg,
ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen );
SSL_DEBUG_BUF( 4, "IV used", ssl->transform_in->iv_dec,
ssl->transform_in->ivlen );
SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, 16 );
memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen,
ssl->in_msg,
ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen );
ret = gcm_auth_decrypt( (gcm_context *) ssl->transform_in->ctx_dec,
dec_msglen,
ssl->transform_in->iv_dec,
ssl->transform_in->ivlen,
add_data, 13,
dec_msg + dec_msglen, 16,
dec_msg, dec_msg_result );
if( ret != 0 )
{
SSL_DEBUG_MSG( 1, ( "AEAD decrypt failed on validation (ret = -0x%02x)",
-ret ) );
return( POLARSSL_ERR_SSL_INVALID_MAC );
}
} else
#endif
return( ret );
}
else
{
/*
* Decrypt and check the padding
*/
unsigned char *dec_msg;
unsigned char *dec_msg_result;
size_t dec_msglen;
size_t minlen = 0, fake_padlen;
/*
* Check immediate ciphertext sanity
*/
if( ssl->in_msglen % ssl->transform_in->ivlen != 0 )
{
SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
ssl->in_msglen, ssl->transform_in->ivlen ) );
return( POLARSSL_ERR_SSL_INVALID_MAC );
}
if( ssl->minor_ver >= SSL_MINOR_VERSION_2 )
minlen += ssl->transform_in->ivlen;
if( ssl->in_msglen < minlen + ssl->transform_in->ivlen ||
ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 )
{
SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) + 1 ) ( + expl IV )",
ssl->in_msglen, ssl->transform_in->ivlen, ssl->transform_in->maclen ) );
return( POLARSSL_ERR_SSL_INVALID_MAC );
}
dec_msglen = ssl->in_msglen;
dec_msg = ssl->in_msg;
dec_msg_result = ssl->in_msg;
/*
* Initialize for prepended IV for block cipher in TLS v1.1 and up
*/
if( ssl->minor_ver >= SSL_MINOR_VERSION_2 )
{
dec_msg += ssl->transform_in->ivlen;
dec_msglen -= ssl->transform_in->ivlen;
ssl->in_msglen -= ssl->transform_in->ivlen;
for( i = 0; i < ssl->transform_in->ivlen; i++ )
ssl->transform_in->iv_dec[i] = ssl->in_msg[i];
}
switch( ssl->transform_in->ivlen )
{
#if defined(POLARSSL_DES_C)
case 8:
#if defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES)
if( ssl->session_in->ciphersuite == TLS_RSA_WITH_DES_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_DES_CBC_SHA )
{
des_crypt_cbc( (des_context *) ssl->transform_in->ctx_dec,
DES_DECRYPT, dec_msglen,
ssl->transform_in->iv_dec, dec_msg, dec_msg_result );
}
else
#endif
des3_crypt_cbc( (des3_context *) ssl->transform_in->ctx_dec,
DES_DECRYPT, dec_msglen,
ssl->transform_in->iv_dec, dec_msg, dec_msg_result );
break;
#endif
case 16:
#if defined(POLARSSL_AES_C)
if ( ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_128_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_256_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_128_CBC_SHA256 ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_256_CBC_SHA256 ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 )
{
aes_crypt_cbc( (aes_context *) ssl->transform_in->ctx_dec,
AES_DECRYPT, dec_msglen,
ssl->transform_in->iv_dec, dec_msg, dec_msg_result );
break;
}
#endif
#if defined(POLARSSL_CAMELLIA_C)
if ( ssl->session_in->ciphersuite == TLS_RSA_WITH_CAMELLIA_128_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_CAMELLIA_256_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 ||
ssl->session_in->ciphersuite == TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 ||
ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 )
{
camellia_crypt_cbc( (camellia_context *) ssl->transform_in->ctx_dec,
CAMELLIA_DECRYPT, dec_msglen,
ssl->transform_in->iv_dec, dec_msg, dec_msg_result );
break;
}
#endif
default:
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
padlen = 1 + ssl->in_msg[ssl->in_msglen - 1];
fake_padlen = 256 - padlen;
if( ssl->in_msglen < ssl->transform_in->maclen + padlen )
{
SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
ssl->in_msglen, ssl->transform_in->maclen, padlen ) );
padlen = 0;
fake_padlen = 256;
correct = 0;
}
if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
{
if( padlen > ssl->transform_in->ivlen )
{
SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
"should be no more than %d",
padlen, ssl->transform_in->ivlen ) );
correct = 0;
}
}
else
{
/*
* TLSv1+: always check the padding up to the first failure
* and fake check up to 256 bytes of padding
*/
for( i = 1; i <= padlen; i++ )
{
if( ssl->in_msg[ssl->in_msglen - i] != padlen - 1 )
{
correct = 0;
fake_padlen = 256 - i;
padlen = 0;
}
}
for( i = 1; i <= fake_padlen; i++ )
{
if( ssl->in_msg[i + 1] != fake_padlen - 1 )
minlen = 0;
else
minlen = 1;
}
if( padlen > 0 && correct == 0)
SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
}
}
SSL_DEBUG_BUF( 4, "raw buffer after decryption",
ssl->in_msg, ssl->in_msglen );
/*
* Always compute the MAC (RFC4346, CBCTIME).
*/
ssl->in_msglen -= ( ssl->transform_in->maclen + padlen );
ssl->in_hdr[3] = (unsigned char)( ssl->in_msglen >> 8 );
ssl->in_hdr[4] = (unsigned char)( ssl->in_msglen );
memcpy( tmp, ssl->in_msg + ssl->in_msglen, ssl->transform_in->maclen );
if( ssl->minor_ver == SSL_MINOR_VERSION_0 )
{
if( ssl->transform_in->maclen == 16 )
ssl_mac_md5( ssl->transform_in->mac_dec,
ssl->in_msg, ssl->in_msglen,
ssl->in_ctr, ssl->in_msgtype );
else if( ssl->transform_in->maclen == 20 )
ssl_mac_sha1( ssl->transform_in->mac_dec,
ssl->in_msg, ssl->in_msglen,
ssl->in_ctr, ssl->in_msgtype );
else if( ssl->transform_in->maclen == 32 )
ssl_mac_sha2( ssl->transform_in->mac_dec,
ssl->in_msg, ssl->in_msglen,
ssl->in_ctr, ssl->in_msgtype );
else if( ssl->transform_in->maclen != 0 )
{
SSL_DEBUG_MSG( 1, ( "invalid MAC len: %d",
ssl->transform_in->maclen ) );
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
}
else
{
/*
* Process MAC and always update for padlen afterwards to make
* total time independent of padlen
*/
if( ssl->transform_in->maclen == 16 )
md5_hmac( ssl->transform_in->mac_dec, 16,
ssl->in_ctr, ssl->in_msglen + 13,
ssl->in_msg + ssl->in_msglen );
else if( ssl->transform_in->maclen == 20 )
sha1_hmac( ssl->transform_in->mac_dec, 20,
ssl->in_ctr, ssl->in_msglen + 13,
ssl->in_msg + ssl->in_msglen );
else if( ssl->transform_in->maclen == 32 )
sha2_hmac( ssl->transform_in->mac_dec, 32,
ssl->in_ctr, ssl->in_msglen + 13,
ssl->in_msg + ssl->in_msglen, 0 );
else if( ssl->transform_in->maclen != 0 )
{
SSL_DEBUG_MSG( 1, ( "invalid MAC len: %d",
ssl->transform_in->maclen ) );
return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE );
}
}
SSL_DEBUG_BUF( 4, "message mac", tmp, ssl->transform_in->maclen );
SSL_DEBUG_BUF( 4, "computed mac", ssl->in_msg + ssl->in_msglen,
ssl->transform_in->maclen );
if( memcmp( tmp, ssl->in_msg + ssl->in_msglen,
ssl->transform_in->maclen ) != 0 )
{
SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
correct = 0;
}
/*
* Finally check the correct flag
*/
if( correct == 0 )
return( POLARSSL_ERR_SSL_INVALID_MAC );
if( ssl->in_msglen == 0 )
{
ssl->nb_zero++;
/*
* Three or more empty messages may be a DoS attack
* (excessive CPU consumption).
*/
if( ssl->nb_zero > 3 )
{
SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
"messages, possible DoS attack" ) );
return( POLARSSL_ERR_SSL_INVALID_MAC );
}
}
else
ssl->nb_zero = 0;
for( i = 8; i > 0; i-- )
if( ++ssl->in_ctr[i - 1] != 0 )
break;
SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
return( 0 );
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Disable debug messages that can introduce a timing side channel.
Introduced the POLARSSL_SSL_DEBUG_ALL flag to enable all these debug
messages in case somebody does want to see the reason checks fail.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: rfbProcessClientMessage(rfbClientPtr cl)
{
switch (cl->state) {
case RFB_PROTOCOL_VERSION:
rfbProcessClientProtocolVersion(cl);
return;
case RFB_SECURITY_TYPE:
rfbAuthProcessSecurityTypeMessage(cl);
return;
#ifdef VINO_HAVE_GNUTLS
case RFB_TLS_HANDSHAKE:
rfbAuthProcessTLSHandshake(cl);
return;
#endif
case RFB_AUTH_TYPE:
rfbAuthProcessAuthTypeMessage(cl);
return;
case RFB_AUTHENTICATION:
rfbAuthProcessClientMessage(cl);
return;
case RFB_AUTH_DEFERRED:
rfbLog("Authentication deferred - ignoring client message\n");
return;
case RFB_INITIALISATION:
rfbProcessClientInitMessage(cl);
return;
default:
rfbProcessClientNormalMessage(cl);
return;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Reject new clients if in the deferred state
As mentioned in bug 641811, Vino can get stuck trying to process the
same data in an infinite loop if an authentication request is received
from a client while that client is in the deferred state.
Avoid this situation by closing new connections from the same client
when it is in the deferred state.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(old_dir)->root;
struct btrfs_root *dest = BTRFS_I(new_dir)->root;
struct inode *new_inode = new_dentry->d_inode;
struct inode *old_inode = old_dentry->d_inode;
struct timespec ctime = CURRENT_TIME;
u64 index = 0;
u64 root_objectid;
int ret;
u64 old_ino = btrfs_ino(old_inode);
if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
return -EPERM;
/* we only allow rename subvolume link between subvolumes */
if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
return -EXDEV;
if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
(new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
return -ENOTEMPTY;
if (S_ISDIR(old_inode->i_mode) && new_inode &&
new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
return -ENOTEMPTY;
/*
* we're using rename to replace one file with another.
* and the replacement file is large. Start IO on it now so
* we don't add too much work to the end of the transaction
*/
if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
filemap_flush(old_inode->i_mapping);
/* close the racy window with snapshot create/destroy ioctl */
if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
down_read(&root->fs_info->subvol_sem);
/*
* We want to reserve the absolute worst case amount of items. So if
* both inodes are subvols and we need to unlink them then that would
* require 4 item modifications, but if they are both normal inodes it
* would require 5 item modifications, so we'll assume their normal
* inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
* should cover the worst case number of items we'll modify.
*/
trans = btrfs_start_transaction(root, 20);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
goto out_notrans;
}
if (dest != root)
btrfs_record_root_in_trans(trans, dest);
ret = btrfs_set_inode_index(new_dir, &index);
if (ret)
goto out_fail;
if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
/* force full log commit if subvolume involved. */
root->fs_info->last_trans_log_full_commit = trans->transid;
} else {
ret = btrfs_insert_inode_ref(trans, dest,
new_dentry->d_name.name,
new_dentry->d_name.len,
old_ino,
btrfs_ino(new_dir), index);
if (ret)
goto out_fail;
/*
* this is an ugly little race, but the rename is required
* to make sure that if we crash, the inode is either at the
* old name or the new one. pinning the log transaction lets
* us make sure we don't allow a log commit to come in after
* we unlink the name but before we add the new name back in.
*/
btrfs_pin_log_trans(root);
}
/*
* make sure the inode gets flushed if it is replacing
* something.
*/
if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
btrfs_add_ordered_operation(trans, root, old_inode);
inode_inc_iversion(old_dir);
inode_inc_iversion(new_dir);
inode_inc_iversion(old_inode);
old_dir->i_ctime = old_dir->i_mtime = ctime;
new_dir->i_ctime = new_dir->i_mtime = ctime;
old_inode->i_ctime = ctime;
if (old_dentry->d_parent != new_dentry->d_parent)
btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
old_dentry->d_name.name,
old_dentry->d_name.len);
} else {
ret = __btrfs_unlink_inode(trans, root, old_dir,
old_dentry->d_inode,
old_dentry->d_name.name,
old_dentry->d_name.len);
if (!ret)
ret = btrfs_update_inode(trans, root, old_inode);
}
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out_fail;
}
if (new_inode) {
inode_inc_iversion(new_inode);
new_inode->i_ctime = CURRENT_TIME;
if (unlikely(btrfs_ino(new_inode) ==
BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
root_objectid = BTRFS_I(new_inode)->location.objectid;
ret = btrfs_unlink_subvol(trans, dest, new_dir,
root_objectid,
new_dentry->d_name.name,
new_dentry->d_name.len);
BUG_ON(new_inode->i_nlink == 0);
} else {
ret = btrfs_unlink_inode(trans, dest, new_dir,
new_dentry->d_inode,
new_dentry->d_name.name,
new_dentry->d_name.len);
}
if (!ret && new_inode->i_nlink == 0) {
ret = btrfs_orphan_add(trans, new_dentry->d_inode);
BUG_ON(ret);
}
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out_fail;
}
}
fixup_inode_flags(new_dir, old_inode);
ret = btrfs_add_link(trans, new_dir, old_inode,
new_dentry->d_name.name,
new_dentry->d_name.len, 0, index);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out_fail;
}
if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
struct dentry *parent = new_dentry->d_parent;
btrfs_log_new_name(trans, old_inode, old_dir, parent);
btrfs_end_log_trans(root);
}
out_fail:
btrfs_end_transaction(trans, root);
out_notrans:
if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
up_read(&root->fs_info->subvol_sem);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Btrfs: fix hash overflow handling
The handling for directory crc hash overflows was fairly obscure,
split_leaf returns EOVERFLOW when we try to extend the item and that is
supposed to bubble up to userland. For a while it did so, but along the
way we added better handling of errors and forced the FS readonly if we
hit IO errors during the directory insertion.
Along the way, we started testing only for EEXIST and the EOVERFLOW case
was dropped. The end result is that we may force the FS readonly if we
catch a directory hash bucket overflow.
This fixes a few problem spots. First I add tests for EOVERFLOW in the
places where we can safely just return the error up the chain.
btrfs_rename is harder though, because it tries to insert the new
directory item only after it has already unlinked anything the rename
was going to overwrite. Rather than adding very complex logic, I added
a helper to test for the hash overflow case early while it is still safe
to bail out.
Snapshot and subvolume creation had a similar problem, so they are using
the new helper now too.
Signed-off-by: Chris Mason <[email protected]>
Reported-by: Pascal Junod <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static noinline int btrfs_mksubvol(struct path *parent,
char *name, int namelen,
struct btrfs_root *snap_src,
u64 *async_transid, bool readonly,
struct btrfs_qgroup_inherit **inherit)
{
struct inode *dir = parent->dentry->d_inode;
struct dentry *dentry;
int error;
mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT);
dentry = lookup_one_len(name, parent->dentry, namelen);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto out_unlock;
error = -EEXIST;
if (dentry->d_inode)
goto out_dput;
error = btrfs_may_create(dir, dentry);
if (error)
goto out_dput;
down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
goto out_up_read;
if (snap_src) {
error = create_snapshot(snap_src, dentry, name, namelen,
async_transid, readonly, inherit);
} else {
error = create_subvol(BTRFS_I(dir)->root, dentry,
name, namelen, async_transid, inherit);
}
if (!error)
fsnotify_mkdir(dir, dentry);
out_up_read:
up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
out_dput:
dput(dentry);
out_unlock:
mutex_unlock(&dir->i_mutex);
return error;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-310'], 'message': 'Btrfs: fix hash overflow handling
The handling for directory crc hash overflows was fairly obscure,
split_leaf returns EOVERFLOW when we try to extend the item and that is
supposed to bubble up to userland. For a while it did so, but along the
way we added better handling of errors and forced the FS readonly if we
hit IO errors during the directory insertion.
Along the way, we started testing only for EEXIST and the EOVERFLOW case
was dropped. The end result is that we may force the FS readonly if we
catch a directory hash bucket overflow.
This fixes a few problem spots. First I add tests for EOVERFLOW in the
places where we can safely just return the error up the chain.
btrfs_rename is harder though, because it tries to insert the new
directory item only after it has already unlinked anything the rename
was going to overwrite. Rather than adding very complex logic, I added
a helper to test for the hash overflow case early while it is still safe
to bail out.
Snapshot and subvolume creation had a similar problem, so they are using
the new helper now too.
Signed-off-by: Chris Mason <[email protected]>
Reported-by: Pascal Junod <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xmlCtxtReset(xmlParserCtxtPtr ctxt)
{
xmlParserInputPtr input;
xmlDictPtr dict;
if (ctxt == NULL)
return;
dict = ctxt->dict;
while ((input = inputPop(ctxt)) != NULL) { /* Non consuming */
xmlFreeInputStream(input);
}
ctxt->inputNr = 0;
ctxt->input = NULL;
ctxt->spaceNr = 0;
if (ctxt->spaceTab != NULL) {
ctxt->spaceTab[0] = -1;
ctxt->space = &ctxt->spaceTab[0];
} else {
ctxt->space = NULL;
}
ctxt->nodeNr = 0;
ctxt->node = NULL;
ctxt->nameNr = 0;
ctxt->name = NULL;
DICT_FREE(ctxt->version);
ctxt->version = NULL;
DICT_FREE(ctxt->encoding);
ctxt->encoding = NULL;
DICT_FREE(ctxt->directory);
ctxt->directory = NULL;
DICT_FREE(ctxt->extSubURI);
ctxt->extSubURI = NULL;
DICT_FREE(ctxt->extSubSystem);
ctxt->extSubSystem = NULL;
if (ctxt->myDoc != NULL)
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
ctxt->standalone = -1;
ctxt->hasExternalSubset = 0;
ctxt->hasPErefs = 0;
ctxt->html = 0;
ctxt->external = 0;
ctxt->instate = XML_PARSER_START;
ctxt->token = 0;
ctxt->wellFormed = 1;
ctxt->nsWellFormed = 1;
ctxt->disableSAX = 0;
ctxt->valid = 1;
#if 0
ctxt->vctxt.userData = ctxt;
ctxt->vctxt.error = xmlParserValidityError;
ctxt->vctxt.warning = xmlParserValidityWarning;
#endif
ctxt->record_info = 0;
ctxt->nbChars = 0;
ctxt->checkIndex = 0;
ctxt->inSubset = 0;
ctxt->errNo = XML_ERR_OK;
ctxt->depth = 0;
ctxt->charset = XML_CHAR_ENCODING_UTF8;
ctxt->catalogs = NULL;
ctxt->nbentities = 0;
ctxt->sizeentities = 0;
xmlInitNodeInfoSeq(&ctxt->node_seq);
if (ctxt->attsDefault != NULL) {
xmlHashFree(ctxt->attsDefault, (xmlHashDeallocator) xmlFree);
ctxt->attsDefault = NULL;
}
if (ctxt->attsSpecial != NULL) {
xmlHashFree(ctxt->attsSpecial, NULL);
ctxt->attsSpecial = NULL;
}
#ifdef LIBXML_CATALOG_ENABLED
if (ctxt->catalogs != NULL)
xmlCatalogFreeLocal(ctxt->catalogs);
#endif
if (ctxt->lastError.code != XML_ERR_OK)
xmlResetError(&ctxt->lastError);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Detect excessive entities expansion upon replacement
If entities expansion in the XML parser is asked for,
it is possble to craft relatively small input document leading
to excessive on-the-fly content generation.
This patch accounts for those replacement and stop parsing
after a given threshold. it can be bypassed as usual with the
HUGE parser option.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xmlParserEntityCheck(xmlParserCtxtPtr ctxt, size_t size,
xmlEntityPtr ent)
{
size_t consumed = 0;
if ((ctxt == NULL) || (ctxt->options & XML_PARSE_HUGE))
return (0);
if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP)
return (1);
if (size != 0) {
/*
* Do the check based on the replacement size of the entity
*/
if (size < XML_PARSER_BIG_ENTITY)
return(0);
/*
* A limit on the amount of text data reasonably used
*/
if (ctxt->input != NULL) {
consumed = ctxt->input->consumed +
(ctxt->input->cur - ctxt->input->base);
}
consumed += ctxt->sizeentities;
if ((size < XML_PARSER_NON_LINEAR * consumed) &&
(ctxt->nbentities * 3 < XML_PARSER_NON_LINEAR * consumed))
return (0);
} else if (ent != NULL) {
/*
* use the number of parsed entities in the replacement
*/
size = ent->checked;
/*
* The amount of data parsed counting entities size only once
*/
if (ctxt->input != NULL) {
consumed = ctxt->input->consumed +
(ctxt->input->cur - ctxt->input->base);
}
consumed += ctxt->sizeentities;
/*
* Check the density of entities for the amount of data
* knowing an entity reference will take at least 3 bytes
*/
if (size * 3 < consumed * XML_PARSER_NON_LINEAR)
return (0);
} else {
/*
* strange we got no data for checking just return
*/
return (0);
}
xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
return (1);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Detect excessive entities expansion upon replacement
If entities expansion in the XML parser is asked for,
it is possble to craft relatively small input document leading
to excessive on-the-fly content generation.
This patch accounts for those replacement and stop parsing
after a given threshold. it can be bypassed as usual with the
HUGE parser option.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xmlInitParserCtxt(xmlParserCtxtPtr ctxt)
{
xmlParserInputPtr input;
if(ctxt==NULL) {
xmlErrInternal(NULL, "Got NULL parser context\n", NULL);
return(-1);
}
xmlDefaultSAXHandlerInit();
if (ctxt->dict == NULL)
ctxt->dict = xmlDictCreate();
if (ctxt->dict == NULL) {
xmlErrMemory(NULL, "cannot initialize parser context\n");
return(-1);
}
xmlDictSetLimit(ctxt->dict, XML_MAX_DICTIONARY_LIMIT);
if (ctxt->sax == NULL)
ctxt->sax = (xmlSAXHandler *) xmlMalloc(sizeof(xmlSAXHandler));
if (ctxt->sax == NULL) {
xmlErrMemory(NULL, "cannot initialize parser context\n");
return(-1);
}
else
xmlSAXVersion(ctxt->sax, 2);
ctxt->maxatts = 0;
ctxt->atts = NULL;
/* Allocate the Input stack */
if (ctxt->inputTab == NULL) {
ctxt->inputTab = (xmlParserInputPtr *)
xmlMalloc(5 * sizeof(xmlParserInputPtr));
ctxt->inputMax = 5;
}
if (ctxt->inputTab == NULL) {
xmlErrMemory(NULL, "cannot initialize parser context\n");
ctxt->inputNr = 0;
ctxt->inputMax = 0;
ctxt->input = NULL;
return(-1);
}
while ((input = inputPop(ctxt)) != NULL) { /* Non consuming */
xmlFreeInputStream(input);
}
ctxt->inputNr = 0;
ctxt->input = NULL;
ctxt->version = NULL;
ctxt->encoding = NULL;
ctxt->standalone = -1;
ctxt->hasExternalSubset = 0;
ctxt->hasPErefs = 0;
ctxt->html = 0;
ctxt->external = 0;
ctxt->instate = XML_PARSER_START;
ctxt->token = 0;
ctxt->directory = NULL;
/* Allocate the Node stack */
if (ctxt->nodeTab == NULL) {
ctxt->nodeTab = (xmlNodePtr *) xmlMalloc(10 * sizeof(xmlNodePtr));
ctxt->nodeMax = 10;
}
if (ctxt->nodeTab == NULL) {
xmlErrMemory(NULL, "cannot initialize parser context\n");
ctxt->nodeNr = 0;
ctxt->nodeMax = 0;
ctxt->node = NULL;
ctxt->inputNr = 0;
ctxt->inputMax = 0;
ctxt->input = NULL;
return(-1);
}
ctxt->nodeNr = 0;
ctxt->node = NULL;
/* Allocate the Name stack */
if (ctxt->nameTab == NULL) {
ctxt->nameTab = (const xmlChar **) xmlMalloc(10 * sizeof(xmlChar *));
ctxt->nameMax = 10;
}
if (ctxt->nameTab == NULL) {
xmlErrMemory(NULL, "cannot initialize parser context\n");
ctxt->nodeNr = 0;
ctxt->nodeMax = 0;
ctxt->node = NULL;
ctxt->inputNr = 0;
ctxt->inputMax = 0;
ctxt->input = NULL;
ctxt->nameNr = 0;
ctxt->nameMax = 0;
ctxt->name = NULL;
return(-1);
}
ctxt->nameNr = 0;
ctxt->name = NULL;
/* Allocate the space stack */
if (ctxt->spaceTab == NULL) {
ctxt->spaceTab = (int *) xmlMalloc(10 * sizeof(int));
ctxt->spaceMax = 10;
}
if (ctxt->spaceTab == NULL) {
xmlErrMemory(NULL, "cannot initialize parser context\n");
ctxt->nodeNr = 0;
ctxt->nodeMax = 0;
ctxt->node = NULL;
ctxt->inputNr = 0;
ctxt->inputMax = 0;
ctxt->input = NULL;
ctxt->nameNr = 0;
ctxt->nameMax = 0;
ctxt->name = NULL;
ctxt->spaceNr = 0;
ctxt->spaceMax = 0;
ctxt->space = NULL;
return(-1);
}
ctxt->spaceNr = 1;
ctxt->spaceMax = 10;
ctxt->spaceTab[0] = -1;
ctxt->space = &ctxt->spaceTab[0];
ctxt->userData = ctxt;
ctxt->myDoc = NULL;
ctxt->wellFormed = 1;
ctxt->nsWellFormed = 1;
ctxt->valid = 1;
ctxt->loadsubset = xmlLoadExtDtdDefaultValue;
ctxt->validate = xmlDoValidityCheckingDefaultValue;
ctxt->pedantic = xmlPedanticParserDefaultValue;
ctxt->linenumbers = xmlLineNumbersDefaultValue;
ctxt->keepBlanks = xmlKeepBlanksDefaultValue;
if (ctxt->keepBlanks == 0)
ctxt->sax->ignorableWhitespace = xmlSAX2IgnorableWhitespace;
ctxt->vctxt.finishDtd = XML_CTXT_FINISH_DTD_0;
ctxt->vctxt.userData = ctxt;
ctxt->vctxt.error = xmlParserValidityError;
ctxt->vctxt.warning = xmlParserValidityWarning;
if (ctxt->validate) {
if (xmlGetWarningsDefaultValue == 0)
ctxt->vctxt.warning = NULL;
else
ctxt->vctxt.warning = xmlParserValidityWarning;
ctxt->vctxt.nodeMax = 0;
}
ctxt->replaceEntities = xmlSubstituteEntitiesDefaultValue;
ctxt->record_info = 0;
ctxt->nbChars = 0;
ctxt->checkIndex = 0;
ctxt->inSubset = 0;
ctxt->errNo = XML_ERR_OK;
ctxt->depth = 0;
ctxt->charset = XML_CHAR_ENCODING_UTF8;
ctxt->catalogs = NULL;
ctxt->nbentities = 0;
ctxt->input_id = 1;
xmlInitNodeInfoSeq(&ctxt->node_seq);
return(0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Detect excessive entities expansion upon replacement
If entities expansion in the XML parser is asked for,
it is possble to craft relatively small input document leading
to excessive on-the-fly content generation.
This patch accounts for those replacement and stop parsing
after a given threshold. it can be bypassed as usual with the
HUGE parser option.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static inline int pmd_large(pmd_t pte)
{
return (pmd_flags(pte) & (_PAGE_PSE | _PAGE_PRESENT)) ==
(_PAGE_PSE | _PAGE_PRESENT);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'mm: thp: fix pmd_present for split_huge_page and PROT_NONE with THP
In many places !pmd_present has been converted to pmd_none. For pmds
that's equivalent and pmd_none is quicker so using pmd_none is better.
However (unless we delete pmd_present) we should provide an accurate
pmd_present too. This will avoid the risk of code thinking the pmd is non
present because it's under __split_huge_page_map, see the pmd_mknotpresent
there and the comment above it.
If the page has been mprotected as PROT_NONE, it would also lead to a
pmd_present false negative in the same way as the race with
split_huge_page.
Because the PSE bit stays on at all times (both during split_huge_page and
when the _PAGE_PROTNONE bit get set), we could only check for the PSE bit,
but checking the PROTNONE bit too is still good to remember pmd_present
must always keep PROT_NONE into account.
This explains a not reproducible BUG_ON that was seldom reported on the
lists.
The same issue is in pmd_large, it would go wrong with both PROT_NONE and
if it races with split_huge_page.
Signed-off-by: Andrea Arcangeli <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: Johannes Weiner <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: pkinit_check_kdc_pkid(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *pdid_buf,
unsigned int pkid_len,
int *valid_kdcPkId)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
PKCS7_ISSUER_AND_SERIAL *is = NULL;
const unsigned char *p = pdid_buf;
int status = 1;
X509 *kdc_cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index);
*valid_kdcPkId = 0;
pkiDebug("found kdcPkId in AS REQ\n");
is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p, (int)pkid_len);
if (is == NULL)
goto cleanup;
status = X509_NAME_cmp(X509_get_issuer_name(kdc_cert), is->issuer);
if (!status) {
status = ASN1_INTEGER_cmp(X509_get_serialNumber(kdc_cert), is->serial);
if (!status)
*valid_kdcPkId = 1;
}
retval = 0;
cleanup:
X509_NAME_free(is->issuer);
ASN1_INTEGER_free(is->serial);
free(is);
return retval;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'PKINIT null pointer deref [CVE-2013-1415]
Don't dereference a null pointer when cleaning up.
The KDC plugin for PKINIT can dereference a null pointer when a
malformed packet causes processing to terminate early, leading to
a crash of the KDC process. An attacker would need to have a valid
PKINIT certificate or have observed a successful PKINIT authentication,
or an unauthenticated attacker could execute the attack if anonymous
PKINIT is enabled.
CVSSv2 vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:P/RL:O/RC:C
This is a minimal commit for pullup; style fixes in a followup.
[[email protected]: reformat and edit commit message]
(cherry picked from commit c773d3c775e9b2d88bcdff5f8a8ba88d7ec4e8ed)
ticket: 7570
version_fixed: 1.11.1
status: resolved'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
bool pr = false;
u32 msr = msr_info->index;
u64 data = msr_info->data;
switch (msr) {
case MSR_AMD64_NB_CFG:
case MSR_IA32_UCODE_REV:
case MSR_IA32_UCODE_WRITE:
case MSR_VM_HSAVE_PA:
case MSR_AMD64_PATCH_LOADER:
case MSR_AMD64_BU_CFG2:
break;
case MSR_EFER:
return set_efer(vcpu, data);
case MSR_K7_HWCR:
data &= ~(u64)0x40; /* ignore flush filter disable */
data &= ~(u64)0x100; /* ignore ignne emulation enable */
data &= ~(u64)0x8; /* ignore TLB cache disable */
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
data);
return 1;
}
break;
case MSR_FAM10H_MMIO_CONF_BASE:
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
"0x%llx\n", data);
return 1;
}
break;
case MSR_IA32_DEBUGCTLMSR:
if (!data) {
/* We support the non-activated case already */
break;
} else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
/* Values other than LBR and BTF are vendor-specific,
thus reserved and should throw a #GP */
return 1;
}
vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
__func__, data);
break;
case 0x200 ... 0x2ff:
return set_msr_mtrr(vcpu, msr, data);
case MSR_IA32_APICBASE:
kvm_set_apic_base(vcpu, data);
break;
case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
return kvm_x2apic_msr_write(vcpu, msr, data);
case MSR_IA32_TSCDEADLINE:
kvm_set_lapic_tscdeadline_msr(vcpu, data);
break;
case MSR_IA32_TSC_ADJUST:
if (guest_cpuid_has_tsc_adjust(vcpu)) {
if (!msr_info->host_initiated) {
u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
}
vcpu->arch.ia32_tsc_adjust_msr = data;
}
break;
case MSR_IA32_MISC_ENABLE:
vcpu->arch.ia32_misc_enable_msr = data;
break;
case MSR_KVM_WALL_CLOCK_NEW:
case MSR_KVM_WALL_CLOCK:
vcpu->kvm->arch.wall_clock = data;
kvm_write_wall_clock(vcpu->kvm, data);
break;
case MSR_KVM_SYSTEM_TIME_NEW:
case MSR_KVM_SYSTEM_TIME: {
kvmclock_reset(vcpu);
vcpu->arch.time = data;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
/* we verify if the enable bit is set... */
if (!(data & 1))
break;
/* ...but clean it before doing the actual write */
vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
vcpu->arch.time_page =
gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
if (is_error_page(vcpu->arch.time_page))
vcpu->arch.time_page = NULL;
break;
}
case MSR_KVM_ASYNC_PF_EN:
if (kvm_pv_enable_async_pf(vcpu, data))
return 1;
break;
case MSR_KVM_STEAL_TIME:
if (unlikely(!sched_info_on()))
return 1;
if (data & KVM_STEAL_RESERVED_MASK)
return 1;
if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
data & KVM_STEAL_VALID_BITS))
return 1;
vcpu->arch.st.msr_val = data;
if (!(data & KVM_MSR_ENABLED))
break;
vcpu->arch.st.last_steal = current->sched_info.run_delay;
preempt_disable();
accumulate_steal_time(vcpu);
preempt_enable();
kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
break;
case MSR_KVM_PV_EOI_EN:
if (kvm_lapic_enable_pv_eoi(vcpu, data))
return 1;
break;
case MSR_IA32_MCG_CTL:
case MSR_IA32_MCG_STATUS:
case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
return set_msr_mce(vcpu, msr, data);
/* Performance counters are not protected by a CPUID bit,
* so we should check all of them in the generic path for the sake of
* cross vendor migration.
* Writing a zero into the event select MSRs disables them,
* which we perfectly emulate ;-). Any other value should be at least
* reported, some guests depend on them.
*/
case MSR_K7_EVNTSEL0:
case MSR_K7_EVNTSEL1:
case MSR_K7_EVNTSEL2:
case MSR_K7_EVNTSEL3:
if (data != 0)
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
/* at least RHEL 4 unconditionally writes to the perfctr registers,
* so we ignore writes to make it happy.
*/
case MSR_K7_PERFCTR0:
case MSR_K7_PERFCTR1:
case MSR_K7_PERFCTR2:
case MSR_K7_PERFCTR3:
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
pr = true;
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (pr || data != 0)
vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_K7_CLK_CTL:
/*
* Ignore all writes to this no longer documented MSR.
* Writes are only relevant for old K7 processors,
* all pre-dating SVM, but a recommended workaround from
* AMD for these chips. It is possible to specify the
* affected processor models on the command line, hence
* the need to ignore the workaround.
*/
break;
case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
if (kvm_hv_msr_partition_wide(msr)) {
int r;
mutex_lock(&vcpu->kvm->lock);
r = set_msr_hyperv_pw(vcpu, msr, data);
mutex_unlock(&vcpu->kvm->lock);
return r;
} else
return set_msr_hyperv(vcpu, msr, data);
break;
case MSR_IA32_BBL_CR_CTL3:
/* Drop writes to this legacy MSR -- see rdmsr
* counterpart for further detail.
*/
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
break;
case MSR_AMD64_OSVW_ID_LENGTH:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.length = data;
break;
case MSR_AMD64_OSVW_STATUS:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.status = data;
break;
default:
if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
return xen_hvm_config(vcpu, data);
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (!ignore_msrs) {
vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
msr, data);
return 1;
} else {
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
msr, data);
break;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'KVM: x86: fix for buffer overflow in handling of MSR_KVM_SYSTEM_TIME (CVE-2013-1796)
If the guest sets the GPA of the time_page so that the request to update the
time straddles a page then KVM will write onto an incorrect page. The
write is done byusing kmap atomic to get a pointer to the page for the time
structure and then performing a memcpy to that page starting at an offset
that the guest controls. Well behaved guests always provide a 32-byte aligned
address, however a malicious guest could use this to corrupt host kernel
memory.
Tested: Tested against kvmclock unit test.
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
bool pr = false;
u32 msr = msr_info->index;
u64 data = msr_info->data;
switch (msr) {
case MSR_AMD64_NB_CFG:
case MSR_IA32_UCODE_REV:
case MSR_IA32_UCODE_WRITE:
case MSR_VM_HSAVE_PA:
case MSR_AMD64_PATCH_LOADER:
case MSR_AMD64_BU_CFG2:
break;
case MSR_EFER:
return set_efer(vcpu, data);
case MSR_K7_HWCR:
data &= ~(u64)0x40; /* ignore flush filter disable */
data &= ~(u64)0x100; /* ignore ignne emulation enable */
data &= ~(u64)0x8; /* ignore TLB cache disable */
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
data);
return 1;
}
break;
case MSR_FAM10H_MMIO_CONF_BASE:
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
"0x%llx\n", data);
return 1;
}
break;
case MSR_IA32_DEBUGCTLMSR:
if (!data) {
/* We support the non-activated case already */
break;
} else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
/* Values other than LBR and BTF are vendor-specific,
thus reserved and should throw a #GP */
return 1;
}
vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
__func__, data);
break;
case 0x200 ... 0x2ff:
return set_msr_mtrr(vcpu, msr, data);
case MSR_IA32_APICBASE:
kvm_set_apic_base(vcpu, data);
break;
case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
return kvm_x2apic_msr_write(vcpu, msr, data);
case MSR_IA32_TSCDEADLINE:
kvm_set_lapic_tscdeadline_msr(vcpu, data);
break;
case MSR_IA32_TSC_ADJUST:
if (guest_cpuid_has_tsc_adjust(vcpu)) {
if (!msr_info->host_initiated) {
u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
}
vcpu->arch.ia32_tsc_adjust_msr = data;
}
break;
case MSR_IA32_MISC_ENABLE:
vcpu->arch.ia32_misc_enable_msr = data;
break;
case MSR_KVM_WALL_CLOCK_NEW:
case MSR_KVM_WALL_CLOCK:
vcpu->kvm->arch.wall_clock = data;
kvm_write_wall_clock(vcpu->kvm, data);
break;
case MSR_KVM_SYSTEM_TIME_NEW:
case MSR_KVM_SYSTEM_TIME: {
kvmclock_reset(vcpu);
vcpu->arch.time = data;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
/* we verify if the enable bit is set... */
if (!(data & 1))
break;
/* ...but clean it before doing the actual write */
vcpu->arch.time_offset = data & ~(PAGE_MASK | 1);
/* Check that the address is 32-byte aligned. */
if (vcpu->arch.time_offset &
(sizeof(struct pvclock_vcpu_time_info) - 1))
break;
vcpu->arch.time_page =
gfn_to_page(vcpu->kvm, data >> PAGE_SHIFT);
if (is_error_page(vcpu->arch.time_page))
vcpu->arch.time_page = NULL;
break;
}
case MSR_KVM_ASYNC_PF_EN:
if (kvm_pv_enable_async_pf(vcpu, data))
return 1;
break;
case MSR_KVM_STEAL_TIME:
if (unlikely(!sched_info_on()))
return 1;
if (data & KVM_STEAL_RESERVED_MASK)
return 1;
if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
data & KVM_STEAL_VALID_BITS))
return 1;
vcpu->arch.st.msr_val = data;
if (!(data & KVM_MSR_ENABLED))
break;
vcpu->arch.st.last_steal = current->sched_info.run_delay;
preempt_disable();
accumulate_steal_time(vcpu);
preempt_enable();
kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
break;
case MSR_KVM_PV_EOI_EN:
if (kvm_lapic_enable_pv_eoi(vcpu, data))
return 1;
break;
case MSR_IA32_MCG_CTL:
case MSR_IA32_MCG_STATUS:
case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
return set_msr_mce(vcpu, msr, data);
/* Performance counters are not protected by a CPUID bit,
* so we should check all of them in the generic path for the sake of
* cross vendor migration.
* Writing a zero into the event select MSRs disables them,
* which we perfectly emulate ;-). Any other value should be at least
* reported, some guests depend on them.
*/
case MSR_K7_EVNTSEL0:
case MSR_K7_EVNTSEL1:
case MSR_K7_EVNTSEL2:
case MSR_K7_EVNTSEL3:
if (data != 0)
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
/* at least RHEL 4 unconditionally writes to the perfctr registers,
* so we ignore writes to make it happy.
*/
case MSR_K7_PERFCTR0:
case MSR_K7_PERFCTR1:
case MSR_K7_PERFCTR2:
case MSR_K7_PERFCTR3:
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
pr = true;
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (pr || data != 0)
vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_K7_CLK_CTL:
/*
* Ignore all writes to this no longer documented MSR.
* Writes are only relevant for old K7 processors,
* all pre-dating SVM, but a recommended workaround from
* AMD for these chips. It is possible to specify the
* affected processor models on the command line, hence
* the need to ignore the workaround.
*/
break;
case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
if (kvm_hv_msr_partition_wide(msr)) {
int r;
mutex_lock(&vcpu->kvm->lock);
r = set_msr_hyperv_pw(vcpu, msr, data);
mutex_unlock(&vcpu->kvm->lock);
return r;
} else
return set_msr_hyperv(vcpu, msr, data);
break;
case MSR_IA32_BBL_CR_CTL3:
/* Drop writes to this legacy MSR -- see rdmsr
* counterpart for further detail.
*/
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
break;
case MSR_AMD64_OSVW_ID_LENGTH:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.length = data;
break;
case MSR_AMD64_OSVW_STATUS:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.status = data;
break;
default:
if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
return xen_hvm_config(vcpu, data);
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr, data);
if (!ignore_msrs) {
vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
msr, data);
return 1;
} else {
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
msr, data);
break;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797)
There is a potential use after free issue with the handling of
MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable
memory such as frame buffers then KVM might continue to write to that
address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins
the page in memory so it's unlikely to cause an issue, but if the user
space component re-purposes the memory previously used for the guest, then
the guest will be able to corrupt that memory.
Tested: Tested against kvmclock unit test
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: 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;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797)
There is a potential use after free issue with the handling of
MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable
memory such as frame buffers then KVM might continue to write to that
address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins
the page in memory so it's unlikely to cause an issue, but if the user
space component re-purposes the memory previously used for the guest, then
the guest will be able to corrupt that memory.
Tested: Tested against kvmclock unit test
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static unsigned long ioapic_read_indirect(struct kvm_ioapic *ioapic,
unsigned long addr,
unsigned long length)
{
unsigned long result = 0;
switch (ioapic->ioregsel) {
case IOAPIC_REG_VERSION:
result = ((((IOAPIC_NUM_PINS - 1) & 0xff) << 16)
| (IOAPIC_VERSION_ID & 0xff));
break;
case IOAPIC_REG_APIC_ID:
case IOAPIC_REG_ARB_ID:
result = ((ioapic->id & 0xf) << 24);
break;
default:
{
u32 redir_index = (ioapic->ioregsel - 0x10) >> 1;
u64 redir_content;
ASSERT(redir_index < IOAPIC_NUM_PINS);
redir_content = ioapic->redirtbl[redir_index].bits;
result = (ioapic->ioregsel & 0x1) ?
(redir_content >> 32) & 0xffffffff :
redir_content & 0xffffffff;
break;
}
}
return result;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'KVM: Fix bounds checking in ioapic indirect register reads (CVE-2013-1798)
If the guest specifies a IOAPIC_REG_SELECT with an invalid value and follows
that with a read of the IOAPIC_REG_WINDOW KVM does not properly validate
that request. ioapic_read_indirect contains an
ASSERT(redir_index < IOAPIC_NUM_PINS), but the ASSERT has no effect in
non-debug builds. In recent kernels this allows a guest to cause a kernel
oops by reading invalid memory. In older kernels (pre-3.3) this allows a
guest to read from large ranges of host memory.
Tested: tested against apic unit tests.
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
zend_bool old_allow_url_fopen;
/*
xmlInitParser();
*/
old_allow_url_fopen = PG(allow_url_fopen);
PG(allow_url_fopen) = 1;
ctxt = xmlCreateFileParserCtxt(filename);
PG(allow_url_fopen) = old_allow_url_fopen;
if (ctxt) {
ctxt->keepBlanks = 0;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
ctxt->sax->error = NULL;
/*ctxt->sax->fatalError = NULL;*/
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Disabled external entities loading'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
/*
xmlInitParser();
*/
ctxt = xmlCreateMemoryParserCtxt(buf, buf_size);
if (ctxt) {
ctxt->options -= XML_PARSE_DTDLOAD;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
ctxt->sax->error = NULL;
/*ctxt->sax->fatalError = NULL;*/
#if LIBXML_VERSION >= 20703
ctxt->options |= XML_PARSE_HUGE;
#endif
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
/*
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
*/
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Proper bit reset code'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: php_libxml_input_buffer_noload(const char *URI, xmlCharEncoding enc)
{
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Fixed external entity loading'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static PHP_FUNCTION(libxml_disable_entity_loader)
{
zend_bool disable = 1;
xmlParserInputBufferCreateFilenameFunc old;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &disable) == FAILURE) {
return;
}
if (disable == 0) {
old = xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_create_filename);
} else {
old = xmlParserInputBufferCreateFilenameDefault(php_libxml_input_buffer_noload);
}
if (old == php_libxml_input_buffer_noload) {
RETURN_TRUE;
}
RETURN_FALSE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Fixed external entity loading'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
zend_bool old_allow_url_fopen;
/*
xmlInitParser();
*/
old_allow_url_fopen = PG(allow_url_fopen);
PG(allow_url_fopen) = 1;
ctxt = xmlCreateFileParserCtxt(filename);
PG(allow_url_fopen) = old_allow_url_fopen;
if (ctxt) {
ctxt->keepBlanks = 0;
ctxt->options &= ~XML_PARSE_DTDLOAD;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
ctxt->sax->error = NULL;
/*ctxt->sax->fatalError = NULL;*/
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Fixed external entity loading'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
zend_bool old_allow_url_fopen;
/*
xmlInitParser();
*/
old_allow_url_fopen = PG(allow_url_fopen);
PG(allow_url_fopen) = 1;
ctxt = xmlCreateFileParserCtxt(filename);
PG(allow_url_fopen) = old_allow_url_fopen;
if (ctxt) {
zend_bool old;
ctxt->keepBlanks = 0;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
ctxt->sax->error = NULL;
/*ctxt->sax->fatalError = NULL;*/
old = php_libxml_disable_entity_loader(1);
xmlParseDocument(ctxt);
php_libxml_disable_entity_loader(old);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Fix TSRM (after afc1debb)'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int sctp_getsockopt_assoc_stats(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_stats sas;
struct sctp_association *asoc = NULL;
/* User must provide at least the assoc id */
if (len < sizeof(sctp_assoc_t))
return -EINVAL;
if (copy_from_user(&sas, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, sas.sas_assoc_id);
if (!asoc)
return -EINVAL;
sas.sas_rtxchunks = asoc->stats.rtxchunks;
sas.sas_gapcnt = asoc->stats.gapcnt;
sas.sas_outofseqtsns = asoc->stats.outofseqtsns;
sas.sas_osacks = asoc->stats.osacks;
sas.sas_isacks = asoc->stats.isacks;
sas.sas_octrlchunks = asoc->stats.octrlchunks;
sas.sas_ictrlchunks = asoc->stats.ictrlchunks;
sas.sas_oodchunks = asoc->stats.oodchunks;
sas.sas_iodchunks = asoc->stats.iodchunks;
sas.sas_ouodchunks = asoc->stats.ouodchunks;
sas.sas_iuodchunks = asoc->stats.iuodchunks;
sas.sas_idupchunks = asoc->stats.idupchunks;
sas.sas_opackets = asoc->stats.opackets;
sas.sas_ipackets = asoc->stats.ipackets;
/* New high max rto observed, will return 0 if not a single
* RTO update took place. obs_rto_ipaddr will be bogus
* in such a case
*/
sas.sas_maxrto = asoc->stats.max_obs_rto;
memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr,
sizeof(struct sockaddr_storage));
/* Mark beginning of a new observation period */
asoc->stats.max_obs_rto = asoc->rto_min;
/* Allow the struct to grow and fill in as much as possible */
len = min_t(size_t, len, sizeof(sas));
if (put_user(len, optlen))
return -EFAULT;
SCTP_DEBUG_PRINTK("sctp_getsockopt_assoc_stat(%d): %d\n",
len, sas.sas_assoc_id);
if (copy_to_user(optval, &sas, len))
return -EFAULT;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS
Building sctp may fail with:
In function ‘copy_from_user’,
inlined from ‘sctp_getsockopt_assoc_stats’ at
net/sctp/socket.c:5656:20:
arch/x86/include/asm/uaccess_32.h:211:26: error: call to
‘copy_from_user_overflow’ declared with attribute error: copy_from_user()
buffer size is not provably correct
if built with W=1 due to a missing parameter size validation
before the call to copy_from_user.
Signed-off-by: Guenter Roeck <[email protected]>
Acked-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static char *build_alias(char *alias, const char *device_name)
{
char *dest;
/* ">bar/": rename to bar/device_name */
/* ">bar[/]baz": rename to bar[/]baz */
dest = strrchr(alias, '/');
if (dest) { /* ">bar/[baz]" ? */
*dest = '\0'; /* mkdir bar */
bb_make_directory(alias, 0755, FILEUTILS_RECUR);
*dest = '/';
if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
dest = alias;
alias = concat_path_file(alias, device_name);
free(dest);
}
}
return alias;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'mdev: fix mode of dir1 in =dir1/dir2/file rule
Signed-off-by: Denys Vlasenko <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static ext3_fsblk_t get_sb_block(void **data, struct super_block *sb)
{
ext3_fsblk_t sb_block;
char *options = (char *) *data;
if (!options || strncmp(options, "sb=", 3) != 0)
return 1; /* Default location */
options += 3;
/*todo: use simple_strtoll with >32bit ext3 */
sb_block = simple_strtoul(options, &options, 0);
if (*options && *options != ',') {
ext3_msg(sb, "error: invalid sb specification: %s",
(char *) *data);
return 1;
}
if (*options == ',')
options++;
*data = (void *) options;
return sb_block;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'ext3: Fix format string issues
ext3_msg() takes the printk prefix as the second parameter and the
format string as the third parameter. Two callers of ext3_msg omit the
prefix and pass the format string as the second parameter and the first
parameter to the format string as the third parameter. In both cases
this string comes from an arbitrary source. Which means the string may
contain format string characters, which will
lead to undefined and potentially harmful behavior.
The issue was introduced in commit 4cf46b67eb("ext3: Unify log messages
in ext3") and is fixed by this patch.
CC: [email protected]
Signed-off-by: Lars-Peter Clausen <[email protected]>
Signed-off-by: Jan Kara <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int dcbnl_getperm_hwaddr(struct net_device *netdev, struct nlmsghdr *nlh,
u32 seq, struct nlattr **tb, struct sk_buff *skb)
{
u8 perm_addr[MAX_ADDR_LEN];
if (!netdev->dcbnl_ops->getpermhwaddr)
return -EOPNOTSUPP;
netdev->dcbnl_ops->getpermhwaddr(netdev, perm_addr);
return nla_put(skb, DCB_ATTR_PERM_HWADDR, sizeof(perm_addr), perm_addr);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'dcbnl: fix various netlink info leaks
The dcb netlink interface leaks stack memory in various places:
* perm_addr[] buffer is only filled at max with 12 of the 32 bytes but
copied completely,
* no in-kernel driver fills all fields of an IEEE 802.1Qaz subcommand,
so we're leaking up to 58 bytes for ieee_ets structs, up to 136 bytes
for ieee_pfc structs, etc.,
* the same is true for CEE -- no in-kernel driver fills the whole
struct,
Prevent all of the above stack info leaks by properly initializing the
buffers/structures involved.
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int rtnl_fill_ifinfo(struct sk_buff *skb, struct net_device *dev,
int type, u32 pid, u32 seq, u32 change,
unsigned int flags, u32 ext_filter_mask)
{
struct ifinfomsg *ifm;
struct nlmsghdr *nlh;
struct rtnl_link_stats64 temp;
const struct rtnl_link_stats64 *stats;
struct nlattr *attr, *af_spec;
struct rtnl_af_ops *af_ops;
struct net_device *upper_dev = netdev_master_upper_dev_get(dev);
ASSERT_RTNL();
nlh = nlmsg_put(skb, pid, seq, type, sizeof(*ifm), flags);
if (nlh == NULL)
return -EMSGSIZE;
ifm = nlmsg_data(nlh);
ifm->ifi_family = AF_UNSPEC;
ifm->__ifi_pad = 0;
ifm->ifi_type = dev->type;
ifm->ifi_index = dev->ifindex;
ifm->ifi_flags = dev_get_flags(dev);
ifm->ifi_change = change;
if (nla_put_string(skb, IFLA_IFNAME, dev->name) ||
nla_put_u32(skb, IFLA_TXQLEN, dev->tx_queue_len) ||
nla_put_u8(skb, IFLA_OPERSTATE,
netif_running(dev) ? dev->operstate : IF_OPER_DOWN) ||
nla_put_u8(skb, IFLA_LINKMODE, dev->link_mode) ||
nla_put_u32(skb, IFLA_MTU, dev->mtu) ||
nla_put_u32(skb, IFLA_GROUP, dev->group) ||
nla_put_u32(skb, IFLA_PROMISCUITY, dev->promiscuity) ||
nla_put_u32(skb, IFLA_NUM_TX_QUEUES, dev->num_tx_queues) ||
#ifdef CONFIG_RPS
nla_put_u32(skb, IFLA_NUM_RX_QUEUES, dev->num_rx_queues) ||
#endif
(dev->ifindex != dev->iflink &&
nla_put_u32(skb, IFLA_LINK, dev->iflink)) ||
(upper_dev &&
nla_put_u32(skb, IFLA_MASTER, upper_dev->ifindex)) ||
nla_put_u8(skb, IFLA_CARRIER, netif_carrier_ok(dev)) ||
(dev->qdisc &&
nla_put_string(skb, IFLA_QDISC, dev->qdisc->ops->id)) ||
(dev->ifalias &&
nla_put_string(skb, IFLA_IFALIAS, dev->ifalias)))
goto nla_put_failure;
if (1) {
struct rtnl_link_ifmap map = {
.mem_start = dev->mem_start,
.mem_end = dev->mem_end,
.base_addr = dev->base_addr,
.irq = dev->irq,
.dma = dev->dma,
.port = dev->if_port,
};
if (nla_put(skb, IFLA_MAP, sizeof(map), &map))
goto nla_put_failure;
}
if (dev->addr_len) {
if (nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr) ||
nla_put(skb, IFLA_BROADCAST, dev->addr_len, dev->broadcast))
goto nla_put_failure;
}
attr = nla_reserve(skb, IFLA_STATS,
sizeof(struct rtnl_link_stats));
if (attr == NULL)
goto nla_put_failure;
stats = dev_get_stats(dev, &temp);
copy_rtnl_link_stats(nla_data(attr), stats);
attr = nla_reserve(skb, IFLA_STATS64,
sizeof(struct rtnl_link_stats64));
if (attr == NULL)
goto nla_put_failure;
copy_rtnl_link_stats64(nla_data(attr), stats);
if (dev->dev.parent && (ext_filter_mask & RTEXT_FILTER_VF) &&
nla_put_u32(skb, IFLA_NUM_VF, dev_num_vf(dev->dev.parent)))
goto nla_put_failure;
if (dev->netdev_ops->ndo_get_vf_config && dev->dev.parent
&& (ext_filter_mask & RTEXT_FILTER_VF)) {
int i;
struct nlattr *vfinfo, *vf;
int num_vfs = dev_num_vf(dev->dev.parent);
vfinfo = nla_nest_start(skb, IFLA_VFINFO_LIST);
if (!vfinfo)
goto nla_put_failure;
for (i = 0; i < num_vfs; i++) {
struct ifla_vf_info ivi;
struct ifla_vf_mac vf_mac;
struct ifla_vf_vlan vf_vlan;
struct ifla_vf_tx_rate vf_tx_rate;
struct ifla_vf_spoofchk vf_spoofchk;
/*
* Not all SR-IOV capable drivers support the
* spoofcheck query. Preset to -1 so the user
* space tool can detect that the driver didn't
* report anything.
*/
ivi.spoofchk = -1;
if (dev->netdev_ops->ndo_get_vf_config(dev, i, &ivi))
break;
vf_mac.vf =
vf_vlan.vf =
vf_tx_rate.vf =
vf_spoofchk.vf = ivi.vf;
memcpy(vf_mac.mac, ivi.mac, sizeof(ivi.mac));
vf_vlan.vlan = ivi.vlan;
vf_vlan.qos = ivi.qos;
vf_tx_rate.rate = ivi.tx_rate;
vf_spoofchk.setting = ivi.spoofchk;
vf = nla_nest_start(skb, IFLA_VF_INFO);
if (!vf) {
nla_nest_cancel(skb, vfinfo);
goto nla_put_failure;
}
if (nla_put(skb, IFLA_VF_MAC, sizeof(vf_mac), &vf_mac) ||
nla_put(skb, IFLA_VF_VLAN, sizeof(vf_vlan), &vf_vlan) ||
nla_put(skb, IFLA_VF_TX_RATE, sizeof(vf_tx_rate),
&vf_tx_rate) ||
nla_put(skb, IFLA_VF_SPOOFCHK, sizeof(vf_spoofchk),
&vf_spoofchk))
goto nla_put_failure;
nla_nest_end(skb, vf);
}
nla_nest_end(skb, vfinfo);
}
if (rtnl_port_fill(skb, dev))
goto nla_put_failure;
if (dev->rtnl_link_ops) {
if (rtnl_link_fill(skb, dev) < 0)
goto nla_put_failure;
}
if (!(af_spec = nla_nest_start(skb, IFLA_AF_SPEC)))
goto nla_put_failure;
list_for_each_entry(af_ops, &rtnl_af_ops, list) {
if (af_ops->fill_link_af) {
struct nlattr *af;
int err;
if (!(af = nla_nest_start(skb, af_ops->family)))
goto nla_put_failure;
err = af_ops->fill_link_af(skb, dev);
/*
* Caller may return ENODATA to indicate that there
* was no data to be dumped. This is not an error, it
* means we should trim the attribute header and
* continue.
*/
if (err == -ENODATA)
nla_nest_cancel(skb, af);
else if (err < 0)
goto nla_put_failure;
nla_nest_end(skb, af);
}
}
nla_nest_end(skb, af_spec);
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'rtnl: fix info leak on RTM_GETLINK request for VF devices
Initialize the mac address buffer with 0 as the driver specific function
will probably not fill the whole buffer. In fact, all in-kernel drivers
fill only ETH_ALEN of the MAX_ADDR_LEN bytes, i.e. 6 of the 32 possible
bytes. Therefore we currently leak 26 bytes of stack memory to userland
via the netlink interface.
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int br_mdb_fill_info(struct sk_buff *skb, struct netlink_callback *cb,
struct net_device *dev)
{
struct net_bridge *br = netdev_priv(dev);
struct net_bridge_mdb_htable *mdb;
struct nlattr *nest, *nest2;
int i, err = 0;
int idx = 0, s_idx = cb->args[1];
if (br->multicast_disabled)
return 0;
mdb = rcu_dereference(br->mdb);
if (!mdb)
return 0;
nest = nla_nest_start(skb, MDBA_MDB);
if (nest == NULL)
return -EMSGSIZE;
for (i = 0; i < mdb->max; i++) {
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p, **pp;
struct net_bridge_port *port;
hlist_for_each_entry_rcu(mp, &mdb->mhash[i], hlist[mdb->ver]) {
if (idx < s_idx)
goto skip;
nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY);
if (nest2 == NULL) {
err = -EMSGSIZE;
goto out;
}
for (pp = &mp->ports;
(p = rcu_dereference(*pp)) != NULL;
pp = &p->next) {
port = p->port;
if (port) {
struct br_mdb_entry e;
e.ifindex = port->dev->ifindex;
e.state = p->state;
if (p->addr.proto == htons(ETH_P_IP))
e.addr.u.ip4 = p->addr.u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
if (p->addr.proto == htons(ETH_P_IPV6))
e.addr.u.ip6 = p->addr.u.ip6;
#endif
e.addr.proto = p->addr.proto;
if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(e), &e)) {
nla_nest_cancel(skb, nest2);
err = -EMSGSIZE;
goto out;
}
}
}
nla_nest_end(skb, nest2);
skip:
idx++;
}
}
out:
cb->args[1] = idx;
nla_nest_end(skb, nest);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'bridge: fix mdb info leaks
The bridging code discloses heap and stack bytes via the RTM_GETMDB
netlink interface and via the notify messages send to group RTNLGRP_MDB
afer a successful add/del.
Fix both cases by initializing all unset members/padding bytes with
memset(0).
Cc: Stephen Hemminger <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void br_mdb_notify(struct net_device *dev, struct net_bridge_port *port,
struct br_ip *group, int type)
{
struct br_mdb_entry entry;
entry.ifindex = port->dev->ifindex;
entry.addr.proto = group->proto;
entry.addr.u.ip4 = group->u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
entry.addr.u.ip6 = group->u.ip6;
#endif
__br_mdb_notify(dev, &entry, type);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'bridge: fix mdb info leaks
The bridging code discloses heap and stack bytes via the RTM_GETMDB
netlink interface and via the notify messages send to group RTNLGRP_MDB
afer a successful add/del.
Fix both cases by initializing all unset members/padding bytes with
memset(0).
Cc: Stephen Hemminger <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int xml_init(modsec_rec *msr, char **error_msg) {
if (error_msg == NULL) return -1;
*error_msg = NULL;
msr->xml = apr_pcalloc(msr->mp, sizeof(xml_data));
if (msr->xml == NULL) return -1;
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-611'], 'message': 'Added SecXmlExternalEntity'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: void *merge_directory_configs(apr_pool_t *mp, void *_parent, void *_child)
{
directory_config *parent = (directory_config *)_parent;
directory_config *child = (directory_config *)_child;
directory_config *merged = create_directory_config(mp, NULL);
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "Merge parent %pp child %pp RESULT %pp", _parent, _child, merged);
#endif
if (merged == NULL) return NULL;
/* Use values from the child configuration where possible,
* otherwise use the parent's.
*/
merged->is_enabled = (child->is_enabled == NOT_SET
? parent->is_enabled : child->is_enabled);
/* IO parameters */
merged->reqbody_access = (child->reqbody_access == NOT_SET
? parent->reqbody_access : child->reqbody_access);
merged->reqbody_buffering = (child->reqbody_buffering == NOT_SET
? parent->reqbody_buffering : child->reqbody_buffering);
merged->reqbody_inmemory_limit = (child->reqbody_inmemory_limit == NOT_SET
? parent->reqbody_inmemory_limit : child->reqbody_inmemory_limit);
merged->reqbody_limit = (child->reqbody_limit == NOT_SET
? parent->reqbody_limit : child->reqbody_limit);
merged->reqbody_no_files_limit = (child->reqbody_no_files_limit == NOT_SET
? parent->reqbody_no_files_limit : child->reqbody_no_files_limit);
merged->resbody_access = (child->resbody_access == NOT_SET
? parent->resbody_access : child->resbody_access);
merged->of_limit = (child->of_limit == NOT_SET
? parent->of_limit : child->of_limit);
merged->if_limit_action = (child->if_limit_action == NOT_SET
? parent->if_limit_action : child->if_limit_action);
merged->of_limit_action = (child->of_limit_action == NOT_SET
? parent->of_limit_action : child->of_limit_action);
merged->reqintercept_oe = (child->reqintercept_oe == NOT_SET
? parent->reqintercept_oe : child->reqintercept_oe);
if (child->of_mime_types != NOT_SET_P) {
/* Child added to the table */
if (child->of_mime_types_cleared == 1) {
/* The list of MIME types was cleared in the child,
* which means the parent's MIME types went away and
* we should not take them into consideration here.
*/
merged->of_mime_types = child->of_mime_types;
merged->of_mime_types_cleared = 1;
} else {
/* Add MIME types defined in the child to those
* defined in the parent context.
*/
if (parent->of_mime_types == NOT_SET_P) {
merged->of_mime_types = child->of_mime_types;
merged->of_mime_types_cleared = NOT_SET;
} else {
merged->of_mime_types = apr_table_overlay(mp, parent->of_mime_types,
child->of_mime_types);
if (merged->of_mime_types == NULL) return NULL;
}
}
} else {
/* Child did not add to the table */
if (child->of_mime_types_cleared == 1) {
merged->of_mime_types_cleared = 1;
} else {
merged->of_mime_types = parent->of_mime_types;
merged->of_mime_types_cleared = parent->of_mime_types_cleared;
}
}
/* debug log */
if (child->debuglog_fd == NOT_SET_P) {
merged->debuglog_name = parent->debuglog_name;
merged->debuglog_fd = parent->debuglog_fd;
} else {
merged->debuglog_name = child->debuglog_name;
merged->debuglog_fd = child->debuglog_fd;
}
merged->debuglog_level = (child->debuglog_level == NOT_SET
? parent->debuglog_level : child->debuglog_level);
merged->cookie_format = (child->cookie_format == NOT_SET
? parent->cookie_format : child->cookie_format);
merged->argument_separator = (child->argument_separator == NOT_SET
? parent->argument_separator : child->argument_separator);
merged->cookiev0_separator = (child->cookiev0_separator == NOT_SET_P
? parent->cookiev0_separator : child->cookiev0_separator);
/* rule inheritance */
if ((child->rule_inheritance == NOT_SET)||(child->rule_inheritance == 1)) {
merged->rule_inheritance = parent->rule_inheritance;
if ((child->ruleset == NULL)&&(parent->ruleset == NULL)) {
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "No rules in this context.");
#endif
/* Do nothing, there are no rules in either context. */
} else
if (child->ruleset == NULL) {
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "Using parent rules in this context.");
#endif
/* Copy the rules from the parent context. */
merged->ruleset = msre_ruleset_create(parent->ruleset->engine, mp);
copy_rules(mp, parent->ruleset, merged->ruleset, child->rule_exceptions);
} else
if (parent->ruleset == NULL) {
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "Using child rules in this context.");
#endif
/* Copy child rules. */
merged->ruleset = msre_ruleset_create(child->ruleset->engine, mp);
merged->ruleset->phase_request_headers = apr_array_copy(mp,
child->ruleset->phase_request_headers);
merged->ruleset->phase_request_body = apr_array_copy(mp,
child->ruleset->phase_request_body);
merged->ruleset->phase_response_headers = apr_array_copy(mp,
child->ruleset->phase_response_headers);
merged->ruleset->phase_response_body = apr_array_copy(mp,
child->ruleset->phase_response_body);
merged->ruleset->phase_logging = apr_array_copy(mp,
child->ruleset->phase_logging);
} else {
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "Using parent then child rules in this context.");
#endif
/* Copy parent rules, then add child rules to it. */
merged->ruleset = msre_ruleset_create(parent->ruleset->engine, mp);
copy_rules(mp, parent->ruleset, merged->ruleset, child->rule_exceptions);
apr_array_cat(merged->ruleset->phase_request_headers,
child->ruleset->phase_request_headers);
apr_array_cat(merged->ruleset->phase_request_body,
child->ruleset->phase_request_body);
apr_array_cat(merged->ruleset->phase_response_headers,
child->ruleset->phase_response_headers);
apr_array_cat(merged->ruleset->phase_response_body,
child->ruleset->phase_response_body);
apr_array_cat(merged->ruleset->phase_logging,
child->ruleset->phase_logging);
}
} else {
merged->rule_inheritance = 0;
if (child->ruleset != NULL) {
/* Copy child rules. */
merged->ruleset = msre_ruleset_create(child->ruleset->engine, mp);
merged->ruleset->phase_request_headers = apr_array_copy(mp,
child->ruleset->phase_request_headers);
merged->ruleset->phase_request_body = apr_array_copy(mp,
child->ruleset->phase_request_body);
merged->ruleset->phase_response_headers = apr_array_copy(mp,
child->ruleset->phase_response_headers);
merged->ruleset->phase_response_body = apr_array_copy(mp,
child->ruleset->phase_response_body);
merged->ruleset->phase_logging = apr_array_copy(mp,
child->ruleset->phase_logging);
}
}
/* Merge rule exceptions. */
merged->rule_exceptions = apr_array_append(mp, parent->rule_exceptions,
child->rule_exceptions);
merged->hash_method = apr_array_append(mp, parent->hash_method,
child->hash_method);
/* audit log variables */
merged->auditlog_flag = (child->auditlog_flag == NOT_SET
? parent->auditlog_flag : child->auditlog_flag);
merged->auditlog_type = (child->auditlog_type == NOT_SET
? parent->auditlog_type : child->auditlog_type);
merged->max_rule_time = (child->max_rule_time == NOT_SET
? parent->max_rule_time : child->max_rule_time);
merged->auditlog_dirperms = (child->auditlog_dirperms == NOT_SET
? parent->auditlog_dirperms : child->auditlog_dirperms);
merged->auditlog_fileperms = (child->auditlog_fileperms == NOT_SET
? parent->auditlog_fileperms : child->auditlog_fileperms);
if (child->auditlog_fd != NOT_SET_P) {
merged->auditlog_fd = child->auditlog_fd;
merged->auditlog_name = child->auditlog_name;
} else {
merged->auditlog_fd = parent->auditlog_fd;
merged->auditlog_name = parent->auditlog_name;
}
if (child->auditlog2_fd != NOT_SET_P) {
merged->auditlog2_fd = child->auditlog2_fd;
merged->auditlog2_name = child->auditlog2_name;
} else {
merged->auditlog2_fd = parent->auditlog2_fd;
merged->auditlog2_name = parent->auditlog2_name;
}
merged->auditlog_storage_dir = (child->auditlog_storage_dir == NOT_SET_P
? parent->auditlog_storage_dir : child->auditlog_storage_dir);
merged->auditlog_parts = (child->auditlog_parts == NOT_SET_P
? parent->auditlog_parts : child->auditlog_parts);
merged->auditlog_relevant_regex = (child->auditlog_relevant_regex == NOT_SET_P
? parent->auditlog_relevant_regex : child->auditlog_relevant_regex);
/* Upload */
merged->tmp_dir = (child->tmp_dir == NOT_SET_P
? parent->tmp_dir : child->tmp_dir);
merged->upload_dir = (child->upload_dir == NOT_SET_P
? parent->upload_dir : child->upload_dir);
merged->upload_keep_files = (child->upload_keep_files == NOT_SET
? parent->upload_keep_files : child->upload_keep_files);
merged->upload_validates_files = (child->upload_validates_files == NOT_SET
? parent->upload_validates_files : child->upload_validates_files);
merged->upload_filemode = (child->upload_filemode == NOT_SET
? parent->upload_filemode : child->upload_filemode);
merged->upload_file_limit = (child->upload_file_limit == NOT_SET
? parent->upload_file_limit : child->upload_file_limit);
/* Misc */
merged->data_dir = (child->data_dir == NOT_SET_P
? parent->data_dir : child->data_dir);
merged->webappid = (child->webappid == NOT_SET_P
? parent->webappid : child->webappid);
merged->sensor_id = (child->sensor_id == NOT_SET_P
? parent->sensor_id : child->sensor_id);
merged->httpBlkey = (child->httpBlkey == NOT_SET_P
? parent->httpBlkey : child->httpBlkey);
/* Content injection. */
merged->content_injection_enabled = (child->content_injection_enabled == NOT_SET
? parent->content_injection_enabled : child->content_injection_enabled);
/* Stream inspection */
merged->stream_inbody_inspection = (child->stream_inbody_inspection == NOT_SET
? parent->stream_inbody_inspection : child->stream_inbody_inspection);
merged->stream_outbody_inspection = (child->stream_outbody_inspection == NOT_SET
? parent->stream_outbody_inspection : child->stream_outbody_inspection);
/* Geo Lookup */
merged->geo = (child->geo == NOT_SET_P
? parent->geo : child->geo);
/* Gsb Lookup */
merged->gsb = (child->gsb == NOT_SET_P
? parent->gsb : child->gsb);
/* Unicode Map */
merged->u_map = (child->u_map == NOT_SET_P
? parent->u_map : child->u_map);
/* Cache */
merged->cache_trans = (child->cache_trans == NOT_SET
? parent->cache_trans : child->cache_trans);
merged->cache_trans_incremental = (child->cache_trans_incremental == NOT_SET
? parent->cache_trans_incremental : child->cache_trans_incremental);
merged->cache_trans_min = (child->cache_trans_min == (apr_size_t)NOT_SET
? parent->cache_trans_min : child->cache_trans_min);
merged->cache_trans_max = (child->cache_trans_max == (apr_size_t)NOT_SET
? parent->cache_trans_max : child->cache_trans_max);
merged->cache_trans_maxitems = (child->cache_trans_maxitems == (apr_size_t)NOT_SET
? parent->cache_trans_maxitems : child->cache_trans_maxitems);
/* Merge component signatures. */
merged->component_signatures = apr_array_append(mp, parent->component_signatures,
child->component_signatures);
merged->request_encoding = (child->request_encoding == NOT_SET_P
? parent->request_encoding : child->request_encoding);
merged->disable_backend_compression = (child->disable_backend_compression == NOT_SET
? parent->disable_backend_compression : child->disable_backend_compression);
merged->col_timeout = (child->col_timeout == NOT_SET
? parent->col_timeout : child->col_timeout);
/* Hash */
merged->crypto_key = (child->crypto_key == NOT_SET_P
? parent->crypto_key : child->crypto_key);
merged->crypto_key_len = (child->crypto_key_len == NOT_SET
? parent->crypto_key_len : child->crypto_key_len);
merged->crypto_key_add = (child->crypto_key_add == NOT_SET
? parent->crypto_key_add : child->crypto_key_add);
merged->crypto_param_name = (child->crypto_param_name == NOT_SET_P
? parent->crypto_param_name : child->crypto_param_name);
merged->hash_is_enabled = (child->hash_is_enabled == NOT_SET
? parent->hash_is_enabled : child->hash_is_enabled);
merged->hash_enforcement = (child->hash_enforcement == NOT_SET
? parent->hash_enforcement : child->hash_enforcement);
merged->crypto_hash_href_rx = (child->crypto_hash_href_rx == NOT_SET
? parent->crypto_hash_href_rx : child->crypto_hash_href_rx);
merged->crypto_hash_faction_rx = (child->crypto_hash_faction_rx == NOT_SET
? parent->crypto_hash_faction_rx : child->crypto_hash_faction_rx);
merged->crypto_hash_location_rx = (child->crypto_hash_location_rx == NOT_SET
? parent->crypto_hash_location_rx : child->crypto_hash_location_rx);
merged->crypto_hash_iframesrc_rx = (child->crypto_hash_iframesrc_rx == NOT_SET
? parent->crypto_hash_iframesrc_rx : child->crypto_hash_iframesrc_rx);
merged->crypto_hash_framesrc_rx = (child->crypto_hash_framesrc_rx == NOT_SET
? parent->crypto_hash_framesrc_rx : child->crypto_hash_framesrc_rx);
merged->crypto_hash_href_pm = (child->crypto_hash_href_pm == NOT_SET
? parent->crypto_hash_href_pm : child->crypto_hash_href_pm);
merged->crypto_hash_faction_pm = (child->crypto_hash_faction_pm == NOT_SET
? parent->crypto_hash_faction_pm : child->crypto_hash_faction_pm);
merged->crypto_hash_location_pm = (child->crypto_hash_location_pm == NOT_SET
? parent->crypto_hash_location_pm : child->crypto_hash_location_pm);
merged->crypto_hash_iframesrc_pm = (child->crypto_hash_iframesrc_pm == NOT_SET
? parent->crypto_hash_iframesrc_pm : child->crypto_hash_iframesrc_pm);
merged->crypto_hash_framesrc_pm = (child->crypto_hash_framesrc_pm == NOT_SET
? parent->crypto_hash_framesrc_pm : child->crypto_hash_framesrc_pm);
return merged;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-611'], 'message': 'Added SecXmlExternalEntity'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: load_image (const gchar *filename,
GError **error)
{
FILE *ifp;
gint depth, bpp;
gint32 image_ID;
L_XWDFILEHEADER xwdhdr;
L_XWDCOLOR *xwdcolmap = NULL;
ifp = g_fopen (filename, "rb");
if (!ifp)
{
g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno),
_("Could not open '%s' for reading: %s"),
gimp_filename_to_utf8 (filename), g_strerror (errno));
return -1;
}
read_xwd_header (ifp, &xwdhdr);
if (xwdhdr.l_file_version != 7)
{
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("Could not read XWD header from '%s'"),
gimp_filename_to_utf8 (filename));
fclose (ifp);
return -1;
}
#ifdef XWD_COL_WAIT_DEBUG
{
int k = 1;
while (k)
k = k;
}
#endif
/* Position to start of XWDColor structures */
fseek (ifp, (long)xwdhdr.l_header_size, SEEK_SET);
if (xwdhdr.l_colormap_entries > 0)
{
xwdcolmap = g_new (L_XWDCOLOR, xwdhdr.l_colormap_entries);
read_xwd_cols (ifp, &xwdhdr, xwdcolmap);
#ifdef XWD_COL_DEBUG
{
int j;
printf ("File %s\n",filename);
for (j = 0; j < xwdhdr.l_colormap_entries; j++)
printf ("Entry 0x%08lx: 0x%04lx, 0x%04lx, 0x%04lx, %d\n",
(long)xwdcolmap[j].l_pixel,(long)xwdcolmap[j].l_red,
(long)xwdcolmap[j].l_green,(long)xwdcolmap[j].l_blue,
(int)xwdcolmap[j].l_flags);
}
#endif
if (xwdhdr.l_file_version != 7)
{
g_message (_("Can't read color entries"));
g_free (xwdcolmap);
fclose (ifp);
return (-1);
}
}
if (xwdhdr.l_pixmap_width <= 0)
{
g_message (_("'%s':\nNo image width specified"),
gimp_filename_to_utf8 (filename));
g_free (xwdcolmap);
fclose (ifp);
return (-1);
}
if (xwdhdr.l_pixmap_width > GIMP_MAX_IMAGE_SIZE
|| xwdhdr.l_bytes_per_line > GIMP_MAX_IMAGE_SIZE * 3)
{
g_message (_("'%s':\nImage width is larger than GIMP can handle"),
gimp_filename_to_utf8 (filename));
g_free (xwdcolmap);
fclose (ifp);
return (-1);
}
if (xwdhdr.l_pixmap_height <= 0)
{
g_message (_("'%s':\nNo image height specified"),
gimp_filename_to_utf8 (filename));
g_free (xwdcolmap);
fclose (ifp);
return (-1);
}
if (xwdhdr.l_pixmap_height > GIMP_MAX_IMAGE_SIZE)
{
g_message (_("'%s':\nImage height is larger than GIMP can handle"),
gimp_filename_to_utf8 (filename));
g_free (xwdcolmap);
fclose (ifp);
return (-1);
}
gimp_progress_init_printf (_("Opening '%s'"),
gimp_filename_to_utf8 (filename));
depth = xwdhdr.l_pixmap_depth;
bpp = xwdhdr.l_bits_per_pixel;
image_ID = -1;
switch (xwdhdr.l_pixmap_format)
{
case 0: /* Single plane bitmap */
if ((depth == 1) && (bpp == 1))
{ /* Can be performed by format 2 loader */
image_ID = load_xwd_f2_d1_b1 (filename, ifp, &xwdhdr, xwdcolmap);
}
break;
case 1: /* Single plane pixmap */
if ((depth <= 24) && (bpp == 1))
{
image_ID = load_xwd_f1_d24_b1 (filename, ifp, &xwdhdr, xwdcolmap,
error);
}
break;
case 2: /* Multiplane pixmaps */
if ((depth == 1) && (bpp == 1))
{
image_ID = load_xwd_f2_d1_b1 (filename, ifp, &xwdhdr, xwdcolmap);
}
else if ((depth <= 8) && (bpp == 8))
{
image_ID = load_xwd_f2_d8_b8 (filename, ifp, &xwdhdr, xwdcolmap);
}
else if ((depth <= 16) && (bpp == 16))
{
image_ID = load_xwd_f2_d16_b16 (filename, ifp, &xwdhdr, xwdcolmap);
}
else if ((depth <= 24) && ((bpp == 24) || (bpp == 32)))
{
image_ID = load_xwd_f2_d24_b32 (filename, ifp, &xwdhdr, xwdcolmap,
error);
}
else if ((depth <= 32) && (bpp == 32))
{
image_ID = load_xwd_f2_d32_b32 (filename, ifp, &xwdhdr, xwdcolmap);
}
break;
}
gimp_progress_update (1.0);
fclose (ifp);
if (xwdcolmap)
g_free (xwdcolmap);
if (image_ID == -1 && ! (error && *error))
g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED,
_("XWD-file %s has format %d, depth %d and bits per pixel %d. "
"Currently this is not supported."),
gimp_filename_to_utf8 (filename),
(gint) xwdhdr.l_pixmap_format, depth, bpp);
return image_ID;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'file-xwd: sanity check colormap size (CVE-2013-1913)'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
int len)
{
int r;
unsigned long addr;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return -EFAULT;
r = copy_from_user(data, (void __user *)addr + offset, len);
if (r)
return -EFAULT;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'KVM: Validate userspace_addr of memslot when registered
This way, we can avoid checking the user space address many times when
we read the guest memory.
Although we can do the same for write if we check which slots are
writable, we do not care write now: reading the guest memory happens
more often than writing.
[avi: change VERIFY_READ to VERIFY_WRITE]
Signed-off-by: Takuya Yoshikawa <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int __kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
int user_alloc)
{
int r;
gfn_t base_gfn;
unsigned long npages;
unsigned long i;
struct kvm_memory_slot *memslot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots, *old_memslots;
r = -EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGE_SIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGE_SIZE - 1))
goto out;
if (user_alloc && (mem->userspace_addr & (PAGE_SIZE - 1)))
goto out;
if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
memslot = &kvm->memslots->memslots[mem->slot];
base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
npages = mem->memory_size >> PAGE_SHIFT;
r = -EINVAL;
if (npages > KVM_MEM_MAX_NR_PAGES)
goto out;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *memslot;
new.id = mem->slot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
/* Disallow changing a memory slot's size. */
r = -EINVAL;
if (npages && old.npages && npages != old.npages)
goto out_free;
/* Check for overlaps */
r = -EEXIST;
for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
struct kvm_memory_slot *s = &kvm->memslots->memslots[i];
if (s == memslot || !s->npages)
continue;
if (!((base_gfn + npages <= s->base_gfn) ||
(base_gfn >= s->base_gfn + s->npages)))
goto out_free;
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = -ENOMEM;
/* Allocate if a slot is being created */
#ifndef CONFIG_S390
if (npages && !new.rmap) {
new.rmap = vzalloc(npages * sizeof(*new.rmap));
if (!new.rmap)
goto out_free;
new.user_alloc = user_alloc;
new.userspace_addr = mem->userspace_addr;
}
if (!npages)
goto skip_lpage;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
unsigned long ugfn;
unsigned long j;
int lpages;
int level = i + 2;
/* Avoid unused variable warning if no large pages */
(void)level;
if (new.lpage_info[i])
continue;
lpages = 1 + ((base_gfn + npages - 1)
>> KVM_HPAGE_GFN_SHIFT(level));
lpages -= base_gfn >> KVM_HPAGE_GFN_SHIFT(level);
new.lpage_info[i] = vzalloc(lpages * sizeof(*new.lpage_info[i]));
if (!new.lpage_info[i])
goto out_free;
if (base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][0].write_count = 1;
if ((base_gfn+npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][lpages - 1].write_count = 1;
ugfn = new.userspace_addr >> PAGE_SHIFT;
/*
* If the gfn and userspace address are not aligned wrt each
* other, or if explicitly asked to, disable large page
* support for this slot
*/
if ((base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
!largepages_enabled)
for (j = 0; j < lpages; ++j)
new.lpage_info[i][j].write_count = 1;
}
skip_lpage:
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
if (kvm_create_dirty_bitmap(&new) < 0)
goto out_free;
/* destroy any largepage mappings for dirty tracking */
}
#else /* not defined CONFIG_S390 */
new.user_alloc = user_alloc;
if (user_alloc)
new.userspace_addr = mem->userspace_addr;
#endif /* not defined CONFIG_S390 */
if (!npages) {
r = -ENOMEM;
slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!slots)
goto out_free;
memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
if (mem->slot >= slots->nmemslots)
slots->nmemslots = mem->slot + 1;
slots->generation++;
slots->memslots[mem->slot].flags |= KVM_MEMSLOT_INVALID;
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
/* From this point no new shadow pages pointing to a deleted
* memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow(kvm);
kfree(old_memslots);
}
r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
if (r)
goto out_free;
/* map the pages in iommu page table */
if (npages) {
r = kvm_iommu_map_pages(kvm, &new);
if (r)
goto out_free;
}
r = -ENOMEM;
slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!slots)
goto out_free;
memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
if (mem->slot >= slots->nmemslots)
slots->nmemslots = mem->slot + 1;
slots->generation++;
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (!npages) {
new.rmap = NULL;
new.dirty_bitmap = NULL;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i)
new.lpage_info[i] = NULL;
}
slots->memslots[mem->slot] = new;
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
kvm_free_physmem_slot(&old, &new);
kfree(old_memslots);
return 0;
out_free:
kvm_free_physmem_slot(&new, &old);
out:
return r;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'KVM: Validate userspace_addr of memslot when registered
This way, we can avoid checking the user space address many times when
we read the guest memory.
Although we can do the same for write if we check which slots are
writable, we do not care write now: reading the guest memory happens
more often than writing.
[avi: change VERIFY_READ to VERIFY_WRITE]
Signed-off-by: Takuya Yoshikawa <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static bool tailmatch(const char *little, const char *bigone)
{
size_t littlelen = strlen(little);
size_t biglen = strlen(bigone);
if(littlelen > biglen)
return FALSE;
return Curl_raw_equal(little, bigone+biglen-littlelen) ? TRUE : FALSE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'cookie: fix tailmatching to prevent cross-domain leakage
Cookies set for 'example.com' could accidentaly also be sent by libcurl
to the 'bexample.com' (ie with a prefix to the first domain name).
This is a security vulnerabilty, CVE-2013-1944.
Bug: http://curl.haxx.se/docs/adv_20130412.html'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: htmlParseChunk(htmlParserCtxtPtr ctxt, const char *chunk, int size,
int terminate) {
if ((ctxt == NULL) || (ctxt->input == NULL)) {
htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
"htmlParseChunk: context error\n", NULL, NULL);
return(XML_ERR_INTERNAL_ERROR);
}
if ((size > 0) && (chunk != NULL) && (ctxt->input != NULL) &&
(ctxt->input->buf != NULL) && (ctxt->instate != XML_PARSER_EOF)) {
size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input);
size_t cur = ctxt->input->cur - ctxt->input->base;
int res;
res = xmlParserInputBufferPush(ctxt->input->buf, size, chunk);
if (res < 0) {
ctxt->errNo = XML_PARSER_EOF;
ctxt->disableSAX = 1;
return (XML_PARSER_EOF);
}
xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, cur);
#ifdef DEBUG_PUSH
xmlGenericError(xmlGenericErrorContext, "HPP: pushed %d\n", size);
#endif
#if 0
if ((terminate) || (ctxt->input->buf->buffer->use > 80))
htmlParseTryOrFinish(ctxt, terminate);
#endif
} else if (ctxt->instate != XML_PARSER_EOF) {
if ((ctxt->input != NULL) && ctxt->input->buf != NULL) {
xmlParserInputBufferPtr in = ctxt->input->buf;
if ((in->encoder != NULL) && (in->buffer != NULL) &&
(in->raw != NULL)) {
int nbchars;
nbchars = xmlCharEncInput(in);
if (nbchars < 0) {
htmlParseErr(ctxt, XML_ERR_INVALID_ENCODING,
"encoder error\n", NULL, NULL);
return(XML_ERR_INVALID_ENCODING);
}
}
}
}
htmlParseTryOrFinish(ctxt, terminate);
if (terminate) {
if ((ctxt->instate != XML_PARSER_EOF) &&
(ctxt->instate != XML_PARSER_EPILOG) &&
(ctxt->instate != XML_PARSER_MISC)) {
ctxt->errNo = XML_ERR_DOCUMENT_END;
ctxt->wellFormed = 0;
}
if (ctxt->instate != XML_PARSER_EOF) {
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
}
ctxt->instate = XML_PARSER_EOF;
}
return((xmlParserErrors) ctxt->errNo);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'Fix some buffer conversion issues
https://bugzilla.gnome.org/show_bug.cgi?id=690202
Buffer overflow errors originating from xmlBufGetInputBase in 2.9.0
The pointers from the context input were not properly reset after
that call which can do reallocations.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static __inline__ void scm_set_cred(struct scm_cookie *scm,
struct pid *pid, const struct cred *cred)
{
scm->pid = get_pid(pid);
scm->cred = cred ? get_cred(cred) : NULL;
scm->creds.pid = pid_vnr(pid);
scm->creds.uid = cred ? cred->euid : INVALID_UID;
scm->creds.gid = cred ? cred->egid : INVALID_GID;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'net: fix incorrect credentials passing
Commit 257b5358b32f ("scm: Capture the full credentials of the scm
sender") changed the credentials passing code to pass in the effective
uid/gid instead of the real uid/gid.
Obviously this doesn't matter most of the time (since normally they are
the same), but it results in differences for suid binaries when the wrong
uid/gid ends up being used.
This just undoes that (presumably unintentional) part of the commit.
Reported-by: Andy Lutomirski <[email protected]>
Cc: Eric W. Biederman <[email protected]>
Cc: Serge E. Hallyn <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
Acked-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code:
int cli_scanpe(cli_ctx *ctx)
{
uint16_t e_magic; /* DOS signature ("MZ") */
uint16_t nsections;
uint32_t e_lfanew; /* address of new exe header */
uint32_t ep, vep; /* entry point (raw, virtual) */
uint8_t polipos = 0;
time_t timestamp;
struct pe_image_file_hdr file_hdr;
union {
struct pe_image_optional_hdr64 opt64;
struct pe_image_optional_hdr32 opt32;
} pe_opt;
struct pe_image_section_hdr *section_hdr;
char sname[9], epbuff[4096], *tempfile;
uint32_t epsize;
ssize_t bytes, at;
unsigned int i, found, upx_success = 0, min = 0, max = 0, err, overlays = 0;
unsigned int ssize = 0, dsize = 0, dll = 0, pe_plus = 0, corrupted_cur;
int (*upxfn)(char *, uint32_t, char *, uint32_t *, uint32_t, uint32_t, uint32_t) = NULL;
char *src = NULL, *dest = NULL;
int ndesc, ret = CL_CLEAN, upack = 0, native=0;
size_t fsize;
uint32_t valign, falign, hdr_size, j;
struct cli_exe_section *exe_sections;
struct cli_matcher *md5_sect;
char timestr[32];
struct pe_image_data_dir *dirs;
struct cli_bc_ctx *bc_ctx;
fmap_t *map;
struct cli_pe_hook_data pedata;
#ifdef HAVE__INTERNAL__SHA_COLLECT
int sha_collect = ctx->sha_collect;
#endif
const char * virname = NULL;
uint32_t viruses_found = 0;
if(!ctx) {
cli_errmsg("cli_scanpe: ctx == NULL\n");
return CL_ENULLARG;
}
map = *ctx->fmap;
if(fmap_readn(map, &e_magic, 0, sizeof(e_magic)) != sizeof(e_magic)) {
cli_dbgmsg("Can't read DOS signature\n");
return CL_CLEAN;
}
if(EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE && EC16(e_magic) != PE_IMAGE_DOS_SIGNATURE_OLD) {
cli_dbgmsg("Invalid DOS signature\n");
return CL_CLEAN;
}
if(fmap_readn(map, &e_lfanew, 58 + sizeof(e_magic), sizeof(e_lfanew)) != sizeof(e_lfanew)) {
cli_dbgmsg("Can't read new header address\n");
/* truncated header? */
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
e_lfanew = EC32(e_lfanew);
cli_dbgmsg("e_lfanew == %d\n", e_lfanew);
if(!e_lfanew) {
cli_dbgmsg("Not a PE file\n");
return CL_CLEAN;
}
if(fmap_readn(map, &file_hdr, e_lfanew, sizeof(struct pe_image_file_hdr)) != sizeof(struct pe_image_file_hdr)) {
/* bad information in e_lfanew - probably not a PE file */
cli_dbgmsg("Can't read file header\n");
return CL_CLEAN;
}
if(EC32(file_hdr.Magic) != PE_IMAGE_NT_SIGNATURE) {
cli_dbgmsg("Invalid PE signature (probably NE file)\n");
return CL_CLEAN;
}
if(EC16(file_hdr.Characteristics) & 0x2000) {
cli_dbgmsg("File type: DLL\n");
dll = 1;
} else if(EC16(file_hdr.Characteristics) & 0x01) {
cli_dbgmsg("File type: Executable\n");
}
switch(EC16(file_hdr.Machine)) {
case 0x0:
cli_dbgmsg("Machine type: Unknown\n");
break;
case 0x14c:
cli_dbgmsg("Machine type: 80386\n");
break;
case 0x14d:
cli_dbgmsg("Machine type: 80486\n");
break;
case 0x14e:
cli_dbgmsg("Machine type: 80586\n");
break;
case 0x160:
cli_dbgmsg("Machine type: R30000 (big-endian)\n");
break;
case 0x162:
cli_dbgmsg("Machine type: R3000\n");
break;
case 0x166:
cli_dbgmsg("Machine type: R4000\n");
break;
case 0x168:
cli_dbgmsg("Machine type: R10000\n");
break;
case 0x184:
cli_dbgmsg("Machine type: DEC Alpha AXP\n");
break;
case 0x284:
cli_dbgmsg("Machine type: DEC Alpha AXP 64bit\n");
break;
case 0x1f0:
cli_dbgmsg("Machine type: PowerPC\n");
break;
case 0x200:
cli_dbgmsg("Machine type: IA64\n");
break;
case 0x268:
cli_dbgmsg("Machine type: M68k\n");
break;
case 0x266:
cli_dbgmsg("Machine type: MIPS16\n");
break;
case 0x366:
cli_dbgmsg("Machine type: MIPS+FPU\n");
break;
case 0x466:
cli_dbgmsg("Machine type: MIPS16+FPU\n");
break;
case 0x1a2:
cli_dbgmsg("Machine type: Hitachi SH3\n");
break;
case 0x1a3:
cli_dbgmsg("Machine type: Hitachi SH3-DSP\n");
break;
case 0x1a4:
cli_dbgmsg("Machine type: Hitachi SH3-E\n");
break;
case 0x1a6:
cli_dbgmsg("Machine type: Hitachi SH4\n");
break;
case 0x1a8:
cli_dbgmsg("Machine type: Hitachi SH5\n");
break;
case 0x1c0:
cli_dbgmsg("Machine type: ARM\n");
break;
case 0x1c2:
cli_dbgmsg("Machine type: THUMB\n");
break;
case 0x1d3:
cli_dbgmsg("Machine type: AM33\n");
break;
case 0x520:
cli_dbgmsg("Machine type: Infineon TriCore\n");
break;
case 0xcef:
cli_dbgmsg("Machine type: CEF\n");
break;
case 0xebc:
cli_dbgmsg("Machine type: EFI Byte Code\n");
break;
case 0x9041:
cli_dbgmsg("Machine type: M32R\n");
break;
case 0xc0ee:
cli_dbgmsg("Machine type: CEE\n");
break;
case 0x8664:
cli_dbgmsg("Machine type: AMD64\n");
break;
default:
cli_dbgmsg("Machine type: ** UNKNOWN ** (0x%x)\n", EC16(file_hdr.Machine));
}
nsections = EC16(file_hdr.NumberOfSections);
if(nsections < 1 || nsections > 96) {
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
if(!ctx->corrupted_input) {
if(nsections)
cli_warnmsg("PE file contains %d sections\n", nsections);
else
cli_warnmsg("PE file contains no sections\n");
}
return CL_CLEAN;
}
cli_dbgmsg("NumberOfSections: %d\n", nsections);
timestamp = (time_t) EC32(file_hdr.TimeDateStamp);
cli_dbgmsg("TimeDateStamp: %s", cli_ctime(×tamp, timestr, sizeof(timestr)));
cli_dbgmsg("SizeOfOptionalHeader: %x\n", EC16(file_hdr.SizeOfOptionalHeader));
if (EC16(file_hdr.SizeOfOptionalHeader) < sizeof(struct pe_image_optional_hdr32)) {
cli_dbgmsg("SizeOfOptionalHeader too small\n");
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
at = e_lfanew + sizeof(struct pe_image_file_hdr);
if(fmap_readn(map, &optional_hdr32, at, sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr32)) {
cli_dbgmsg("Can't read optional file header\n");
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
at += sizeof(struct pe_image_optional_hdr32);
/* This will be a chicken and egg problem until we drop 9x */
if(EC16(optional_hdr64.Magic)==PE32P_SIGNATURE) {
if(EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr64)) {
/* FIXME: need to play around a bit more with xp64 */
cli_dbgmsg("Incorrect SizeOfOptionalHeader for PE32+\n");
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
pe_plus = 1;
}
if(!pe_plus) { /* PE */
if (EC16(file_hdr.SizeOfOptionalHeader)!=sizeof(struct pe_image_optional_hdr32)) {
/* Seek to the end of the long header */
at += EC16(file_hdr.SizeOfOptionalHeader)-sizeof(struct pe_image_optional_hdr32);
}
if(DCONF & PE_CONF_UPACK)
upack = (EC16(file_hdr.SizeOfOptionalHeader)==0x148);
vep = EC32(optional_hdr32.AddressOfEntryPoint);
hdr_size = EC32(optional_hdr32.SizeOfHeaders);
cli_dbgmsg("File format: PE\n");
cli_dbgmsg("MajorLinkerVersion: %d\n", optional_hdr32.MajorLinkerVersion);
cli_dbgmsg("MinorLinkerVersion: %d\n", optional_hdr32.MinorLinkerVersion);
cli_dbgmsg("SizeOfCode: 0x%x\n", EC32(optional_hdr32.SizeOfCode));
cli_dbgmsg("SizeOfInitializedData: 0x%x\n", EC32(optional_hdr32.SizeOfInitializedData));
cli_dbgmsg("SizeOfUninitializedData: 0x%x\n", EC32(optional_hdr32.SizeOfUninitializedData));
cli_dbgmsg("AddressOfEntryPoint: 0x%x\n", vep);
cli_dbgmsg("BaseOfCode: 0x%x\n", EC32(optional_hdr32.BaseOfCode));
cli_dbgmsg("SectionAlignment: 0x%x\n", EC32(optional_hdr32.SectionAlignment));
cli_dbgmsg("FileAlignment: 0x%x\n", EC32(optional_hdr32.FileAlignment));
cli_dbgmsg("MajorSubsystemVersion: %d\n", EC16(optional_hdr32.MajorSubsystemVersion));
cli_dbgmsg("MinorSubsystemVersion: %d\n", EC16(optional_hdr32.MinorSubsystemVersion));
cli_dbgmsg("SizeOfImage: 0x%x\n", EC32(optional_hdr32.SizeOfImage));
cli_dbgmsg("SizeOfHeaders: 0x%x\n", hdr_size);
cli_dbgmsg("NumberOfRvaAndSizes: %d\n", EC32(optional_hdr32.NumberOfRvaAndSizes));
dirs = optional_hdr32.DataDirectory;
} else { /* PE+ */
/* read the remaining part of the header */
if(fmap_readn(map, &optional_hdr32 + 1, at, sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) != sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32)) {
cli_dbgmsg("Can't read optional file header\n");
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
at += sizeof(struct pe_image_optional_hdr64) - sizeof(struct pe_image_optional_hdr32);
vep = EC32(optional_hdr64.AddressOfEntryPoint);
hdr_size = EC32(optional_hdr64.SizeOfHeaders);
cli_dbgmsg("File format: PE32+\n");
cli_dbgmsg("MajorLinkerVersion: %d\n", optional_hdr64.MajorLinkerVersion);
cli_dbgmsg("MinorLinkerVersion: %d\n", optional_hdr64.MinorLinkerVersion);
cli_dbgmsg("SizeOfCode: 0x%x\n", EC32(optional_hdr64.SizeOfCode));
cli_dbgmsg("SizeOfInitializedData: 0x%x\n", EC32(optional_hdr64.SizeOfInitializedData));
cli_dbgmsg("SizeOfUninitializedData: 0x%x\n", EC32(optional_hdr64.SizeOfUninitializedData));
cli_dbgmsg("AddressOfEntryPoint: 0x%x\n", vep);
cli_dbgmsg("BaseOfCode: 0x%x\n", EC32(optional_hdr64.BaseOfCode));
cli_dbgmsg("SectionAlignment: 0x%x\n", EC32(optional_hdr64.SectionAlignment));
cli_dbgmsg("FileAlignment: 0x%x\n", EC32(optional_hdr64.FileAlignment));
cli_dbgmsg("MajorSubsystemVersion: %d\n", EC16(optional_hdr64.MajorSubsystemVersion));
cli_dbgmsg("MinorSubsystemVersion: %d\n", EC16(optional_hdr64.MinorSubsystemVersion));
cli_dbgmsg("SizeOfImage: 0x%x\n", EC32(optional_hdr64.SizeOfImage));
cli_dbgmsg("SizeOfHeaders: 0x%x\n", hdr_size);
cli_dbgmsg("NumberOfRvaAndSizes: %d\n", EC32(optional_hdr64.NumberOfRvaAndSizes));
dirs = optional_hdr64.DataDirectory;
}
switch(pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem)) {
case 0:
cli_dbgmsg("Subsystem: Unknown\n");
break;
case 1:
cli_dbgmsg("Subsystem: Native (svc)\n");
native = 1;
break;
case 2:
cli_dbgmsg("Subsystem: Win32 GUI\n");
break;
case 3:
cli_dbgmsg("Subsystem: Win32 console\n");
break;
case 5:
cli_dbgmsg("Subsystem: OS/2 console\n");
break;
case 7:
cli_dbgmsg("Subsystem: POSIX console\n");
break;
case 8:
cli_dbgmsg("Subsystem: Native Win9x driver\n");
break;
case 9:
cli_dbgmsg("Subsystem: WinCE GUI\n");
break;
case 10:
cli_dbgmsg("Subsystem: EFI application\n");
break;
case 11:
cli_dbgmsg("Subsystem: EFI driver\n");
break;
case 12:
cli_dbgmsg("Subsystem: EFI runtime driver\n");
break;
case 13:
cli_dbgmsg("Subsystem: EFI ROM image\n");
break;
case 14:
cli_dbgmsg("Subsystem: Xbox\n");
break;
case 16:
cli_dbgmsg("Subsystem: Boot application\n");
break;
default:
cli_dbgmsg("Subsystem: ** UNKNOWN ** (0x%x)\n", pe_plus ? EC16(optional_hdr64.Subsystem) : EC16(optional_hdr32.Subsystem));
}
cli_dbgmsg("------------------------------------\n");
if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment)) || (pe_plus?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment))%0x1000)) {
cli_dbgmsg("Bad virtual alignment\n");
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
if (DETECT_BROKEN_PE && !native && (!(pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment)) || (pe_plus?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment))%0x200)) {
cli_dbgmsg("Bad file alignment\n");
cli_append_virus(ctx, "Heuristics.Broken.Executable");
return CL_VIRUS;
}
fsize = map->len;
section_hdr = (struct pe_image_section_hdr *) cli_calloc(nsections, sizeof(struct pe_image_section_hdr));
if(!section_hdr) {
cli_dbgmsg("Can't allocate memory for section headers\n");
return CL_EMEM;
}
exe_sections = (struct cli_exe_section *) cli_calloc(nsections, sizeof(struct cli_exe_section));
if(!exe_sections) {
cli_dbgmsg("Can't allocate memory for section headers\n");
free(section_hdr);
return CL_EMEM;
}
valign = (pe_plus)?EC32(optional_hdr64.SectionAlignment):EC32(optional_hdr32.SectionAlignment);
falign = (pe_plus)?EC32(optional_hdr64.FileAlignment):EC32(optional_hdr32.FileAlignment);
if(fmap_readn(map, section_hdr, at, sizeof(struct pe_image_section_hdr)*nsections) != (int)(nsections*sizeof(struct pe_image_section_hdr))) {
cli_dbgmsg("Can't read section header\n");
cli_dbgmsg("Possibly broken PE file\n");
free(section_hdr);
free(exe_sections);
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
at += sizeof(struct pe_image_section_hdr)*nsections;
for(i = 0; falign!=0x200 && i<nsections; i++) {
/* file alignment fallback mode - blah */
if (falign && section_hdr[i].SizeOfRawData && EC32(section_hdr[i].PointerToRawData)%falign && !(EC32(section_hdr[i].PointerToRawData)%0x200)) {
cli_dbgmsg("Found misaligned section, using 0x200\n");
falign = 0x200;
}
}
hdr_size = PESALIGN(hdr_size, valign); /* Aligned headers virtual size */
for(i = 0; i < nsections; i++) {
strncpy(sname, (char *) section_hdr[i].Name, 8);
sname[8] = 0;
exe_sections[i].rva = PEALIGN(EC32(section_hdr[i].VirtualAddress), valign);
exe_sections[i].vsz = PESALIGN(EC32(section_hdr[i].VirtualSize), valign);
exe_sections[i].raw = PEALIGN(EC32(section_hdr[i].PointerToRawData), falign);
exe_sections[i].rsz = PESALIGN(EC32(section_hdr[i].SizeOfRawData), falign);
exe_sections[i].chr = EC32(section_hdr[i].Characteristics);
exe_sections[i].urva = EC32(section_hdr[i].VirtualAddress); /* Just in case */
exe_sections[i].uvsz = EC32(section_hdr[i].VirtualSize);
exe_sections[i].uraw = EC32(section_hdr[i].PointerToRawData);
exe_sections[i].ursz = EC32(section_hdr[i].SizeOfRawData);
if (!exe_sections[i].vsz && exe_sections[i].rsz)
exe_sections[i].vsz=PESALIGN(exe_sections[i].ursz, valign);
if (exe_sections[i].rsz && fsize>exe_sections[i].raw && !CLI_ISCONTAINED(0, (uint32_t) fsize, exe_sections[i].raw, exe_sections[i].rsz))
exe_sections[i].rsz = fsize - exe_sections[i].raw;
cli_dbgmsg("Section %d\n", i);
cli_dbgmsg("Section name: %s\n", sname);
cli_dbgmsg("Section data (from headers - in memory)\n");
cli_dbgmsg("VirtualSize: 0x%x 0x%x\n", exe_sections[i].uvsz, exe_sections[i].vsz);
cli_dbgmsg("VirtualAddress: 0x%x 0x%x\n", exe_sections[i].urva, exe_sections[i].rva);
cli_dbgmsg("SizeOfRawData: 0x%x 0x%x\n", exe_sections[i].ursz, exe_sections[i].rsz);
cli_dbgmsg("PointerToRawData: 0x%x 0x%x\n", exe_sections[i].uraw, exe_sections[i].raw);
if(exe_sections[i].chr & 0x20) {
cli_dbgmsg("Section contains executable code\n");
if(exe_sections[i].vsz < exe_sections[i].rsz) {
cli_dbgmsg("Section contains free space\n");
/*
cli_dbgmsg("Dumping %d bytes\n", section_hdr.SizeOfRawData - section_hdr.VirtualSize);
ddump(desc, section_hdr.PointerToRawData + section_hdr.VirtualSize, section_hdr.SizeOfRawData - section_hdr.VirtualSize, cli_gentemp(NULL));
*/
}
}
if(exe_sections[i].chr & 0x20000000)
cli_dbgmsg("Section's memory is executable\n");
if(exe_sections[i].chr & 0x80000000)
cli_dbgmsg("Section's memory is writeable\n");
if (DETECT_BROKEN_PE && (!valign || (exe_sections[i].urva % valign))) { /* Bad virtual alignment */
cli_dbgmsg("VirtualAddress is misaligned\n");
cli_dbgmsg("------------------------------------\n");
cli_append_virus(ctx, "Heuristics.Broken.Executable");
free(section_hdr);
free(exe_sections);
return CL_VIRUS;
}
if (exe_sections[i].rsz) { /* Don't bother with virtual only sections */
if (exe_sections[i].raw >= fsize) { /* really broken */
cli_dbgmsg("Broken PE file - Section %d starts beyond the end of file (Offset@ %lu, Total filesize %lu)\n", i, (unsigned long)exe_sections[i].raw, (unsigned long)fsize);
cli_dbgmsg("------------------------------------\n");
free(section_hdr);
free(exe_sections);
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx, "Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN; /* no ninjas to see here! move along! */
}
if(SCAN_ALGO && (DCONF & PE_CONF_POLIPOS) && !*sname && exe_sections[i].vsz > 40000 && exe_sections[i].vsz < 70000 && exe_sections[i].chr == 0xe0000060) polipos = i;
/* check MD5 section sigs */
md5_sect = ctx->engine->hm_mdb;
if((DCONF & PE_CONF_MD5SECT) && md5_sect) {
unsigned char md5_dig[16];
if(cli_hm_have_size(md5_sect, CLI_HASH_MD5, exe_sections[i].rsz) &&
cli_md5sect(map, &exe_sections[i], md5_dig) &&
cli_hm_scan(md5_dig, exe_sections[i].rsz, &virname, md5_sect, CLI_HASH_MD5) == CL_VIRUS) {
cli_append_virus(ctx, virname);
if(cli_hm_scan(md5_dig, fsize, NULL, ctx->engine->hm_fp, CLI_HASH_MD5) != CL_VIRUS) {
if (!SCAN_ALL) {
cli_dbgmsg("------------------------------------\n");
free(section_hdr);
free(exe_sections);
return CL_VIRUS;
}
}
viruses_found++;
}
}
}
cli_dbgmsg("------------------------------------\n");
if (exe_sections[i].urva>>31 || exe_sections[i].uvsz>>31 || (exe_sections[i].rsz && exe_sections[i].uraw>>31) || exe_sections[i].ursz>>31) {
cli_dbgmsg("Found PE values with sign bit set\n");
free(section_hdr);
free(exe_sections);
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx, "Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
if(!i) {
if (DETECT_BROKEN_PE && exe_sections[i].urva!=hdr_size) { /* Bad first section RVA */
cli_dbgmsg("First section is in the wrong place\n");
cli_append_virus(ctx, "Heuristics.Broken.Executable");
free(section_hdr);
free(exe_sections);
return CL_VIRUS;
}
min = exe_sections[i].rva;
max = exe_sections[i].rva + exe_sections[i].rsz;
} else {
if (DETECT_BROKEN_PE && exe_sections[i].urva - exe_sections[i-1].urva != exe_sections[i-1].vsz) { /* No holes, no overlapping, no virtual disorder */
cli_dbgmsg("Virtually misplaced section (wrong order, overlapping, non contiguous)\n");
cli_append_virus(ctx, "Heuristics.Broken.Executable");
free(section_hdr);
free(exe_sections);
return CL_VIRUS;
}
if(exe_sections[i].rva < min)
min = exe_sections[i].rva;
if(exe_sections[i].rva + exe_sections[i].rsz > max) {
max = exe_sections[i].rva + exe_sections[i].rsz;
overlays = exe_sections[i].raw + exe_sections[i].rsz;
}
}
}
free(section_hdr);
if(!(ep = cli_rawaddr(vep, exe_sections, nsections, &err, fsize, hdr_size)) && err) {
cli_dbgmsg("EntryPoint out of file\n");
free(exe_sections);
if(DETECT_BROKEN_PE) {
cli_append_virus(ctx,"Heuristics.Broken.Executable");
return CL_VIRUS;
}
return CL_CLEAN;
}
cli_dbgmsg("EntryPoint offset: 0x%x (%d)\n", ep, ep);
if(pe_plus) { /* Do not continue for PE32+ files */
free(exe_sections);
return CL_CLEAN;
}
epsize = fmap_readn(map, epbuff, ep, 4096);
/* Disasm scan disabled since it's now handled by the bytecode */
/* CLI_UNPTEMP("DISASM",(exe_sections,0)); */
/* if(disasmbuf((unsigned char*)epbuff, epsize, ndesc)) */
/* ret = cli_scandesc(ndesc, ctx, CL_TYPE_PE_DISASM, 1, NULL, AC_SCAN_VIR); */
/* close(ndesc); */
/* CLI_TMPUNLK(); */
/* free(tempfile); */
/* if(ret == CL_VIRUS) { */
/* free(exe_sections); */
/* return ret; */
/* } */
if(overlays) {
int overlays_sz = fsize - overlays;
if(overlays_sz > 0) {
ret = cli_scanishield(ctx, overlays, overlays_sz);
if(ret != CL_CLEAN) {
free(exe_sections);
return ret;
}
}
}
pedata.nsections = nsections;
pedata.ep = ep;
pedata.offset = 0;
memcpy(&pedata.file_hdr, &file_hdr, sizeof(file_hdr));
memcpy(&pedata.opt32, &pe_opt.opt32, sizeof(pe_opt.opt32));
memcpy(&pedata.opt64, &pe_opt.opt64, sizeof(pe_opt.opt64));
memcpy(&pedata.dirs, dirs, sizeof(pedata.dirs));
pedata.e_lfanew = e_lfanew;
pedata.overlays = overlays;
pedata.overlays_sz = fsize - overlays;
pedata.hdr_size = hdr_size;
/* Bytecode BC_PE_ALL hook */
bc_ctx = cli_bytecode_context_alloc();
if (!bc_ctx) {
cli_errmsg("cli_scanpe: can't allocate memory for bc_ctx\n");
return CL_EMEM;
}
cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections);
cli_bytecode_context_setctx(bc_ctx, ctx);
ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_ALL, map);
if (ret == CL_VIRUS || ret == CL_BREAK) {
free(exe_sections);
cli_bytecode_context_destroy(bc_ctx);
return ret == CL_VIRUS ? CL_VIRUS : CL_CLEAN;
}
cli_bytecode_context_destroy(bc_ctx);
/* Attempt to detect some popular polymorphic viruses */
/* W32.Parite.B */
if(SCAN_ALGO && (DCONF & PE_CONF_PARITE) && !dll && epsize == 4096 && ep == exe_sections[nsections - 1].raw) {
const char *pt = cli_memstr(epbuff, 4040, "\x47\x65\x74\x50\x72\x6f\x63\x41\x64\x64\x72\x65\x73\x73\x00", 15);
if(pt) {
pt += 15;
if((((uint32_t)cli_readint32(pt) ^ (uint32_t)cli_readint32(pt + 4)) == 0x505a4f) && (((uint32_t)cli_readint32(pt + 8) ^ (uint32_t)cli_readint32(pt + 12)) == 0xffffb) && (((uint32_t)cli_readint32(pt + 16) ^ (uint32_t)cli_readint32(pt + 20)) == 0xb8)) {
cli_append_virus(ctx,"Heuristics.W32.Parite.B");
if (!SCAN_ALL) {
free(exe_sections);
return CL_VIRUS;
}
viruses_found++;
}
}
}
/* Kriz */
if(SCAN_ALGO && (DCONF & PE_CONF_KRIZ) && epsize >= 200 && CLI_ISCONTAINED(exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz, ep, 0x0fd2) && epbuff[1]=='\x9c' && epbuff[2]=='\x60') {
enum {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSXORPRFX,KZSXOR,KZSDDELTA,KZSLOOP,KZSTOP};
uint8_t kzs[] = {KZSTRASH,KZSCDELTA,KZSPDELTA,KZSGETSIZE,KZSTRASH,KZSXORPRFX,KZSXOR,KZSTRASH,KZSDDELTA,KZSTRASH,KZSLOOP,KZSTOP};
uint8_t *kzstate = kzs;
uint8_t *kzcode = (uint8_t *)epbuff + 3;
uint8_t kzdptr=0xff, kzdsize=0xff;
int kzlen = 197, kzinitlen=0xffff, kzxorlen=-1;
cli_dbgmsg("in kriz\n");
while(*kzstate!=KZSTOP) {
uint8_t op;
if(kzlen<=6) break;
op = *kzcode++;
kzlen--;
switch (*kzstate) {
case KZSTRASH: case KZSGETSIZE: {
int opsz=0;
switch(op) {
case 0x81:
kzcode+=5;
kzlen-=5;
break;
case 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbd: case 0xbe: case 0xbf:
if(*kzstate==KZSGETSIZE && cli_readint32(kzcode)==0x0fd2) {
kzinitlen = kzlen-5;
kzdsize=op-0xb8;
kzstate++;
op=4; /* fake the register to avoid breaking out */
cli_dbgmsg("kriz: using #%d as size counter\n", kzdsize);
}
opsz=4;
case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4d: case 0x4e: case 0x4f:
op&=7;
if(op!=kzdptr && op!=kzdsize) {
kzcode+=opsz;
kzlen-=opsz;
break;
}
default:
kzcode--;
kzlen++;
kzstate++;
}
break;
}
case KZSCDELTA:
if(op==0xe8 && (uint32_t)cli_readint32(kzcode) < 0xff) {
kzlen-=*kzcode+4;
kzcode+=*kzcode+4;
kzstate++;
} else *kzstate=KZSTOP;
break;
case KZSPDELTA:
if((op&0xf8)==0x58 && (kzdptr=op-0x58)!=4) {
kzstate++;
cli_dbgmsg("kriz: using #%d as pointer\n", kzdptr);
} else *kzstate=KZSTOP;
break;
case KZSXORPRFX:
kzstate++;
if(op==0x3e) break;
case KZSXOR:
if (op==0x80 && *kzcode==kzdptr+0xb0) {
kzxorlen=kzlen;
kzcode+=+6;
kzlen-=+6;
kzstate++;
} else *kzstate=KZSTOP;
break;
case KZSDDELTA:
if (op==kzdptr+0x48) kzstate++;
else *kzstate=KZSTOP;
break;
case KZSLOOP:
if (op==kzdsize+0x48 && *kzcode==0x75 && kzlen-(int8_t)kzcode[1]-3<=kzinitlen && kzlen-(int8_t)kzcode[1]>=kzxorlen) {
cli_append_virus(ctx,"Heuristics.W32.Kriz");
free(exe_sections);
if (!SCAN_ALL)
return CL_VIRUS;
viruses_found++;
}
cli_dbgmsg("kriz: loop out of bounds, corrupted sample?\n");
kzstate++;
}
}
}
/* W32.Magistr.A/B */
if(SCAN_ALGO && (DCONF & PE_CONF_MAGISTR) && !dll && (nsections>1) && (exe_sections[nsections - 1].chr & 0x80000000)) {
uint32_t rsize, vsize, dam = 0;
vsize = exe_sections[nsections - 1].uvsz;
rsize = exe_sections[nsections - 1].rsz;
if(rsize < exe_sections[nsections - 1].ursz) {
rsize = exe_sections[nsections - 1].ursz;
dam = 1;
}
if(vsize >= 0x612c && rsize >= 0x612c && ((vsize & 0xff) == 0xec)) {
int bw = rsize < 0x7000 ? rsize : 0x7000;
char *tbuff;
if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) {
if(cli_memstr(tbuff, 4091, "\xe8\x2c\x61\x00\x00", 5)) {
cli_append_virus(ctx, dam ? "Heuristics.W32.Magistr.A.dam" : "Heuristics.W32.Magistr.A");
free(exe_sections);
if (!SCAN_ALL)
return CL_VIRUS;
viruses_found++;
}
}
} else if(rsize >= 0x7000 && vsize >= 0x7000 && ((vsize & 0xff) == 0xed)) {
int bw = rsize < 0x8000 ? rsize : 0x8000;
char *tbuff;
if((tbuff = fmap_need_off_once(map, exe_sections[nsections - 1].raw + rsize - bw, 4096))) {
if(cli_memstr(tbuff, 4091, "\xe8\x04\x72\x00\x00", 5)) {
cli_append_virus(ctx,dam ? "Heuristics.W32.Magistr.B.dam" : "Heuristics.W32.Magistr.B");
free(exe_sections);
if (!SCAN_ALL)
return CL_VIRUS;
viruses_found++;
}
}
}
}
/* W32.Polipos.A */
while(polipos && !dll && nsections > 2 && nsections < 13 && e_lfanew <= 0x800 && (EC16(optional_hdr32.Subsystem) == 2 || EC16(optional_hdr32.Subsystem) == 3) && EC16(file_hdr.Machine) == 0x14c && optional_hdr32.SizeOfStackReserve >= 0x80000) {
uint32_t jump, jold, *jumps = NULL;
uint8_t *code;
unsigned int xsjs = 0;
if(exe_sections[0].rsz > CLI_MAX_ALLOCATION) break;
if(!exe_sections[0].rsz) break;
if(!(code=fmap_need_off_once(map, exe_sections[0].raw, exe_sections[0].rsz))) break;
for(i=0; i<exe_sections[0].rsz - 5; i++) {
if((uint8_t)(code[i]-0xe8) > 1) continue;
jump = cli_rawaddr(exe_sections[0].rva+i+5+cli_readint32(&code[i+1]), exe_sections, nsections, &err, fsize, hdr_size);
if(err || !CLI_ISCONTAINED(exe_sections[polipos].raw, exe_sections[polipos].rsz, jump, 9)) continue;
if(xsjs % 128 == 0) {
if(xsjs == 1280) break;
if(!(jumps=(uint32_t *)cli_realloc2(jumps, (xsjs+128)*sizeof(uint32_t)))) {
free(exe_sections);
return CL_EMEM;
}
}
j=0;
for(; j<xsjs; j++) {
if(jumps[j]<jump) continue;
if(jumps[j]==jump) {
xsjs--;
break;
}
jold=jumps[j];
jumps[j]=jump;
jump=jold;
}
jumps[j]=jump;
xsjs++;
}
if(!xsjs) break;
cli_dbgmsg("Polipos: Checking %d xsect jump(s)\n", xsjs);
for(i=0;i<xsjs;i++) {
if(!(code = fmap_need_off_once(map, jumps[i], 9))) continue;
if((jump=cli_readint32(code))==0x60ec8b55 || (code[4]==0x0ec && ((jump==0x83ec8b55 && code[6]==0x60) || (jump==0x81ec8b55 && !code[7] && !code[8])))) {
cli_append_virus(ctx,"Heuristics.W32.Polipos.A");
free(jumps);
free(exe_sections);
if (!SCAN_ALL)
return CL_VIRUS;
viruses_found++;
}
}
free(jumps);
break;
}
/* Trojan.Swizzor.Gen */
if (SCAN_ALGO && (DCONF & PE_CONF_SWIZZOR) && nsections > 1 && fsize > 64*1024 && fsize < 4*1024*1024) {
if(dirs[2].Size) {
struct swizz_stats *stats = cli_calloc(1, sizeof(*stats));
unsigned int m = 1000;
ret = CL_CLEAN;
if (!stats)
ret = CL_EMEM;
else {
cli_parseres_special(EC32(dirs[2].VirtualAddress), EC32(dirs[2].VirtualAddress), map, exe_sections, nsections, fsize, hdr_size, 0, 0, &m, stats);
if ((ret = cli_detect_swizz(stats)) == CL_VIRUS) {
cli_append_virus(ctx,"Heuristics.Trojan.Swizzor.Gen");
}
free(stats);
}
if (ret != CL_CLEAN) {
if (!(ret == CL_VIRUS && SCAN_ALL)) {
free(exe_sections);
return ret;
}
viruses_found++;
}
}
}
/* !!!!!!!!!!!!!! PACKERS START HERE !!!!!!!!!!!!!! */
corrupted_cur = ctx->corrupted_input;
ctx->corrupted_input = 2; /* caller will reset on return */
/* UPX, FSG, MEW support */
/* try to find the first section with physical size == 0 */
found = 0;
if(DCONF & (PE_CONF_UPX | PE_CONF_FSG | PE_CONF_MEW)) {
for(i = 0; i < (unsigned int) nsections - 1; i++) {
if(!exe_sections[i].rsz && exe_sections[i].vsz && exe_sections[i + 1].rsz && exe_sections[i + 1].vsz) {
found = 1;
cli_dbgmsg("UPX/FSG/MEW: empty section found - assuming compression\n");
break;
}
}
}
/* MEW support */
if (found && (DCONF & PE_CONF_MEW) && epsize>=16 && epbuff[0]=='\xe9') {
uint32_t fileoffset;
char *tbuff;
fileoffset = (vep + cli_readint32(epbuff + 1) + 5);
while (fileoffset == 0x154 || fileoffset == 0x158) {
uint32_t offdiff, uselzma;
cli_dbgmsg ("MEW: found MEW characteristics %08X + %08X + 5 = %08X\n",
cli_readint32(epbuff + 1), vep, cli_readint32(epbuff + 1) + vep + 5);
if(!(tbuff = fmap_need_off_once(map, fileoffset, 0xb0)))
break;
if (fileoffset == 0x154) cli_dbgmsg("MEW: Win9x compatibility was set!\n");
else cli_dbgmsg("MEW: Win9x compatibility was NOT set!\n");
if((offdiff = cli_readint32(tbuff+1) - EC32(optional_hdr32.ImageBase)) <= exe_sections[i + 1].rva || offdiff >= exe_sections[i + 1].rva + exe_sections[i + 1].raw - 4) {
cli_dbgmsg("MEW: ESI is not in proper section\n");
break;
}
offdiff -= exe_sections[i + 1].rva;
if(!exe_sections[i + 1].rsz) {
cli_dbgmsg("MEW: mew section is empty\n");
break;
}
ssize = exe_sections[i + 1].vsz;
dsize = exe_sections[i].vsz;
cli_dbgmsg("MEW: ssize %08x dsize %08x offdiff: %08x\n", ssize, dsize, offdiff);
CLI_UNPSIZELIMITS("MEW", MAX(ssize, dsize));
CLI_UNPSIZELIMITS("MEW", MAX(ssize + dsize, exe_sections[i + 1].rsz));
if (exe_sections[i + 1].rsz < offdiff + 12 || exe_sections[i + 1].rsz > ssize) {
cli_dbgmsg("MEW: Size mismatch: %08x\n", exe_sections[i + 1].rsz);
break;
}
/* allocate needed buffer */
if (!(src = cli_calloc (ssize + dsize, sizeof(char)))) {
free(exe_sections);
return CL_EMEM;
}
if((bytes = fmap_readn(map, src + dsize, exe_sections[i + 1].raw, exe_sections[i + 1].rsz)) != exe_sections[i + 1].rsz) {
cli_dbgmsg("MEW: Can't read %d bytes [read: %lu]\n", exe_sections[i + 1].rsz, (unsigned long)bytes);
free(exe_sections);
free(src);
return CL_EREAD;
}
cli_dbgmsg("MEW: %u (%08x) bytes read\n", (unsigned int)bytes, (unsigned int)bytes);
/* count offset to lzma proc, if lzma used, 0xe8 -> call */
if (tbuff[0x7b] == '\xe8') {
if (!CLI_ISCONTAINED(exe_sections[1].rva, exe_sections[1].vsz, cli_readint32(tbuff + 0x7c) + fileoffset + 0x80, 4)) {
cli_dbgmsg("MEW: lzma proc out of bounds!\n");
free(src);
break; /* to next unpacker in chain */
}
uselzma = cli_readint32(tbuff + 0x7c) - (exe_sections[0].rva - fileoffset - 0x80);
} else {
uselzma = 0;
}
CLI_UNPTEMP("MEW",(src,exe_sections,0));
CLI_UNPRESULTS("MEW",(unmew11(src, offdiff, ssize, dsize, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, uselzma, ndesc)),1,(src,0));
break;
}
}
if(epsize<168) {
free(exe_sections);
return CL_CLEAN;
}
if (found || upack) {
/* Check EP for UPX vs. FSG vs. Upack */
/* Upack 0.39 produces 2 types of executables
* 3 sections: | 2 sections (one empty, I don't chech found if !upack, since it's in OR above):
* mov esi, value | pusha
* lodsd | call $+0x9
* push eax |
*
* Upack 1.1/1.2 Beta produces [based on 2 samples (sUx) provided by aCaB]:
* 2 sections
* mov esi, value
* loads
* mov edi, eax
*
* Upack unknown [sample 0297729]
* 3 sections
* mov esi, value
* push [esi]
* jmp
*
*/
/* upack 0.39-3s + sample 0151477*/
while(((upack && nsections == 3) && /* 3 sections */
((
epbuff[0] == '\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && /* mov esi */
epbuff[5] == '\xad' && epbuff[6] == '\x50' /* lodsd; push eax */
)
||
/* based on 0297729 sample from aCaB */
(epbuff[0] == '\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > min && /* mov esi */
epbuff[5] == '\xff' && epbuff[6] == '\x36' /* push [esi] */
)
))
||
((!upack && nsections == 2) && /* 2 sections */
(( /* upack 0.39-2s */
epbuff[0] == '\x60' && epbuff[1] == '\xe8' && cli_readint32(epbuff+2) == 0x9 /* pusha; call+9 */
)
||
( /* upack 1.1/1.2, based on 2 samples */
epbuff[0] == '\xbe' && cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase) < min && /* mov esi */
cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) > 0 &&
epbuff[5] == '\xad' && epbuff[6] == '\x8b' && epbuff[7] == '\xf8' /* loads; mov edi, eax */
)
))
) {
uint32_t vma, off;
int a,b,c;
cli_dbgmsg("Upack characteristics found.\n");
a = exe_sections[0].vsz;
b = exe_sections[1].vsz;
if (upack) {
cli_dbgmsg("Upack: var set\n");
c = exe_sections[2].vsz;
ssize = exe_sections[0].ursz + exe_sections[0].uraw;
off = exe_sections[0].rva;
vma = EC32(optional_hdr32.ImageBase) + exe_sections[0].rva;
} else {
cli_dbgmsg("Upack: var NOT set\n");
c = exe_sections[1].rva;
ssize = exe_sections[1].uraw;
off = 0;
vma = exe_sections[1].rva - exe_sections[1].uraw;
}
dsize = a+b+c;
CLI_UNPSIZELIMITS("Upack", MAX(MAX(dsize, ssize), exe_sections[1].ursz));
if (!CLI_ISCONTAINED(0, dsize, exe_sections[1].rva - off, exe_sections[1].ursz) || (upack && !CLI_ISCONTAINED(0, dsize, exe_sections[2].rva - exe_sections[0].rva, ssize)) || ssize > dsize) {
cli_dbgmsg("Upack: probably malformed pe-header, skipping to next unpacker\n");
break;
}
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
free(exe_sections);
return CL_EMEM;
}
if(fmap_readn(map, dest, 0, ssize) != ssize) {
cli_dbgmsg("Upack: Can't read raw data of section 0\n");
free(dest);
break;
}
if(upack) memmove(dest + exe_sections[2].rva - exe_sections[0].rva, dest, ssize);
if(fmap_readn(map, dest + exe_sections[1].rva - off, exe_sections[1].uraw, exe_sections[1].ursz) != exe_sections[1].ursz) {
cli_dbgmsg("Upack: Can't read raw data of section 1\n");
free(dest);
break;
}
CLI_UNPTEMP("Upack",(dest,exe_sections,0));
CLI_UNPRESULTS("Upack",(unupack(upack, dest, dsize, epbuff, vma, ep, EC32(optional_hdr32.ImageBase), exe_sections[0].rva, ndesc)),1,(dest,0));
break;
}
}
while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\x87' && epbuff[1] == '\x25') {
/* FSG v2.0 support - thanks to aCaB ! */
uint32_t newesi, newedi, newebx, newedx;
ssize = exe_sections[i + 1].rsz;
dsize = exe_sections[i].vsz;
CLI_UNPSIZELIMITS("FSG", MAX(dsize, ssize));
if(ssize <= 0x19 || dsize <= ssize) {
cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize);
free(exe_sections);
return CL_CLEAN;
}
newedx = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase);
if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) {
cli_dbgmsg("FSG: xchg out of bounds (%x), giving up\n", newedx);
break;
}
if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {
cli_dbgmsg("Can't read raw data of section %d\n", i + 1);
free(exe_sections);
return CL_ESEEK;
}
dest = src + newedx - exe_sections[i + 1].rva;
if(newedx < exe_sections[i + 1].rva || !CLI_ISCONTAINED(src, ssize, dest, 4)) {
cli_dbgmsg("FSG: New ESP out of bounds\n");
break;
}
newedx = cli_readint32(dest) - EC32(optional_hdr32.ImageBase);
if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newedx, 4)) {
cli_dbgmsg("FSG: New ESP (%x) is wrong\n", newedx);
break;
}
dest = src + newedx - exe_sections[i + 1].rva;
if(!CLI_ISCONTAINED(src, ssize, dest, 32)) {
cli_dbgmsg("FSG: New stack out of bounds\n");
break;
}
newedi = cli_readint32(dest) - EC32(optional_hdr32.ImageBase);
newesi = cli_readint32(dest + 4) - EC32(optional_hdr32.ImageBase);
newebx = cli_readint32(dest + 16) - EC32(optional_hdr32.ImageBase);
newedx = cli_readint32(dest + 20);
if(newedi != exe_sections[i].rva) {
cli_dbgmsg("FSG: Bad destination buffer (edi is %x should be %x)\n", newedi, exe_sections[i].rva);
break;
}
if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) {
cli_dbgmsg("FSG: Source buffer out of section bounds\n");
break;
}
if(!CLI_ISCONTAINED(exe_sections[i + 1].rva, exe_sections[i + 1].rsz, newebx, 16)) {
cli_dbgmsg("FSG: Array of functions out of bounds\n");
break;
}
newedx=cli_readint32(newebx + 12 - exe_sections[i + 1].rva + src) - EC32(optional_hdr32.ImageBase);
cli_dbgmsg("FSG: found old EP @%x\n",newedx);
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
free(exe_sections);
free(src);
return CL_EMEM;
}
CLI_UNPTEMP("FSG",(dest,exe_sections,0));
CLI_UNPRESULTSFSG2("FSG",(unfsg_200(newesi - exe_sections[i + 1].rva + src, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, newedi, EC32(optional_hdr32.ImageBase), newedx, ndesc)),1,(dest,0));
break;
}
while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\xbe' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min) {
/* FSG support - v. 1.33 (thx trog for the many samples) */
int sectcnt = 0;
char *support;
uint32_t newesi, newedi, oldep, gp, t;
struct cli_exe_section *sections;
ssize = exe_sections[i + 1].rsz;
dsize = exe_sections[i].vsz;
CLI_UNPSIZELIMITS("FSG", MAX(dsize, ssize));
if(ssize <= 0x19 || dsize <= ssize) {
cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize);
free(exe_sections);
return CL_CLEAN;
}
if(!(t = cli_rawaddr(cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size)) && err ) {
cli_dbgmsg("FSG: Support data out of padding area\n");
break;
}
gp = exe_sections[i + 1].raw - t;
CLI_UNPSIZELIMITS("FSG", gp);
if(!(support = fmap_need_off_once(map, t, gp))) {
cli_dbgmsg("Can't read %d bytes from padding area\n", gp);
free(exe_sections);
return CL_EREAD;
}
/* newebx = cli_readint32(support) - EC32(optional_hdr32.ImageBase); Unused */
newedi = cli_readint32(support + 4) - EC32(optional_hdr32.ImageBase); /* 1st dest */
newesi = cli_readint32(support + 8) - EC32(optional_hdr32.ImageBase); /* Source */
if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].rsz) {
cli_dbgmsg("FSG: Source buffer out of section bounds\n");
break;
}
if(newedi != exe_sections[i].rva) {
cli_dbgmsg("FSG: Bad destination (is %x should be %x)\n", newedi, exe_sections[i].rva);
break;
}
/* Counting original sections */
for(t = 12; t < gp - 4; t += 4) {
uint32_t rva = cli_readint32(support+t);
if(!rva)
break;
rva -= EC32(optional_hdr32.ImageBase)+1;
sectcnt++;
if(rva % 0x1000) cli_dbgmsg("FSG: Original section %d is misaligned\n", sectcnt);
if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) {
cli_dbgmsg("FSG: Original section %d is out of bounds\n", sectcnt);
break;
}
}
if(t >= gp - 4 || cli_readint32(support + t)) {
break;
}
if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) {
free(exe_sections);
return CL_EMEM;
}
sections[0].rva = newedi;
for(t = 1; t <= (uint32_t)sectcnt; t++)
sections[t].rva = cli_readint32(support + 8 + t * 4) - 1 - EC32(optional_hdr32.ImageBase);
if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {
cli_dbgmsg("Can't read raw data of section %d\n", i);
free(exe_sections);
free(sections);
return CL_EREAD;
}
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
free(exe_sections);
free(sections);
return CL_EMEM;
}
oldep = vep + 161 + 6 + cli_readint32(epbuff+163);
cli_dbgmsg("FSG: found old EP @%x\n", oldep);
CLI_UNPTEMP("FSG",(dest,sections,exe_sections,0));
CLI_UNPRESULTSFSG1("FSG",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0));
break; /* were done with 1.33 */
}
while(found && (DCONF & PE_CONF_FSG) && epbuff[0] == '\xbb' && cli_readint32(epbuff + 1) - EC32(optional_hdr32.ImageBase) < min && epbuff[5] == '\xbf' && epbuff[10] == '\xbe' && vep >= exe_sections[i + 1].rva && vep - exe_sections[i + 1].rva > exe_sections[i + 1].rva - 0xe0 ) {
/* FSG support - v. 1.31 */
int sectcnt = 0;
uint32_t gp, t = cli_rawaddr(cli_readint32(epbuff+1) - EC32(optional_hdr32.ImageBase), NULL, 0 , &err, fsize, hdr_size);
char *support;
uint32_t newesi = cli_readint32(epbuff+11) - EC32(optional_hdr32.ImageBase);
uint32_t newedi = cli_readint32(epbuff+6) - EC32(optional_hdr32.ImageBase);
uint32_t oldep = vep - exe_sections[i + 1].rva;
struct cli_exe_section *sections;
ssize = exe_sections[i + 1].rsz;
dsize = exe_sections[i].vsz;
if(err) {
cli_dbgmsg("FSG: Support data out of padding area\n");
break;
}
if(newesi < exe_sections[i + 1].rva || newesi - exe_sections[i + 1].rva >= exe_sections[i + 1].raw) {
cli_dbgmsg("FSG: Source buffer out of section bounds\n");
break;
}
if(newedi != exe_sections[i].rva) {
cli_dbgmsg("FSG: Bad destination (is %x should be %x)\n", newedi, exe_sections[i].rva);
break;
}
CLI_UNPSIZELIMITS("FSG", MAX(dsize, ssize));
if(ssize <= 0x19 || dsize <= ssize) {
cli_dbgmsg("FSG: Size mismatch (ssize: %d, dsize: %d)\n", ssize, dsize);
free(exe_sections);
return CL_CLEAN;
}
gp = exe_sections[i + 1].raw - t;
CLI_UNPSIZELIMITS("FSG", gp)
if(!(support = fmap_need_off_once(map, t, gp))) {
cli_dbgmsg("Can't read %d bytes from padding area\n", gp);
free(exe_sections);
return CL_EREAD;
}
/* Counting original sections */
for(t = 0; t < gp - 2; t += 2) {
uint32_t rva = support[t]|(support[t+1]<<8);
if (rva == 2 || rva == 1)
break;
rva = ((rva-2)<<12) - EC32(optional_hdr32.ImageBase);
sectcnt++;
if(rva < exe_sections[i].rva || rva - exe_sections[i].rva >= exe_sections[i].vsz) {
cli_dbgmsg("FSG: Original section %d is out of bounds\n", sectcnt);
break;
}
}
if(t >= gp-10 || cli_readint32(support + t + 6) != 2) {
break;
}
if((sections = (struct cli_exe_section *) cli_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) {
free(exe_sections);
return CL_EMEM;
}
sections[0].rva = newedi;
for(t = 0; t <= (uint32_t)sectcnt - 1; t++) {
sections[t+1].rva = (((support[t*2]|(support[t*2+1]<<8))-2)<<12)-EC32(optional_hdr32.ImageBase);
}
if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {
cli_dbgmsg("FSG: Can't read raw data of section %d\n", i);
free(exe_sections);
free(sections);
return CL_EREAD;
}
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
free(exe_sections);
free(sections);
return CL_EMEM;
}
gp = 0xda + 6*(epbuff[16]=='\xe8');
oldep = vep + gp + 6 + cli_readint32(src+gp+2+oldep);
cli_dbgmsg("FSG: found old EP @%x\n", oldep);
CLI_UNPTEMP("FSG",(dest,sections,exe_sections,0));
CLI_UNPRESULTSFSG1("FSG",(unfsg_133(src + newesi - exe_sections[i + 1].rva, dest, ssize + exe_sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(optional_hdr32.ImageBase), oldep, ndesc)),1,(dest,sections,0));
break; /* were done with 1.31 */
}
if(found && (DCONF & PE_CONF_UPX)) {
/* UPX support */
/* we assume (i + 1) is UPX1 */
ssize = exe_sections[i + 1].rsz;
dsize = exe_sections[i].vsz + exe_sections[i + 1].vsz;
CLI_UNPSIZELIMITS("UPX", MAX(dsize, ssize));
if(ssize <= 0x19 || dsize <= ssize || dsize > CLI_MAX_ALLOCATION ) {
cli_dbgmsg("UPX: Size mismatch or dsize too big (ssize: %d, dsize: %d)\n", ssize, dsize);
free(exe_sections);
return CL_CLEAN;
}
if(!exe_sections[i + 1].rsz || !(src = fmap_need_off_once(map, exe_sections[i + 1].raw, ssize))) {
cli_dbgmsg("UPX: Can't read raw data of section %d\n", i+1);
free(exe_sections);
return CL_EREAD;
}
if((dest = (char *) cli_calloc(dsize + 8192, sizeof(char))) == NULL) {
free(exe_sections);
return CL_EMEM;
}
/* try to detect UPX code */
if(cli_memstr(UPX_NRV2B, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2B, 24, epbuff + 0x69 + 8, 13)) {
cli_dbgmsg("UPX: Looks like a NRV2B decompression routine\n");
upxfn = upx_inflate2b;
} else if(cli_memstr(UPX_NRV2D, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2D, 24, epbuff + 0x69 + 8, 13)) {
cli_dbgmsg("UPX: Looks like a NRV2D decompression routine\n");
upxfn = upx_inflate2d;
} else if(cli_memstr(UPX_NRV2E, 24, epbuff + 0x69, 13) || cli_memstr(UPX_NRV2E, 24, epbuff + 0x69 + 8, 13)) {
cli_dbgmsg("UPX: Looks like a NRV2E decompression routine\n");
upxfn = upx_inflate2e;
}
if(upxfn) {
int skew = cli_readint32(epbuff + 2) - EC32(optional_hdr32.ImageBase) - exe_sections[i + 1].rva;
if(epbuff[1] != '\xbe' || skew <= 0 || skew > 0xfff) { /* FIXME: legit skews?? */
skew = 0;
if(upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0)
upx_success = 1;
} else {
cli_dbgmsg("UPX: UPX1 seems skewed by %d bytes\n", skew);
if(upxfn(src + skew, ssize - skew, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep-skew) >= 0 || upxfn(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >= 0)
upx_success = 1;
}
if(upx_success)
cli_dbgmsg("UPX: Successfully decompressed\n");
else
cli_dbgmsg("UPX: Preferred decompressor failed\n");
}
if(!upx_success && upxfn != upx_inflate2b) {
if(upx_inflate2b(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2b(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {
cli_dbgmsg("UPX: NRV2B decompressor failed\n");
} else {
upx_success = 1;
cli_dbgmsg("UPX: Successfully decompressed with NRV2B\n");
}
}
if(!upx_success && upxfn != upx_inflate2d) {
if(upx_inflate2d(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2d(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {
cli_dbgmsg("UPX: NRV2D decompressor failed\n");
} else {
upx_success = 1;
cli_dbgmsg("UPX: Successfully decompressed with NRV2D\n");
}
}
if(!upx_success && upxfn != upx_inflate2e) {
if(upx_inflate2e(src, ssize, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) == -1 && upx_inflate2e(src + 0x15, ssize - 0x15, dest, &dsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep - 0x15) == -1) {
cli_dbgmsg("UPX: NRV2E decompressor failed\n");
} else {
upx_success = 1;
cli_dbgmsg("UPX: Successfully decompressed with NRV2E\n");
}
}
if(cli_memstr(UPX_LZMA2, 20, epbuff + 0x2f, 20)) {
uint32_t strictdsize=cli_readint32(epbuff+0x21), skew = 0;
if(ssize > 0x15 && epbuff[0] == '\x60' && epbuff[1] == '\xbe') {
skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase;
if(skew!=0x15) skew = 0;
}
if(strictdsize<=dsize)
upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0;
} else if (cli_memstr(UPX_LZMA1, 20, epbuff + 0x39, 20)) {
uint32_t strictdsize=cli_readint32(epbuff+0x2b), skew = 0;
if(ssize > 0x15 && epbuff[0] == '\x60' && epbuff[1] == '\xbe') {
skew = cli_readint32(epbuff+2) - exe_sections[i + 1].rva - optional_hdr32.ImageBase;
if(skew!=0x15) skew = 0;
}
if(strictdsize<=dsize)
upx_success = upx_inflatelzma(src+skew, ssize-skew, dest, &strictdsize, exe_sections[i].rva, exe_sections[i + 1].rva, vep) >=0;
}
if(!upx_success) {
cli_dbgmsg("UPX: All decompressors failed\n");
free(dest);
}
}
if(upx_success) {
free(exe_sections);
CLI_UNPTEMP("UPX/FSG",(dest,0));
if((unsigned int) write(ndesc, dest, dsize) != dsize) {
cli_dbgmsg("UPX/FSG: Can't write %d bytes\n", dsize);
free(tempfile);
free(dest);
close(ndesc);
return CL_EWRITE;
}
free(dest);
lseek(ndesc, 0, SEEK_SET);
if(ctx->engine->keeptmp)
cli_dbgmsg("UPX/FSG: Decompressed data saved in %s\n", tempfile);
cli_dbgmsg("***** Scanning decompressed file *****\n");
SHA_OFF;
if((ret = cli_magic_scandesc(ndesc, ctx)) == CL_VIRUS) {
close(ndesc);
CLI_TMPUNLK();
free(tempfile);
SHA_RESET;
return CL_VIRUS;
}
SHA_RESET;
close(ndesc);
CLI_TMPUNLK();
free(tempfile);
return ret;
}
/* Petite */
if(epsize<200) {
free(exe_sections);
return CL_CLEAN;
}
found = 2;
if(epbuff[0] != '\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 1].rva + EC32(optional_hdr32.ImageBase)) {
if(nsections < 2 || epbuff[0] != '\xb8' || (uint32_t) cli_readint32(epbuff + 1) != exe_sections[nsections - 2].rva + EC32(optional_hdr32.ImageBase))
found = 0;
else
found = 1;
}
if(found && (DCONF & PE_CONF_PETITE)) {
cli_dbgmsg("Petite: v2.%d compression detected\n", found);
if(cli_readint32(epbuff + 0x80) == 0x163c988d) {
cli_dbgmsg("Petite: level zero compression is not supported yet\n");
} else {
dsize = max - min;
CLI_UNPSIZELIMITS("Petite", dsize);
if((dest = (char *) cli_calloc(dsize, sizeof(char))) == NULL) {
cli_dbgmsg("Petite: Can't allocate %d bytes\n", dsize);
free(exe_sections);
return CL_EMEM;
}
for(i = 0 ; i < nsections; i++) {
if(exe_sections[i].raw) {
if(!exe_sections[i].rsz || fmap_readn(map, dest + exe_sections[i].rva - min, exe_sections[i].raw, exe_sections[i].ursz) != exe_sections[i].ursz) {
free(exe_sections);
free(dest);
return CL_CLEAN;
}
}
}
CLI_UNPTEMP("Petite",(dest,exe_sections,0));
CLI_UNPRESULTS("Petite",(petite_inflate2x_1to9(dest, min, max - min, exe_sections, nsections - (found == 1 ? 1 : 0), EC32(optional_hdr32.ImageBase),vep, ndesc, found, EC32(optional_hdr32.DataDirectory[2].VirtualAddress),EC32(optional_hdr32.DataDirectory[2].Size))),0,(dest,0));
}
}
/* PESpin 1.1 */
if((DCONF & PE_CONF_PESPIN) && nsections > 1 &&
vep >= exe_sections[nsections - 1].rva &&
vep < exe_sections[nsections - 1].rva + exe_sections[nsections - 1].rsz - 0x3217 - 4 &&
memcmp(epbuff+4, "\xe8\x00\x00\x00\x00\x8b\x1c\x24\x83\xc3", 10) == 0) {
char *spinned;
CLI_UNPSIZELIMITS("PEspin", fsize);
if((spinned = (char *) cli_malloc(fsize)) == NULL) {
free(exe_sections);
return CL_EMEM;
}
if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) {
cli_dbgmsg("PESpin: Can't read %lu bytes\n", (unsigned long)fsize);
free(spinned);
free(exe_sections);
return CL_EREAD;
}
CLI_UNPTEMP("PESpin",(spinned,exe_sections,0));
CLI_UNPRESULTS_("PEspin",SPINCASE(),(unspin(spinned, fsize, exe_sections, nsections - 1, vep, ndesc, ctx)),0,(spinned,0));
}
/* yC 1.3 & variants */
if((DCONF & PE_CONF_YC) && nsections > 1 &&
(EC32(optional_hdr32.AddressOfEntryPoint) == exe_sections[nsections - 1].rva + 0x60)) {
uint32_t ecx = 0;
int16_t offset;
/* yC 1.3 */
if (!memcmp(epbuff, "\x55\x8B\xEC\x53\x56\x57\x60\xE8\x00\x00\x00\x00\x5D\x81\xED", 15) &&
!memcmp(epbuff+0x26, "\x8D\x3A\x8B\xF7\x33\xC0\xEB\x04\x90\xEB\x01\xC2\xAC", 13) &&
((uint8_t)epbuff[0x13] == 0xB9) &&
((uint16_t)(cli_readint16(epbuff+0x18)) == 0xE981) &&
!memcmp(epbuff+0x1e,"\x8B\xD5\x81\xC2", 4)) {
offset = 0;
if (0x6c - cli_readint32(epbuff+0xf) + cli_readint32(epbuff+0x22) == 0xC6)
ecx = cli_readint32(epbuff+0x14) - cli_readint32(epbuff+0x1a);
}
/* yC 1.3 variant */
if (!ecx && !memcmp(epbuff, "\x55\x8B\xEC\x83\xEC\x40\x53\x56\x57", 9) &&
!memcmp(epbuff+0x17, "\xe8\x00\x00\x00\x00\x5d\x81\xed", 8) &&
((uint8_t)epbuff[0x23] == 0xB9)) {
offset = 0x10;
if (0x6c - cli_readint32(epbuff+0x1f) + cli_readint32(epbuff+0x32) == 0xC6)
ecx = cli_readint32(epbuff+0x24) - cli_readint32(epbuff+0x2a);
}
/* yC 1.x/modified */
if (!ecx && !memcmp(epbuff, "\x60\xe8\x00\x00\x00\x00\x5d\x81\xed",9) &&
((uint8_t)epbuff[0xd] == 0xb9) &&
((uint16_t)cli_readint16(epbuff + 0x12)== 0xbd8d) &&
!memcmp(epbuff+0x18, "\x8b\xf7\xac", 3)) {
offset = -0x18;
if (0x66 - cli_readint32(epbuff+0x9) + cli_readint32(epbuff+0x14) == 0xae)
ecx = cli_readint32(epbuff+0xe);
}
if (ecx > 0x800 && ecx < 0x2000 &&
!memcmp(epbuff+0x63+offset, "\xaa\xe2\xcc", 3) &&
(fsize >= exe_sections[nsections-1].raw + 0xC6 + ecx + offset)) {
char *spinned;
if((spinned = (char *) cli_malloc(fsize)) == NULL) {
free(exe_sections);
return CL_EMEM;
}
if((size_t) fmap_readn(map, spinned, 0, fsize) != fsize) {
cli_dbgmsg("yC: Can't read %lu bytes\n", (unsigned long)fsize);
free(spinned);
free(exe_sections);
return CL_EREAD;
}
cli_dbgmsg("%d,%d,%d,%d\n", nsections-1, e_lfanew, ecx, offset);
CLI_UNPTEMP("yC",(spinned,exe_sections,0));
CLI_UNPRESULTS("yC",(yc_decrypt(spinned, fsize, exe_sections, nsections-1, e_lfanew, ndesc, ecx, offset)),0,(spinned,0));
}
}
/* WWPack */
while ((DCONF & PE_CONF_WWPACK) && nsections > 1 &&
vep == exe_sections[nsections - 1].rva &&
memcmp(epbuff, "\x53\x55\x8b\xe8\x33\xdb\xeb", 7) == 0 &&
memcmp(epbuff+0x68, "\xe8\x00\x00\x00\x00\x58\x2d\x6d\x00\x00\x00\x50\x60\x33\xc9\x50\x58\x50\x50", 19) == 0) {
uint32_t head = exe_sections[nsections - 1].raw;
uint8_t *packer;
ssize = 0;
for(i=0 ; ; i++) {
if(exe_sections[i].raw<head)
head=exe_sections[i].raw;
if(i+1==nsections) break;
if(ssize<exe_sections[i].rva+exe_sections[i].vsz)
ssize=exe_sections[i].rva+exe_sections[i].vsz;
}
if(!head || !ssize || head>ssize) break;
CLI_UNPSIZELIMITS("WWPack", ssize);
if(!(src=(char *)cli_calloc(ssize, sizeof(char)))) {
free(exe_sections);
return CL_EMEM;
}
if((size_t) fmap_readn(map, src, 0, head) != head) {
cli_dbgmsg("WWPack: Can't read %d bytes from headers\n", head);
free(src);
free(exe_sections);
return CL_EREAD;
}
for(i = 0 ; i < (unsigned int)nsections-1; i++) {
if(!exe_sections[i].rsz) continue;
if(!CLI_ISCONTAINED(src, ssize, src+exe_sections[i].rva, exe_sections[i].rsz)) break;
if(fmap_readn(map, src+exe_sections[i].rva, exe_sections[i].raw, exe_sections[i].rsz)!=exe_sections[i].rsz) break;
}
if(i+1!=nsections) {
cli_dbgmsg("WWpack: Probably hacked/damaged file.\n");
free(src);
break;
}
if((packer = (uint8_t *) cli_calloc(exe_sections[nsections - 1].rsz, sizeof(char))) == NULL) {
free(src);
free(exe_sections);
return CL_EMEM;
}
if(!exe_sections[nsections - 1].rsz || (size_t) fmap_readn(map, packer, exe_sections[nsections - 1].raw, exe_sections[nsections - 1].rsz) != exe_sections[nsections - 1].rsz) {
cli_dbgmsg("WWPack: Can't read %d bytes from wwpack sect\n", exe_sections[nsections - 1].rsz);
free(src);
free(packer);
free(exe_sections);
return CL_EREAD;
}
CLI_UNPTEMP("WWPack",(src,packer,exe_sections,0));
CLI_UNPRESULTS("WWPack",(wwunpack((uint8_t *)src, ssize, packer, exe_sections, nsections-1, e_lfanew, ndesc)),0,(src,packer,0));
break;
}
/* ASPACK support */
while((DCONF & PE_CONF_ASPACK) && ep+58+0x70e < fsize && !memcmp(epbuff,"\x60\xe8\x03\x00\x00\x00\xe9\xeb",8)) {
if(epsize<0x3bf || memcmp(epbuff+0x3b9, "\x68\x00\x00\x00\x00\xc3",6)) break;
ssize = 0;
for(i=0 ; i< nsections ; i++)
if(ssize<exe_sections[i].rva+exe_sections[i].vsz)
ssize=exe_sections[i].rva+exe_sections[i].vsz;
if(!ssize) break;
CLI_UNPSIZELIMITS("Aspack", ssize);
if(!(src=(char *)cli_calloc(ssize, sizeof(char)))) {
free(exe_sections);
return CL_EMEM;
}
for(i = 0 ; i < (unsigned int)nsections; i++) {
if(!exe_sections[i].rsz) continue;
if(!CLI_ISCONTAINED(src, ssize, src+exe_sections[i].rva, exe_sections[i].rsz)) break;
if(fmap_readn(map, src+exe_sections[i].rva, exe_sections[i].raw, exe_sections[i].rsz)!=exe_sections[i].rsz) break;
}
if(i!=nsections) {
cli_dbgmsg("Aspack: Probably hacked/damaged Aspack file.\n");
free(src);
break;
}
CLI_UNPTEMP("Aspack",(src,exe_sections,0));
CLI_UNPRESULTS("Aspack",(unaspack212((uint8_t *)src, ssize, exe_sections, nsections, vep-1, EC32(optional_hdr32.ImageBase), ndesc)),1,(src,0));
break;
}
/* NsPack */
while (DCONF & PE_CONF_NSPACK) {
uint32_t eprva = vep;
uint32_t start_of_stuff, rep = ep;
unsigned int nowinldr;
char *nbuff;
src=epbuff;
if (*epbuff=='\xe9') { /* bitched headers */
eprva = cli_readint32(epbuff+1)+vep+5;
if (!(rep = cli_rawaddr(eprva, exe_sections, nsections, &err, fsize, hdr_size)) && err) break;
if (!(nbuff = fmap_need_off_once(map, rep, 24))) break;
src = nbuff;
}
if (memcmp(src, "\x9c\x60\xe8\x00\x00\x00\x00\x5d\xb8\x07\x00\x00\x00", 13)) break;
nowinldr = 0x54-cli_readint32(src+17);
cli_dbgmsg("NsPack: Found *start_of_stuff @delta-%x\n", nowinldr);
if(!(nbuff = fmap_need_off_once(map, rep-nowinldr, 4))) break;
start_of_stuff=rep+cli_readint32(nbuff);
if(!(nbuff = fmap_need_off_once(map, start_of_stuff, 20))) break;
src = nbuff;
if (!cli_readint32(nbuff)) {
start_of_stuff+=4; /* FIXME: more to do */
src+=4;
}
ssize = cli_readint32(src+5)|0xff;
dsize = cli_readint32(src+9);
CLI_UNPSIZELIMITS("NsPack", MAX(ssize,dsize));
if (!ssize || !dsize || dsize != exe_sections[0].vsz) break;
if (!(dest=cli_malloc(dsize))) break;
/* memset(dest, 0xfc, dsize); */
if(!(src = fmap_need_off(map, start_of_stuff, ssize))) {
free(dest);
break;
}
/* memset(src, 0x00, ssize); */
eprva+=0x27a;
if (!(rep = cli_rawaddr(eprva, exe_sections, nsections, &err, fsize, hdr_size)) && err) {
free(dest);
break;
}
if(!(nbuff = fmap_need_off_once(map, rep, 5))) {
free(dest);
break;
}
fmap_unneed_off(map, start_of_stuff, ssize);
eprva=eprva+5+cli_readint32(nbuff+1);
cli_dbgmsg("NsPack: OEP = %08x\n", eprva);
CLI_UNPTEMP("NsPack",(dest,exe_sections,0));
CLI_UNPRESULTS("NsPack",(unspack(src, dest, ctx, exe_sections[0].rva, EC32(optional_hdr32.ImageBase), eprva, ndesc)),0,(dest,0));
break;
}
/* to be continued ... */
/* !!!!!!!!!!!!!! PACKERS END HERE !!!!!!!!!!!!!! */
ctx->corrupted_input = corrupted_cur;
/* Bytecode BC_PE_UNPACKER hook */
bc_ctx = cli_bytecode_context_alloc();
if (!bc_ctx) {
cli_errmsg("cli_scanpe: can't allocate memory for bc_ctx\n");
return CL_EMEM;
}
cli_bytecode_context_setpe(bc_ctx, &pedata, exe_sections);
cli_bytecode_context_setctx(bc_ctx, ctx);
ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PE_UNPACKER, map);
switch (ret) {
case CL_VIRUS:
free(exe_sections);
cli_bytecode_context_destroy(bc_ctx);
return CL_VIRUS;
case CL_SUCCESS:
ndesc = cli_bytecode_context_getresult_file(bc_ctx, &tempfile);
cli_bytecode_context_destroy(bc_ctx);
if (ndesc != -1 && tempfile) {
CLI_UNPRESULTS("bytecode PE hook", 1, 1, (0));
}
break;
default:
cli_bytecode_context_destroy(bc_ctx);
}
free(exe_sections);
if (SCAN_ALL && viruses_found)
return CL_VIRUS;
return CL_CLEAN; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'libclamav: bb #7055'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void pdf_parseobj(struct pdf_struct *pdf, struct pdf_obj *obj)
{
/* enough to hold common pdf names, we don't need all the names */
char pdfname[64];
const char *q2, *q3;
const char *q = obj->start + pdf->map;
const char *dict, *start;
off_t dict_length;
off_t bytesleft = obj_size(pdf, obj, 1);
unsigned i, filters=0;
enum objstate objstate = STATE_NONE;
if (bytesleft < 0)
return;
start = q;
/* find start of dictionary */
do {
q2 = pdf_nextobject(q, bytesleft);
bytesleft -= q2 -q;
if (!q2 || bytesleft < 0) {
return;
}
q3 = memchr(q-1, '<', q2-q+1);
q2++;
bytesleft--;
q = q2;
} while (!q3 || q3[1] != '<');
dict = q3+2;
q = dict;
bytesleft = obj_size(pdf, obj, 1) - (q - start);
/* find end of dictionary */
do {
q2 = pdf_nextobject(q, bytesleft);
bytesleft -= q2 -q;
if (!q2 || bytesleft < 0) {
return;
}
q3 = memchr(q-1, '>', q2-q+1);
q2++;
bytesleft--;
q = q2;
} while (!q3 || q3[1] != '>');
obj->flags |= 1 << OBJ_DICT;
dict_length = q3 - dict;
/* process pdf names */
for (q = dict;dict_length > 0;) {
int escapes = 0;
q2 = memchr(q, '/', dict_length);
if (!q2)
break;
dict_length -= q2 - q;
q = q2;
/* normalize PDF names */
for (i = 0;dict_length > 0 && (i < sizeof(pdfname)-1); i++) {
q++;
dict_length--;
if (*q == '#') {
if (cli_hex2str_to(q+1, pdfname+i, 2) == -1)
break;
q += 2;
dict_length -= 2;
escapes = 1;
continue;
}
if (*q == ' ' || *q == '\t' || *q == '\r' || *q == '\n' ||
*q == '/' || *q == '>' || *q == ']' || *q == '[' || *q == '<'
|| *q == '(')
break;
pdfname[i] = *q;
}
pdfname[i] = '\0';
handle_pdfname(pdf, obj, pdfname, escapes, &objstate);
if (objstate == STATE_LINEARIZED) {
long trailer_end, trailer;
pdfobj_flag(pdf, obj, LINEARIZED_PDF);
objstate = STATE_NONE;
trailer_end = pdf_readint(q, dict_length, "/H");
if (trailer_end > 0 && trailer_end < pdf->size) {
trailer = trailer_end - 1024;
if (trailer < 0) trailer = 0;
q2 = pdf->map + trailer;
cli_dbgmsg("cli_pdf: looking for trailer in linearized pdf: %ld - %ld\n", trailer, trailer_end);
pdf_parse_trailer(pdf, q2, trailer_end - trailer);
if (pdf->fileID)
cli_dbgmsg("cli_pdf: found fileID\n");
}
}
if (objstate == STATE_LAUNCHACTION)
pdfobj_flag(pdf, obj, HAS_LAUNCHACTION);
if (dict_length > 0 && (objstate == STATE_JAVASCRIPT ||
objstate == STATE_OPENACTION)) {
if (objstate == STATE_OPENACTION)
pdfobj_flag(pdf, obj, HAS_OPENACTION);
q2 = pdf_nextobject(q, dict_length);
if (q2 && isdigit(*q2)) {
uint32_t objid = atoi(q2) << 8;
while (isdigit(*q2)) q2++;
q2 = pdf_nextobject(q2, dict_length);
if (q2 && isdigit(*q2)) {
objid |= atoi(q2) & 0xff;
q2 = pdf_nextobject(q2, dict_length);
if (q2 && *q2 == 'R') {
struct pdf_obj *obj2;
cli_dbgmsg("cli_pdf: found %s stored in indirect object %u %u\n",
pdfname,
objid >> 8, objid&0xff);
obj2 = find_obj(pdf, obj, objid);
if (obj2) {
enum pdf_objflags flag = objstate == STATE_JAVASCRIPT ?
OBJ_JAVASCRIPT : OBJ_OPENACTION;
obj2->flags |= 1 << flag;
obj->flags &= ~(1 << flag);
} else {
pdfobj_flag(pdf, obj, BAD_INDOBJ);
}
}
}
}
objstate = STATE_NONE;
}
}
for (i=0;i<sizeof(pdfname_actions)/sizeof(pdfname_actions[0]);i++) {
const struct pdfname_action *act = &pdfname_actions[i];
if ((obj->flags & (1 << act->set_objflag)) &&
act->from_state == STATE_FILTER &&
act->to_state == STATE_FILTER &&
act->set_objflag != OBJ_FILTER_CRYPT &&
act->set_objflag != OBJ_FILTER_STANDARD) {
filters++;
}
}
if (filters > 2) { /* more than 2 non-crypt filters */
pdfobj_flag(pdf, obj, MANY_FILTERS);
}
if (obj->flags & ((1 << OBJ_SIGNED) | KNOWN_FILTERS))
obj->flags &= ~(1 << OBJ_FILTER_UNKNOWN);
if (obj->flags & (1 << OBJ_FILTER_UNKNOWN))
pdfobj_flag(pdf, obj, UNKNOWN_FILTER);
cli_dbgmsg("cli_pdf: %u %u obj flags: %02x\n", obj->id>>8, obj->id&0xff, obj->flags);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-189', 'CWE-79'], 'message': 'pdf: bb #7053'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void check_user_password(struct pdf_struct *pdf, int R, const char *O,
const char *U, int32_t P, int EM,
unsigned length, unsigned oulen)
{
unsigned i;
uint8_t result[16];
char data[32];
cli_md5_ctx md5;
struct arc4_state arc4;
unsigned password_empty = 0;
dbg_printhex("U: ", U, 32);
dbg_printhex("O: ", O, 32);
if (R == 5) {
uint8_t result2[32];
SHA256_CTX sha256;
/* supplement to ISO3200, 3.5.2 Algorithm 3.11 */
sha256_init(&sha256);
/* user validation salt */
sha256_update(&sha256, U+32, 8);
sha256_final(&sha256, result2);
dbg_printhex("Computed U", result2, 32);
if (!memcmp(result2, U, 32)) {
password_empty = 1;
/* Algorithm 3.2a could be used to recover encryption key */
}
} else {
/* 7.6.3.3 Algorithm 2 */
cli_md5_init(&md5);
/* empty password, password == padding */
cli_md5_update(&md5, key_padding, 32);
cli_md5_update(&md5, O, 32);
P = le32_to_host(P);
cli_md5_update(&md5, &P, 4);
cli_md5_update(&md5, pdf->fileID, pdf->fileIDlen);
if (R >= 4 && !EM) {
uint32_t v = 0xFFFFFFFF;
cli_md5_update(&md5, &v, 4);
}
cli_md5_final(result, &md5);
if (R >= 3) {
if (length > 128)
length = 128;
for (i=0;i<50;i++) {
cli_md5_init(&md5);
cli_md5_update(&md5, result, length/8);
cli_md5_final(result, &md5);
}
}
if (R == 2)
length = 40;
pdf->keylen = length / 8;
pdf->key = cli_malloc(pdf->keylen);
if (!pdf->key)
return;
memcpy(pdf->key, result, pdf->keylen);
dbg_printhex("md5", result, 16);
dbg_printhex("Candidate encryption key", pdf->key, pdf->keylen);
/* 7.6.3.3 Algorithm 6 */
if (R == 2) {
/* 7.6.3.3 Algorithm 4 */
memcpy(data, key_padding, 32);
arc4_init(&arc4, pdf->key, pdf->keylen);
arc4_apply(&arc4, data, 32);
dbg_printhex("computed U (R2)", data, 32);
if (!memcmp(data, U, 32))
password_empty = 1;
} else if (R >= 3) {
unsigned len = pdf->keylen;
/* 7.6.3.3 Algorithm 5 */
cli_md5_init(&md5);
cli_md5_update(&md5, key_padding, 32);
cli_md5_update(&md5, pdf->fileID, pdf->fileIDlen);
cli_md5_final(result, &md5);
memcpy(data, pdf->key, len);
arc4_init(&arc4, data, len);
arc4_apply(&arc4, result, 16);
for (i=1;i<=19;i++) {
unsigned j;
for (j=0;j<len;j++)
data[j] = pdf->key[j] ^ i;
arc4_init(&arc4, data, len);
arc4_apply(&arc4, result, 16);
}
dbg_printhex("fileID", pdf->fileID, pdf->fileIDlen);
dbg_printhex("computed U (R>=3)", result, 16);
if (!memcmp(result, U, 16))
password_empty = 1;
} else {
cli_dbgmsg("cli_pdf: invalid revision %d\n", R);
}
}
if (password_empty) {
cli_dbgmsg("cli_pdf: user password is empty\n");
/* The key we computed above is the key used to encrypt the streams.
* We could decrypt it now if we wanted to */
pdf->flags |= 1 << DECRYPTABLE_PDF;
} else {
cli_dbgmsg("cli_pdf: user/owner password would be required for decryption\n");
/* the key is not valid, we would need the user or the owner password to
* decrypt */
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-189', 'CWE-79'], 'message': 'pdf: bb #7053'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static char *getsistring(FILE *f, uint32_t ptr, uint32_t len) {
char *name;
uint32_t i;
if (!len) return NULL;
if (len>400) len=400;
name = cli_malloc(len);
if (!name) {
cli_dbgmsg("SIS: OOM\n");
return NULL;
}
fseek(f, ptr, SEEK_SET);
if (fread(name, len, 1, f)!=1) {
cli_dbgmsg("SIS: Unable to read string\n");
free(name);
return NULL;
}
for (i = 0 ; i < len; i+=2) name[i/2] = name[i];
name[i/2]='\0';
return name;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'bb #6808'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct net_device *rcv = NULL;
struct veth_priv *priv, *rcv_priv;
struct veth_net_stats *stats, *rcv_stats;
int length;
priv = netdev_priv(dev);
rcv = priv->peer;
rcv_priv = netdev_priv(rcv);
stats = this_cpu_ptr(priv->stats);
rcv_stats = this_cpu_ptr(rcv_priv->stats);
if (!(rcv->flags & IFF_UP))
goto tx_drop;
if (dev->features & NETIF_F_NO_CSUM)
skb->ip_summed = rcv_priv->ip_summed;
length = skb->len + ETH_HLEN;
if (dev_forward_skb(rcv, skb) != NET_RX_SUCCESS)
goto rx_drop;
stats->tx_bytes += length;
stats->tx_packets++;
rcv_stats->rx_bytes += length;
rcv_stats->rx_packets++;
return NETDEV_TX_OK;
tx_drop:
kfree_skb(skb);
stats->tx_dropped++;
return NETDEV_TX_OK;
rx_drop:
kfree_skb(skb);
rcv_stats->rx_dropped++;
return NETDEV_TX_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'veth: Dont kfree_skb() after dev_forward_skb()
In case of congestion, netif_rx() frees the skb, so we must assume
dev_forward_skb() also consume skb.
Bug introduced by commit 445409602c092
(veth: move loopback logic to common location)
We must change dev_forward_skb() to always consume skb, and veth to not
double free it.
Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3
Reported-by: Martín Ferrari <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static void drive_machine(conn *c) {
bool stop = false;
int sfd, flags = 1;
socklen_t addrlen;
struct sockaddr_storage addr;
int nreqs = settings.reqs_per_event;
int res;
const char *str;
assert(c != NULL);
while (!stop) {
switch(c->state) {
case conn_listening:
addrlen = sizeof(addr);
if ((sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen)) == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
/* these are transient, so don't log anything */
stop = true;
} else if (errno == EMFILE) {
if (settings.verbose > 0)
fprintf(stderr, "Too many open connections\n");
accept_new_conns(false);
stop = true;
} else {
perror("accept()");
stop = true;
}
break;
}
if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 ||
fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("setting O_NONBLOCK");
close(sfd);
break;
}
if (settings.maxconns_fast &&
stats.curr_conns + stats.reserved_fds >= settings.maxconns - 1) {
str = "ERROR Too many open connections\r\n";
res = write(sfd, str, strlen(str));
close(sfd);
STATS_LOCK();
stats.rejected_conns++;
STATS_UNLOCK();
} else {
dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST,
DATA_BUFFER_SIZE, tcp_transport);
}
stop = true;
break;
case conn_waiting:
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
conn_set_state(c, conn_read);
stop = true;
break;
case conn_read:
res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c);
switch (res) {
case READ_NO_DATA_RECEIVED:
conn_set_state(c, conn_waiting);
break;
case READ_DATA_RECEIVED:
conn_set_state(c, conn_parse_cmd);
break;
case READ_ERROR:
conn_set_state(c, conn_closing);
break;
case READ_MEMORY_ERROR: /* Failed to allocate more memory */
/* State already set by try_read_network */
break;
}
break;
case conn_parse_cmd :
if (try_read_command(c) == 0) {
/* wee need more data! */
conn_set_state(c, conn_waiting);
}
break;
case conn_new_cmd:
/* Only process nreqs at a time to avoid starving other
connections */
--nreqs;
if (nreqs >= 0) {
reset_cmd_handler(c);
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.conn_yields++;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rbytes > 0) {
/* We have already read in data into the input buffer,
so libevent will most likely not signal read events
on the socket (unless more data is available. As a
hack we should just put in a request to write data,
because that should be possible ;-)
*/
if (!update_event(c, EV_WRITE | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
}
stop = true;
}
break;
case conn_nread:
if (c->rlbytes == 0) {
complete_nread(c);
break;
}
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes;
if (c->ritem != c->rcurr) {
memmove(c->ritem, c->rcurr, tocopy);
}
c->ritem += tocopy;
c->rlbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
if (c->rlbytes == 0) {
break;
}
}
/* now try reading from the socket */
res = read(c->sfd, c->ritem, c->rlbytes);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
if (c->rcurr == c->ritem) {
c->rcurr += res;
}
c->ritem += res;
c->rlbytes -= res;
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0) {
fprintf(stderr, "Failed to read, and not due to blocking:\n"
"errno: %d %s \n"
"rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\n",
errno, strerror(errno),
(long)c->rcurr, (long)c->ritem, (long)c->rbuf,
(int)c->rlbytes, (int)c->rsize);
}
conn_set_state(c, conn_closing);
break;
case conn_swallow:
/* we are reading sbytes and throwing them away */
if (c->sbytes == 0) {
conn_set_state(c, conn_new_cmd);
break;
}
/* first check if we have leftovers in the conn_read buffer */
if (c->rbytes > 0) {
int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes;
c->sbytes -= tocopy;
c->rcurr += tocopy;
c->rbytes -= tocopy;
break;
}
/* now try reading from the socket */
res = read(c->sfd, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize);
if (res > 0) {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.bytes_read += res;
pthread_mutex_unlock(&c->thread->stats.mutex);
c->sbytes -= res;
break;
}
if (res == 0) { /* end of stream */
conn_set_state(c, conn_closing);
break;
}
if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (!update_event(c, EV_READ | EV_PERSIST)) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't update event\n");
conn_set_state(c, conn_closing);
break;
}
stop = true;
break;
}
/* otherwise we have a real error, on which we close the connection */
if (settings.verbose > 0)
fprintf(stderr, "Failed to read, and not due to blocking\n");
conn_set_state(c, conn_closing);
break;
case conn_write:
/*
* We want to write out a simple response. If we haven't already,
* assemble it into a msgbuf list (this will be a single-entry
* list for TCP or a two-entry list for UDP).
*/
if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) {
if (add_iov(c, c->wcurr, c->wbytes) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Couldn't build response\n");
conn_set_state(c, conn_closing);
break;
}
}
/* fall through... */
case conn_mwrite:
if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) {
if (settings.verbose > 0)
fprintf(stderr, "Failed to build UDP headers\n");
conn_set_state(c, conn_closing);
break;
}
switch (transmit(c)) {
case TRANSMIT_COMPLETE:
if (c->state == conn_mwrite) {
while (c->ileft > 0) {
item *it = *(c->icurr);
assert((it->it_flags & ITEM_SLABBED) == 0);
item_remove(it);
c->icurr++;
c->ileft--;
}
while (c->suffixleft > 0) {
char *suffix = *(c->suffixcurr);
cache_free(c->thread->suffix_cache, suffix);
c->suffixcurr++;
c->suffixleft--;
}
/* XXX: I don't know why this wasn't the general case */
if(c->protocol == binary_prot) {
conn_set_state(c, c->write_and_go);
} else {
conn_set_state(c, conn_new_cmd);
}
} else if (c->state == conn_write) {
if (c->write_and_free) {
free(c->write_and_free);
c->write_and_free = 0;
}
conn_set_state(c, c->write_and_go);
} else {
if (settings.verbose > 0)
fprintf(stderr, "Unexpected state %d\n", c->state);
conn_set_state(c, conn_closing);
}
break;
case TRANSMIT_INCOMPLETE:
case TRANSMIT_HARD_ERROR:
break; /* Continue in state machine. */
case TRANSMIT_SOFT_ERROR:
stop = true;
break;
}
break;
case conn_closing:
if (IS_UDP(c->transport))
conn_cleanup(c);
else
conn_close(c);
stop = true;
break;
case conn_max_state:
assert(false);
break;
}
}
return;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-189'], 'message': 'Fix segfault on specially crafted packet.'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: openvpn_decrypt (struct buffer *buf, struct buffer work,
const struct crypto_options *opt,
const struct frame* frame)
{
static const char error_prefix[] = "Authenticate/Decrypt packet error";
struct gc_arena gc;
gc_init (&gc);
if (buf->len > 0 && opt->key_ctx_bi)
{
struct key_ctx *ctx = &opt->key_ctx_bi->decrypt;
struct packet_id_net pin;
bool have_pin = false;
/* Verify the HMAC */
if (ctx->hmac)
{
int hmac_len;
uint8_t local_hmac[MAX_HMAC_KEY_LENGTH]; /* HMAC of ciphertext computed locally */
hmac_ctx_reset(ctx->hmac);
/* Assume the length of the input HMAC */
hmac_len = hmac_ctx_size (ctx->hmac);
/* Authentication fails if insufficient data in packet for HMAC */
if (buf->len < hmac_len)
CRYPT_ERROR ("missing authentication info");
hmac_ctx_update (ctx->hmac, BPTR (buf) + hmac_len, BLEN (buf) - hmac_len);
hmac_ctx_final (ctx->hmac, local_hmac);
/* Compare locally computed HMAC with packet HMAC */
if (memcmp (local_hmac, BPTR (buf), hmac_len))
CRYPT_ERROR ("packet HMAC authentication failed");
ASSERT (buf_advance (buf, hmac_len));
}
/* Decrypt packet ID + payload */
if (ctx->cipher)
{
const unsigned int mode = cipher_ctx_mode (ctx->cipher);
const int iv_size = cipher_ctx_iv_length (ctx->cipher);
uint8_t iv_buf[OPENVPN_MAX_IV_LENGTH];
int outlen;
/* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
ASSERT (buf_init (&work, FRAME_HEADROOM_ADJ (frame, FRAME_HEADROOM_MARKER_DECRYPT)));
/* use IV if user requested it */
CLEAR (iv_buf);
if (opt->flags & CO_USE_IV)
{
if (buf->len < iv_size)
CRYPT_ERROR ("missing IV info");
memcpy (iv_buf, BPTR (buf), iv_size);
ASSERT (buf_advance (buf, iv_size));
}
/* show the IV's initial state */
if (opt->flags & CO_USE_IV)
dmsg (D_PACKET_CONTENT, "DECRYPT IV: %s", format_hex (iv_buf, iv_size, 0, &gc));
if (buf->len < 1)
CRYPT_ERROR ("missing payload");
/* ctx->cipher was already initialized with key & keylen */
if (!cipher_ctx_reset (ctx->cipher, iv_buf))
CRYPT_ERROR ("cipher init failed");
/* Buffer overflow check (should never happen) */
if (!buf_safe (&work, buf->len))
CRYPT_ERROR ("buffer overflow");
/* Decrypt packet ID, payload */
if (!cipher_ctx_update (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf)))
CRYPT_ERROR ("cipher update failed");
work.len += outlen;
/* Flush the decryption buffer */
if (!cipher_ctx_final (ctx->cipher, BPTR (&work) + outlen, &outlen))
CRYPT_ERROR ("cipher final failed");
work.len += outlen;
dmsg (D_PACKET_CONTENT, "DECRYPT TO: %s",
format_hex (BPTR (&work), BLEN (&work), 80, &gc));
/* Get packet ID from plaintext buffer or IV, depending on cipher mode */
{
if (mode == OPENVPN_MODE_CBC)
{
if (opt->packet_id)
{
if (!packet_id_read (&pin, &work, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM)))
CRYPT_ERROR ("error reading CBC packet-id");
have_pin = true;
}
}
else if (mode == OPENVPN_MODE_CFB || mode == OPENVPN_MODE_OFB)
{
struct buffer b;
ASSERT (opt->flags & CO_USE_IV); /* IV and packet-ID required */
ASSERT (opt->packet_id); /* for this mode. */
buf_set_read (&b, iv_buf, iv_size);
if (!packet_id_read (&pin, &b, true))
CRYPT_ERROR ("error reading CFB/OFB packet-id");
have_pin = true;
}
else /* We only support CBC, CFB, or OFB modes right now */
{
ASSERT (0);
}
}
}
else
{
work = *buf;
if (opt->packet_id)
{
if (!packet_id_read (&pin, &work, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM)))
CRYPT_ERROR ("error reading packet-id");
have_pin = !BOOL_CAST (opt->flags & CO_IGNORE_PACKET_ID);
}
}
if (have_pin)
{
packet_id_reap_test (&opt->packet_id->rec);
if (packet_id_test (&opt->packet_id->rec, &pin))
{
packet_id_add (&opt->packet_id->rec, &pin);
if (opt->pid_persist && (opt->flags & CO_PACKET_ID_LONG_FORM))
packet_id_persist_save_obj (opt->pid_persist, opt->packet_id);
}
else
{
if (!(opt->flags & CO_MUTE_REPLAY_WARNINGS))
msg (D_REPLAY_ERRORS, "%s: bad packet ID (may be a replay): %s -- see the man page entry for --no-replay and --replay-window for more info or silence this warning with --mute-replay-warnings",
error_prefix, packet_id_net_print (&pin, true, &gc));
goto error_exit;
}
}
*buf = work;
}
gc_free (&gc);
return true;
error_exit:
crypto_clear_error();
buf->len = 0;
gc_free (&gc);
return false;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Use constant time memcmp when comparing HMACs in openvpn_decrypt.
Signed-off-by: Steffan Karger <[email protected]>
Acked-by: Gert Doering <[email protected]>
Signed-off-by: Gert Doering <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: process_chpw_request(krb5_context context, void *server_handle, char *realm,
krb5_keytab keytab, const krb5_fulladdr *local_faddr,
const krb5_fulladdr *remote_faddr, krb5_data *req,
krb5_data *rep)
{
krb5_error_code ret;
char *ptr;
unsigned int plen, vno;
krb5_data ap_req, ap_rep = empty_data();
krb5_data cipher = empty_data(), clear = empty_data();
krb5_auth_context auth_context = NULL;
krb5_principal changepw = NULL;
krb5_principal client, target = NULL;
krb5_ticket *ticket = NULL;
krb5_replay_data replay;
krb5_error krberror;
int numresult;
char strresult[1024];
char *clientstr = NULL, *targetstr = NULL;
const char *errmsg = NULL;
size_t clen;
char *cdots;
struct sockaddr_storage ss;
socklen_t salen;
char addrbuf[100];
krb5_address *addr = remote_faddr->address;
*rep = empty_data();
if (req->length < 4) {
/* either this, or the server is printing bad messages,
or the caller passed in garbage */
ret = KRB5KRB_AP_ERR_MODIFIED;
numresult = KRB5_KPASSWD_MALFORMED;
strlcpy(strresult, "Request was truncated", sizeof(strresult));
goto chpwfail;
}
ptr = req->data;
/* verify length */
plen = (*ptr++ & 0xff);
plen = (plen<<8) | (*ptr++ & 0xff);
if (plen != req->length) {
ret = KRB5KRB_AP_ERR_MODIFIED;
numresult = KRB5_KPASSWD_MALFORMED;
strlcpy(strresult, "Request length was inconsistent",
sizeof(strresult));
goto chpwfail;
}
/* verify version number */
vno = (*ptr++ & 0xff) ;
vno = (vno<<8) | (*ptr++ & 0xff);
if (vno != 1 && vno != RFC3244_VERSION) {
ret = KRB5KDC_ERR_BAD_PVNO;
numresult = KRB5_KPASSWD_BAD_VERSION;
snprintf(strresult, sizeof(strresult),
"Request contained unknown protocol version number %d", vno);
goto chpwfail;
}
/* read, check ap-req length */
ap_req.length = (*ptr++ & 0xff);
ap_req.length = (ap_req.length<<8) | (*ptr++ & 0xff);
if (ptr + ap_req.length >= req->data + req->length) {
ret = KRB5KRB_AP_ERR_MODIFIED;
numresult = KRB5_KPASSWD_MALFORMED;
strlcpy(strresult, "Request was truncated in AP-REQ",
sizeof(strresult));
goto chpwfail;
}
/* verify ap_req */
ap_req.data = ptr;
ptr += ap_req.length;
ret = krb5_auth_con_init(context, &auth_context);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed initializing auth context",
sizeof(strresult));
goto chpwfail;
}
ret = krb5_auth_con_setflags(context, auth_context,
KRB5_AUTH_CONTEXT_DO_SEQUENCE);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed initializing auth context",
sizeof(strresult));
goto chpwfail;
}
ret = krb5_build_principal(context, &changepw, strlen(realm), realm,
"kadmin", "changepw", NULL);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed building kadmin/changepw principal",
sizeof(strresult));
goto chpwfail;
}
ret = krb5_rd_req(context, &auth_context, &ap_req, changepw, keytab,
NULL, &ticket);
if (ret) {
numresult = KRB5_KPASSWD_AUTHERROR;
strlcpy(strresult, "Failed reading application request",
sizeof(strresult));
goto chpwfail;
}
/* construct the ap-rep */
ret = krb5_mk_rep(context, auth_context, &ap_rep);
if (ret) {
numresult = KRB5_KPASSWD_AUTHERROR;
strlcpy(strresult, "Failed replying to application request",
sizeof(strresult));
goto chpwfail;
}
/* decrypt the ChangePasswdData */
cipher.length = (req->data + req->length) - ptr;
cipher.data = ptr;
/*
* Don't set a remote address in auth_context before calling krb5_rd_priv,
* so that we can work against clients behind a NAT. Reflection attacks
* aren't a concern since we use sequence numbers and since our requests
* don't look anything like our responses. Also don't set a local address,
* since we don't know what interface the request was received on.
*/
ret = krb5_rd_priv(context, auth_context, &cipher, &clear, &replay);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed decrypting request", sizeof(strresult));
goto chpwfail;
}
client = ticket->enc_part2->client;
/* decode ChangePasswdData for setpw requests */
if (vno == RFC3244_VERSION) {
krb5_data *clear_data;
ret = decode_krb5_setpw_req(&clear, &clear_data, &target);
if (ret != 0) {
numresult = KRB5_KPASSWD_MALFORMED;
strlcpy(strresult, "Failed decoding ChangePasswdData",
sizeof(strresult));
goto chpwfail;
}
zapfree(clear.data, clear.length);
clear = *clear_data;
free(clear_data);
if (target != NULL) {
ret = krb5_unparse_name(context, target, &targetstr);
if (ret != 0) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed unparsing target name for log",
sizeof(strresult));
goto chpwfail;
}
}
}
ret = krb5_unparse_name(context, client, &clientstr);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed unparsing client name for log",
sizeof(strresult));
goto chpwfail;
}
/* for cpw, verify that this is an AS_REQ ticket */
if (vno == 1 &&
(ticket->enc_part2->flags & TKT_FLG_INITIAL) == 0) {
numresult = KRB5_KPASSWD_INITIAL_FLAG_NEEDED;
strlcpy(strresult, "Ticket must be derived from a password",
sizeof(strresult));
goto chpwfail;
}
/* change the password */
ptr = k5memdup0(clear.data, clear.length, &ret);
ret = schpw_util_wrapper(server_handle, client, target,
(ticket->enc_part2->flags & TKT_FLG_INITIAL) != 0,
ptr, NULL, strresult, sizeof(strresult));
if (ret)
errmsg = krb5_get_error_message(context, ret);
/* zap the password */
zapfree(clear.data, clear.length);
zapfree(ptr, clear.length);
clear = empty_data();
clen = strlen(clientstr);
trunc_name(&clen, &cdots);
switch (addr->addrtype) {
case ADDRTYPE_INET: {
struct sockaddr_in *sin = ss2sin(&ss);
sin->sin_family = AF_INET;
memcpy(&sin->sin_addr, addr->contents, addr->length);
sin->sin_port = htons(remote_faddr->port);
salen = sizeof(*sin);
break;
}
case ADDRTYPE_INET6: {
struct sockaddr_in6 *sin6 = ss2sin6(&ss);
sin6->sin6_family = AF_INET6;
memcpy(&sin6->sin6_addr, addr->contents, addr->length);
sin6->sin6_port = htons(remote_faddr->port);
salen = sizeof(*sin6);
break;
}
default: {
struct sockaddr *sa = ss2sa(&ss);
sa->sa_family = AF_UNSPEC;
salen = sizeof(*sa);
break;
}
}
if (getnameinfo(ss2sa(&ss), salen,
addrbuf, sizeof(addrbuf), NULL, 0,
NI_NUMERICHOST | NI_NUMERICSERV) != 0)
strlcpy(addrbuf, "<unprintable>", sizeof(addrbuf));
if (vno == RFC3244_VERSION) {
size_t tlen;
char *tdots;
const char *targetp;
if (target == NULL) {
tlen = clen;
tdots = cdots;
targetp = targetstr;
} else {
tlen = strlen(targetstr);
trunc_name(&tlen, &tdots);
targetp = clientstr;
}
krb5_klog_syslog(LOG_NOTICE, _("setpw request from %s by %.*s%s for "
"%.*s%s: %s"), addrbuf, (int) clen,
clientstr, cdots, (int) tlen, targetp, tdots,
errmsg ? errmsg : "success");
} else {
krb5_klog_syslog(LOG_NOTICE, _("chpw request from %s for %.*s%s: %s"),
addrbuf, (int) clen, clientstr, cdots,
errmsg ? errmsg : "success");
}
switch (ret) {
case KADM5_AUTH_CHANGEPW:
numresult = KRB5_KPASSWD_ACCESSDENIED;
break;
case KADM5_PASS_Q_TOOSHORT:
case KADM5_PASS_REUSE:
case KADM5_PASS_Q_CLASS:
case KADM5_PASS_Q_DICT:
case KADM5_PASS_Q_GENERIC:
case KADM5_PASS_TOOSOON:
numresult = KRB5_KPASSWD_SOFTERROR;
break;
case 0:
numresult = KRB5_KPASSWD_SUCCESS;
strlcpy(strresult, "", sizeof(strresult));
break;
default:
numresult = KRB5_KPASSWD_HARDERROR;
break;
}
chpwfail:
clear.length = 2 + strlen(strresult);
clear.data = (char *) malloc(clear.length);
ptr = clear.data;
*ptr++ = (numresult>>8) & 0xff;
*ptr++ = numresult & 0xff;
memcpy(ptr, strresult, strlen(strresult));
cipher = empty_data();
if (ap_rep.length) {
ret = krb5_auth_con_setaddrs(context, auth_context,
local_faddr->address, NULL);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult,
"Failed storing client and server internet addresses",
sizeof(strresult));
} else {
ret = krb5_mk_priv(context, auth_context, &clear, &cipher,
&replay);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed encrypting reply",
sizeof(strresult));
}
}
}
/* if no KRB-PRIV was constructed, then we need a KRB-ERROR.
if this fails, just bail. there's nothing else we can do. */
if (cipher.length == 0) {
/* clear out ap_rep now, so that it won't be inserted in the
reply */
if (ap_rep.length) {
free(ap_rep.data);
ap_rep = empty_data();
}
krberror.ctime = 0;
krberror.cusec = 0;
krberror.susec = 0;
ret = krb5_timeofday(context, &krberror.stime);
if (ret)
goto bailout;
/* this is really icky. but it's what all the other callers
to mk_error do. */
krberror.error = ret;
krberror.error -= ERROR_TABLE_BASE_krb5;
if (krberror.error < 0 || krberror.error > 128)
krberror.error = KRB_ERR_GENERIC;
krberror.client = NULL;
ret = krb5_build_principal(context, &krberror.server,
strlen(realm), realm,
"kadmin", "changepw", NULL);
if (ret)
goto bailout;
krberror.text.length = 0;
krberror.e_data = clear;
ret = krb5_mk_error(context, &krberror, &cipher);
krb5_free_principal(context, krberror.server);
if (ret)
goto bailout;
}
/* construct the reply */
ret = alloc_data(rep, 6 + ap_rep.length + cipher.length);
if (ret)
goto bailout;
ptr = rep->data;
/* length */
*ptr++ = (rep->length>>8) & 0xff;
*ptr++ = rep->length & 0xff;
/* version == 0x0001 big-endian */
*ptr++ = 0;
*ptr++ = 1;
/* ap_rep length, big-endian */
*ptr++ = (ap_rep.length>>8) & 0xff;
*ptr++ = ap_rep.length & 0xff;
/* ap-rep data */
if (ap_rep.length) {
memcpy(ptr, ap_rep.data, ap_rep.length);
ptr += ap_rep.length;
}
/* krb-priv or krb-error */
memcpy(ptr, cipher.data, cipher.length);
bailout:
krb5_auth_con_free(context, auth_context);
krb5_free_principal(context, changepw);
krb5_free_ticket(context, ticket);
free(ap_rep.data);
free(clear.data);
free(cipher.data);
krb5_free_principal(context, target);
krb5_free_unparsed_name(context, targetstr);
krb5_free_unparsed_name(context, clientstr);
krb5_free_error_message(context, errmsg);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Fix kpasswd UDP ping-pong [CVE-2002-2443]
The kpasswd service provided by kadmind was vulnerable to a UDP
"ping-pong" attack [CVE-2002-2443]. Don't respond to packets unless
they pass some basic validation, and don't respond to our own error
packets.
Some authors use CVE-1999-0103 to refer to the kpasswd UDP ping-pong
attack or UDP ping-pong attacks in general, but there is discussion
leading toward narrowing the definition of CVE-1999-0103 to the echo,
chargen, or other similar built-in inetd services.
Thanks to Vincent Danen for alerting us to this issue.
CVSSv2: AV:N/AC:L/Au:N/C:N/I:N/A:P/E:P/RL:O/RC:C
ticket: 7637 (new)
target_version: 1.11.3
tags: pullup'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: CURLcode Curl_urldecode(struct SessionHandle *data,
const char *string, size_t length,
char **ostring, size_t *olen,
bool reject_ctrl)
{
size_t alloc = (length?length:strlen(string))+1;
char *ns = malloc(alloc);
unsigned char in;
size_t strindex=0;
unsigned long hex;
CURLcode res;
if(!ns)
return CURLE_OUT_OF_MEMORY;
while(--alloc > 0) {
in = *string;
if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) {
/* this is two hexadecimal digits following a '%' */
char hexstr[3];
char *ptr;
hexstr[0] = string[1];
hexstr[1] = string[2];
hexstr[2] = 0;
hex = strtoul(hexstr, &ptr, 16);
in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */
res = Curl_convert_from_network(data, &in, 1);
if(res) {
/* Curl_convert_from_network calls failf if unsuccessful */
free(ns);
return res;
}
string+=2;
alloc-=2;
}
if(reject_ctrl && (in < 0x20)) {
free(ns);
return CURLE_URL_MALFORMAT;
}
ns[strindex++] = in;
string++;
}
ns[strindex]=0; /* terminate it */
if(olen)
/* store output size */
*olen = strindex;
if(ostring)
/* store output string */
*ostring = ns;
return CURLE_OK;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Curl_urldecode: no peeking beyond end of input buffer
Security problem: CVE-2013-2174
If a program would give a string like "%FF" to curl_easy_unescape() but
ask for it to decode only the first byte, it would still parse and
decode the full hex sequence. The function then not only read beyond the
allowed buffer but it would also deduct the *unsigned* counter variable
for how many more bytes there's left to read in the buffer by two,
making the counter wrap. Continuing this, the function would go on
reading beyond the buffer and soon writing beyond the allocated target
buffer...
Bug: http://curl.haxx.se/docs/adv_20130622.html
Reported-by: Timo Sirainen'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static apr_status_t modsecurity_request_body_store_memory(modsec_rec *msr,
const char *data, apr_size_t length, char **error_msg)
{
*error_msg = NULL;
/* Would storing this chunk mean going over the limit? */
if ((msr->msc_reqbody_spilltodisk)
&& (msr->msc_reqbody_length + length > (apr_size_t)msr->txcfg->reqbody_inmemory_limit))
{
msc_data_chunk **chunks;
unsigned int disklen = 0;
int i;
msr_log(msr, 4, "Input filter: Request too large to store in memory, switching to disk.");
/* NOTE Must use modsecurity_request_body_store_disk() here
* to prevent data to be sent to the streaming
* processors again.
*/
/* Initialise disk storage */
msr->msc_reqbody_storage = MSC_REQBODY_DISK;
if (modsecurity_request_body_start_init(msr, error_msg) < 0) return -1;
/* Write the data we keep in memory */
chunks = (msc_data_chunk **)msr->msc_reqbody_chunks->elts;
for(i = 0; i < msr->msc_reqbody_chunks->nelts; i++) {
disklen += chunks[i]->length;
if (modsecurity_request_body_store_disk(msr, chunks[i]->data, chunks[i]->length, error_msg) < 0) {
return -1;
}
free(chunks[i]->data);
chunks[i]->data = NULL;
}
/* Clear the memory pool as we no longer need the bits. */
/* IMP1 But since we only used apr_pool_clear memory might
* not be released back to the OS straight away?
*/
msr->msc_reqbody_chunks = NULL;
apr_pool_clear(msr->msc_reqbody_mp);
msr_log(msr, 4, "Input filter: Wrote %u bytes from memory to disk.", disklen);
/* Continue with disk storage from now on */
return modsecurity_request_body_store_disk(msr, data, length, error_msg);
}
/* If we're here that means we are not over the
* request body in-memory limit yet.
*/
{
unsigned long int bucket_offset, bucket_left;
bucket_offset = 0;
bucket_left = length;
/* Although we store the request body in chunks we don't
* want to use the same chunk sizes as the incoming memory
* buffers. They are often of very small sizes and that
* would make us waste a lot of memory. That's why we
* use our own chunks of CHUNK_CAPACITY sizes.
*/
/* Loop until we empty this bucket into our chunks. */
while(bucket_left > 0) {
/* Allocate a new chunk if we have to. */
if (msr->msc_reqbody_chunk_current == NULL) {
msr->msc_reqbody_chunk_current = (msc_data_chunk *)
apr_pcalloc(msr->msc_reqbody_mp, sizeof(msc_data_chunk));
if (msr->msc_reqbody_chunk_current == NULL) {
*error_msg = apr_psprintf(msr->mp, "Input filter: Failed to allocate %lu bytes "
"for request body chunk.", (unsigned long)sizeof(msc_data_chunk));
return -1;
}
msr->msc_reqbody_chunk_current->data = malloc(CHUNK_CAPACITY);
if (msr->msc_reqbody_chunk_current->data == NULL) {
*error_msg = apr_psprintf(msr->mp, "Input filter: Failed to allocate %d bytes "
"for request body chunk data.", CHUNK_CAPACITY);
return -1;
}
msr->msc_reqbody_chunk_current->length = 0;
msr->msc_reqbody_chunk_current->is_permanent = 1;
*(const msc_data_chunk **)apr_array_push(msr->msc_reqbody_chunks)
= msr->msc_reqbody_chunk_current;
}
if (bucket_left < (CHUNK_CAPACITY - msr->msc_reqbody_chunk_current->length)) {
/* There's enough space in the current chunk. */
memcpy(msr->msc_reqbody_chunk_current->data +
msr->msc_reqbody_chunk_current->length, data + bucket_offset, bucket_left);
msr->msc_reqbody_chunk_current->length += bucket_left;
bucket_left = 0;
} else {
/* Fill the existing chunk. */
unsigned long int copy_length = CHUNK_CAPACITY -
msr->msc_reqbody_chunk_current->length;
memcpy(msr->msc_reqbody_chunk_current->data +
msr->msc_reqbody_chunk_current->length, data + bucket_offset, copy_length);
bucket_offset += copy_length;
bucket_left -= copy_length;
msr->msc_reqbody_chunk_current->length += copy_length;
/* We're done with this chunk. Setting the pointer
* to NULL is going to force a new chunk to be allocated
* on the next go.
*/
msr->msc_reqbody_chunk_current = NULL;
}
}
msr->msc_reqbody_length += length;
}
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'Fixed: chuck null pointer when unknown CT is sent and over in-memory limit'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static int iscsi_add_notunderstood_response(
char *key,
char *value,
struct iscsi_param_list *param_list)
{
struct iscsi_extra_response *extra_response;
if (strlen(value) > VALUE_MAXLEN) {
pr_err("Value for notunderstood key \"%s\" exceeds %d,"
" protocol error.\n", key, VALUE_MAXLEN);
return -1;
}
extra_response = kzalloc(sizeof(struct iscsi_extra_response), GFP_KERNEL);
if (!extra_response) {
pr_err("Unable to allocate memory for"
" struct iscsi_extra_response.\n");
return -1;
}
INIT_LIST_HEAD(&extra_response->er_list);
strncpy(extra_response->key, key, strlen(key) + 1);
strncpy(extra_response->value, NOTUNDERSTOOD,
strlen(NOTUNDERSTOOD) + 1);
list_add_tail(&extra_response->er_list,
¶m_list->extra_response_list);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'iscsi-target: fix heap buffer overflow on error
If a key was larger than 64 bytes, as checked by iscsi_check_key(), the
error response packet, generated by iscsi_add_notunderstood_response(),
would still attempt to copy the entire key into the packet, overflowing
the structure on the heap.
Remote preauthentication kernel memory corruption was possible if a
target was configured and listening on the network.
CVE-2013-2850
Signed-off-by: Kees Cook <[email protected]>
Cc: [email protected]
Signed-off-by: Nicholas Bellinger <[email protected]>'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int LibRaw::subtract_black()
{
CHECK_ORDER_LOW(LIBRAW_PROGRESS_RAW2_IMAGE);
try {
if(!is_phaseone_compressed() && (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3]))
{
#define BAYERC(row,col,c) imgdata.image[((row) >> IO.shrink)*S.iwidth + ((col) >> IO.shrink)][c]
int cblk[4],i;
for(i=0;i<4;i++)
cblk[i] = C.cblack[i];
int size = S.iheight * S.iwidth;
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define LIM(x,min,max) MAX(min,MIN(x,max))
#define CLIP(x) LIM(x,0,65535)
for(i=0; i< size*4; i++)
{
int val = imgdata.image[0][i];
val -= cblk[i & 3];
imgdata.image[0][i] = CLIP(val);
if(C.data_maximum < val) C.data_maximum = val;
}
#undef MIN
#undef MAX
#undef LIM
#undef CLIP
C.maximum -= C.black;
ZERO(C.cblack);
C.black = 0;
#undef BAYERC
}
else
{
// Nothing to Do, maximum is already calculated, black level is 0, so no change
// only calculate channel maximum;
int idx;
ushort *p = (ushort*)imgdata.image;
C.data_maximum = 0;
for(idx=0;idx<S.iheight*S.iwidth*4;idx++)
if(C.data_maximum < p[idx]) C.data_maximum = p[idx];
}
return 0;
}
catch ( LibRaw_exceptions err) {
EXCEPTION_HANDLER(err);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'fixed wrong data_maximum calcluation; prevent out-of-buffer in exp_bef'</s>
|
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int LibRaw::dcraw_process(void)
{
int quality,i;
int iterations=-1, dcb_enhance=1, noiserd=0;
int eeci_refine_fl=0, es_med_passes_fl=0;
float cared=0,cablue=0;
float linenoise=0;
float lclean=0,cclean=0;
float thresh=0;
float preser=0;
float expos=1.0;
CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW);
// CHECK_ORDER_HIGH(LIBRAW_PROGRESS_PRE_INTERPOLATE);
try {
int no_crop = 1;
if (~O.cropbox[2] && ~O.cropbox[3])
no_crop=0;
libraw_decoder_info_t di;
get_decoder_info(&di);
int subtract_inline = !O.bad_pixels && !O.dark_frame && !O.wf_debanding && !(di.decoder_flags & LIBRAW_DECODER_LEGACY) && !IO.zero_is_bad;
raw2image_ex(subtract_inline); // allocate imgdata.image and copy data!
int save_4color = O.four_color_rgb;
if (IO.zero_is_bad)
{
remove_zeroes();
SET_PROC_FLAG(LIBRAW_PROGRESS_REMOVE_ZEROES);
}
if(O.half_size)
O.four_color_rgb = 1;
if(O.bad_pixels && no_crop)
{
bad_pixels(O.bad_pixels);
SET_PROC_FLAG(LIBRAW_PROGRESS_BAD_PIXELS);
}
if (O.dark_frame && no_crop)
{
subtract (O.dark_frame);
SET_PROC_FLAG(LIBRAW_PROGRESS_DARK_FRAME);
}
if (O.wf_debanding)
{
wf_remove_banding();
}
quality = 2 + !IO.fuji_width;
if (O.user_qual >= 0) quality = O.user_qual;
if(!subtract_inline || !C.data_maximum)
{
adjust_bl();
subtract_black();
}
adjust_maximum();
if (O.user_sat > 0) C.maximum = O.user_sat;
if (P1.is_foveon)
{
if(load_raw == &LibRaw::foveon_dp_load_raw)
{
for (int i=0; i < S.height*S.width*4; i++)
if ((short) imgdata.image[0][i] < 0) imgdata.image[0][i] = 0;
}
else
foveon_interpolate();
SET_PROC_FLAG(LIBRAW_PROGRESS_FOVEON_INTERPOLATE);
}
if (O.green_matching && !O.half_size)
{
green_matching();
}
if (!P1.is_foveon)
{
scale_colors();
SET_PROC_FLAG(LIBRAW_PROGRESS_SCALE_COLORS);
}
pre_interpolate();
SET_PROC_FLAG(LIBRAW_PROGRESS_PRE_INTERPOLATE);
if (O.dcb_iterations >= 0) iterations = O.dcb_iterations;
if (O.dcb_enhance_fl >=0 ) dcb_enhance = O.dcb_enhance_fl;
if (O.fbdd_noiserd >=0 ) noiserd = O.fbdd_noiserd;
if (O.eeci_refine >=0 ) eeci_refine_fl = O.eeci_refine;
if (O.es_med_passes >0 ) es_med_passes_fl = O.es_med_passes;
// LIBRAW_DEMOSAIC_PACK_GPL3
if (!O.half_size && O.cfa_green >0) {thresh=O.green_thresh ;green_equilibrate(thresh);}
if (O.exp_correc >0) {expos=O.exp_shift ; preser=O.exp_preser; exp_bef(expos,preser);}
if (O.ca_correc >0 ) {cablue=O.cablue; cared=O.cared; CA_correct_RT(cablue, cared);}
if (O.cfaline >0 ) {linenoise=O.linenoise; cfa_linedn(linenoise);}
if (O.cfa_clean >0 ) {lclean=O.lclean; cclean=O.cclean; cfa_impulse_gauss(lclean,cclean);}
if (P1.filters)
{
if (noiserd>0 && P1.colors==3 && P1.filters) fbdd(noiserd);
if (quality == 0)
lin_interpolate();
else if (quality == 1 || P1.colors > 3 || P1.filters < 1000)
vng_interpolate();
else if (quality == 2)
ppg_interpolate();
else if (quality == 3)
ahd_interpolate(); // really don't need it here due to fallback op
else if (quality == 4)
dcb(iterations, dcb_enhance);
// LIBRAW_DEMOSAIC_PACK_GPL2
else if (quality == 5)
ahd_interpolate_mod();
else if (quality == 6)
afd_interpolate_pl(2,1);
else if (quality == 7)
vcd_interpolate(0);
else if (quality == 8)
vcd_interpolate(12);
else if (quality == 9)
lmmse_interpolate(1);
// LIBRAW_DEMOSAIC_PACK_GPL3
else if (quality == 10)
amaze_demosaic_RT();
// LGPL2
else if (quality == 11)
dht_interpolate();
else if (quality == 12)
aahd_interpolate();
// fallback to AHD
else
ahd_interpolate();
SET_PROC_FLAG(LIBRAW_PROGRESS_INTERPOLATE);
}
if (IO.mix_green)
{
for (P1.colors=3, i=0; i < S.height * S.width; i++)
imgdata.image[i][1] = (imgdata.image[i][1] + imgdata.image[i][3]) >> 1;
SET_PROC_FLAG(LIBRAW_PROGRESS_MIX_GREEN);
}
if(!P1.is_foveon)
{
if (P1.colors == 3)
{
if (quality == 8)
{
if (eeci_refine_fl == 1) refinement();
if (O.med_passes > 0) median_filter_new();
if (es_med_passes_fl > 0) es_median_filter();
}
else {
median_filter();
}
SET_PROC_FLAG(LIBRAW_PROGRESS_MEDIAN_FILTER);
}
}
if (O.highlight == 2)
{
blend_highlights();
SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS);
}
if (O.highlight > 2)
{
recover_highlights();
SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS);
}
if (O.use_fuji_rotate)
{
fuji_rotate();
SET_PROC_FLAG(LIBRAW_PROGRESS_FUJI_ROTATE);
}
if(!libraw_internal_data.output_data.histogram)
{
libraw_internal_data.output_data.histogram = (int (*)[LIBRAW_HISTOGRAM_SIZE]) malloc(sizeof(*libraw_internal_data.output_data.histogram)*4);
merror(libraw_internal_data.output_data.histogram,"LibRaw::dcraw_process()");
}
#ifndef NO_LCMS
if(O.camera_profile)
{
apply_profile(O.camera_profile,O.output_profile);
SET_PROC_FLAG(LIBRAW_PROGRESS_APPLY_PROFILE);
}
#endif
convert_to_rgb();
SET_PROC_FLAG(LIBRAW_PROGRESS_CONVERT_RGB);
if (O.use_fuji_rotate)
{
stretch();
SET_PROC_FLAG(LIBRAW_PROGRESS_STRETCH);
}
O.four_color_rgb = save_4color; // also, restore
return 0;
}
catch ( LibRaw_exceptions err) {
EXCEPTION_HANDLER(err);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'fixed wrong data_maximum calcluation; prevent out-of-buffer in exp_bef'</s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.