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: fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env)
{
int r, num;
OnigCodePoint c;
OnigEncoding enc = env->enc;
OnigSyntaxType* syn = env->syntax;
UChar* prev;
UChar* p = *src;
PFETCH_READY;
start:
if (PEND) {
tok->type = TK_EOT;
return tok->type;
}
tok->type = TK_STRING;
tok->base = 0;
tok->backp = p;
PFETCH(c);
if (IS_MC_ESC_CODE(c, syn)) {
if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE;
tok->backp = p;
PFETCH(c);
tok->u.c = c;
tok->escaped = 1;
switch (c) {
case '*':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '+':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 1;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '?':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break;
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = 1;
greedy_check:
if (!PEND && PPEEK_IS('?') &&
IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) {
PFETCH(c);
tok->u.repeat.greedy = 0;
tok->u.repeat.possessive = 0;
}
else {
possessive_check:
if (!PEND && PPEEK_IS('+') &&
((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) &&
tok->type != TK_INTERVAL) ||
(IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) &&
tok->type == TK_INTERVAL))) {
PFETCH(c);
tok->u.repeat.greedy = 1;
tok->u.repeat.possessive = 1;
}
else {
tok->u.repeat.greedy = 1;
tok->u.repeat.possessive = 0;
}
}
break;
case '{':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break;
r = fetch_range_quantifier(&p, end, tok, env);
if (r < 0) return r; /* error */
if (r == 0) goto greedy_check;
else if (r == 2) { /* {n} */
if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))
goto possessive_check;
goto greedy_check;
}
/* r == 1 : normal char */
break;
case '|':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break;
tok->type = TK_ALT;
break;
case '(':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_OPEN;
break;
case ')':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_CLOSE;
break;
case 'w':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 0;
break;
case 'W':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_WORD;
tok->u.prop.not = 1;
break;
case 'b':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_WORD_BOUND;
break;
case 'B':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_NOT_WORD_BOUND;
break;
#ifdef USE_WORD_BEGIN_END
case '<':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_WORD_BEGIN;
break;
case '>':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break;
tok->type = TK_ANCHOR;
tok->u.anchor = ANCHOR_WORD_END;
break;
#endif
case 's':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 0;
break;
case 'S':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_SPACE;
tok->u.prop.not = 1;
break;
case 'd':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 0;
break;
case 'D':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT;
tok->u.prop.not = 1;
break;
case 'h':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 0;
break;
case 'H':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break;
tok->type = TK_CHAR_TYPE;
tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT;
tok->u.prop.not = 1;
break;
case 'A':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
begin_buf:
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_BEGIN_BUF;
break;
case 'Z':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_SEMI_END_BUF;
break;
case 'z':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break;
end_buf:
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_END_BUF;
break;
case 'G':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = ANCHOR_BEGIN_POSITION;
break;
case '`':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;
goto begin_buf;
break;
case '\'':
if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break;
goto end_buf;
break;
case 'x':
if (PEND) break;
prev = p;
if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) {
PINC;
num = scan_unsigned_hexadecimal_number(&p, end, 8, enc);
if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE;
if (!PEND) {
if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK))
return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE;
}
if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) {
PINC;
tok->type = TK_CODE_POINT;
tok->u.code = (OnigCodePoint )num;
}
else {
/* can't read nothing or invalid format */
p = prev;
}
}
else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) {
num = scan_unsigned_hexadecimal_number(&p, end, 2, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 16;
tok->u.c = num;
}
break;
case 'u':
if (PEND) break;
prev = p;
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) {
num = scan_unsigned_hexadecimal_number(&p, end, 4, enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_CODE_POINT;
tok->base = 16;
tok->u.code = (OnigCodePoint )num;
}
break;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
PUNFETCH;
prev = p;
num = onig_scan_unsigned_number(&p, end, enc);
if (num < 0 || num > ONIG_MAX_BACKREF_NUM) {
goto skip_backref;
}
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) &&
(num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num]))
return ONIGERR_INVALID_BACKREF;
}
tok->type = TK_BACKREF;
tok->u.backref.num = 1;
tok->u.backref.ref1 = num;
tok->u.backref.by_name = 0;
#ifdef USE_BACKREF_WITH_LEVEL
tok->u.backref.exist_level = 0;
#endif
break;
}
skip_backref:
if (c == '8' || c == '9') {
/* normal char */
p = prev; PINC;
break;
}
p = prev;
/* fall through */
case '0':
if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) {
prev = p;
num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc);
if (num < 0) return ONIGERR_TOO_BIG_NUMBER;
if (p == prev) { /* can't read nothing. */
num = 0; /* but, it's not error */
}
tok->type = TK_RAW_BYTE;
tok->base = 8;
tok->u.c = num;
}
else if (c != '0') {
PINC;
}
break;
#ifdef USE_NAMED_GROUP
case 'k':
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) {
PFETCH(c);
if (c == '<' || c == '\'') {
UChar* name_end;
int* backs;
int back_num;
prev = p;
#ifdef USE_BACKREF_WITH_LEVEL
name_end = NULL_UCHARP; /* no need. escape gcc warning. */
r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end,
env, &back_num, &tok->u.backref.level);
if (r == 1) tok->u.backref.exist_level = 1;
else tok->u.backref.exist_level = 0;
#else
r = fetch_name(&p, end, &name_end, env, &back_num, 1);
#endif
if (r < 0) return r;
if (back_num != 0) {
if (back_num < 0) {
back_num = BACKREF_REL_TO_ABS(back_num, env);
if (back_num <= 0)
return ONIGERR_INVALID_BACKREF;
}
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
if (back_num > env->num_mem ||
IS_NULL(SCANENV_MEM_NODES(env)[back_num]))
return ONIGERR_INVALID_BACKREF;
}
tok->type = TK_BACKREF;
tok->u.backref.by_name = 0;
tok->u.backref.num = 1;
tok->u.backref.ref1 = back_num;
}
else {
num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs);
if (num <= 0) {
onig_scan_env_set_error_string(env,
ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end);
return ONIGERR_UNDEFINED_NAME_REFERENCE;
}
if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) {
int i;
for (i = 0; i < num; i++) {
if (backs[i] > env->num_mem ||
IS_NULL(SCANENV_MEM_NODES(env)[backs[i]]))
return ONIGERR_INVALID_BACKREF;
}
}
tok->type = TK_BACKREF;
tok->u.backref.by_name = 1;
if (num == 1) {
tok->u.backref.num = 1;
tok->u.backref.ref1 = backs[0];
}
else {
tok->u.backref.num = num;
tok->u.backref.refs = backs;
}
}
}
else
PUNFETCH;
}
break;
#endif
#ifdef USE_SUBEXP_CALL
case 'g':
if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) {
PFETCH(c);
if (c == '<' || c == '\'') {
int gnum;
UChar* name_end;
prev = p;
r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1);
if (r < 0) return r;
tok->type = TK_CALL;
tok->u.call.name = prev;
tok->u.call.name_end = name_end;
tok->u.call.gnum = gnum;
}
else
PUNFETCH;
}
break;
#endif
case 'Q':
if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) {
tok->type = TK_QUOTE_OPEN;
}
break;
case 'p':
case 'P':
if (!PEND && PPEEK_IS('{') &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) {
PINC;
tok->type = TK_CHAR_PROPERTY;
tok->u.prop.not = (c == 'P' ? 1 : 0);
if (!PEND &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) {
PFETCH(c);
if (c == '^') {
tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0);
}
else
PUNFETCH;
}
}
break;
default:
{
OnigCodePoint c2;
PUNFETCH;
num = fetch_escaped_value(&p, end, env, &c2);
if (num < 0) return num;
/* set_raw: */
if (tok->u.c != c2) {
tok->type = TK_CODE_POINT;
tok->u.code = c2;
}
else { /* string */
p = tok->backp + enclen(enc, tok->backp);
}
}
break;
}
}
else {
tok->u.c = c;
tok->escaped = 0;
#ifdef USE_VARIABLE_META_CHARS
if ((c != ONIG_INEFFECTIVE_META_CHAR) &&
IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) {
if (c == MC_ANYCHAR(syn))
goto any_char;
else if (c == MC_ANYTIME(syn))
goto anytime;
else if (c == MC_ZERO_OR_ONE_TIME(syn))
goto zero_or_one_time;
else if (c == MC_ONE_OR_MORE_TIME(syn))
goto one_or_more_time;
else if (c == MC_ANYCHAR_ANYTIME(syn)) {
tok->type = TK_ANYCHAR_ANYTIME;
goto out;
}
}
#endif
switch (c) {
case '.':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break;
#ifdef USE_VARIABLE_META_CHARS
any_char:
#endif
tok->type = TK_ANYCHAR;
break;
case '*':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break;
#ifdef USE_VARIABLE_META_CHARS
anytime:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '+':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break;
#ifdef USE_VARIABLE_META_CHARS
one_or_more_time:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 1;
tok->u.repeat.upper = REPEAT_INFINITE;
goto greedy_check;
break;
case '?':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break;
#ifdef USE_VARIABLE_META_CHARS
zero_or_one_time:
#endif
tok->type = TK_OP_REPEAT;
tok->u.repeat.lower = 0;
tok->u.repeat.upper = 1;
goto greedy_check;
break;
case '{':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break;
r = fetch_range_quantifier(&p, end, tok, env);
if (r < 0) return r; /* error */
if (r == 0) goto greedy_check;
else if (r == 2) { /* {n} */
if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY))
goto possessive_check;
goto greedy_check;
}
/* r == 1 : normal char */
break;
case '|':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break;
tok->type = TK_ALT;
break;
case '(':
if (!PEND && PPEEK_IS('?') &&
IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) {
PINC;
if (!PEND && PPEEK_IS('#')) {
PFETCH(c);
while (1) {
if (PEND) return ONIGERR_END_PATTERN_IN_GROUP;
PFETCH(c);
if (c == MC_ESC(syn)) {
if (!PEND) PFETCH(c);
}
else {
if (c == ')') break;
}
}
goto start;
}
PUNFETCH;
}
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_OPEN;
break;
case ')':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break;
tok->type = TK_SUBEXP_CLOSE;
break;
case '^':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = (IS_SINGLELINE(env->option)
? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE);
break;
case '$':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break;
tok->type = TK_ANCHOR;
tok->u.subtype = (IS_SINGLELINE(env->option)
? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE);
break;
case '[':
if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break;
tok->type = TK_CC_OPEN;
break;
case ']':
if (*src > env->pattern) /* /].../ is allowed. */
CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]");
break;
case '#':
if (IS_EXTEND(env->option)) {
while (!PEND) {
PFETCH(c);
if (ONIGENC_IS_CODE_NEWLINE(enc, c))
break;
}
goto start;
break;
}
break;
case ' ': case '\t': case '\n': case '\r': case '\f':
if (IS_EXTEND(env->option))
goto start;
break;
default:
/* string */
break;
}
}
#ifdef USE_VARIABLE_META_CHARS
out:
#endif
*src = p;
return tok->type;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'fix #55 : Byte value expressed in octal must be smaller than 256'</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: next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type,
enum CCSTATE* state, ScanEnv* env)
{
int r;
if (*state == CCS_RANGE)
return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE;
if (*state == CCS_VALUE && *type != CCV_CLASS) {
if (*type == CCV_SB)
BITSET_SET_BIT(cc->bs, (int )(*vs));
else if (*type == CCV_CODE_POINT) {
r = add_code_range(&(cc->mbuf), env, *vs, *vs);
if (r < 0) return r;
}
}
*state = CCS_VALUE;
*type = CCV_CLASS;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'fix #60 : invalid state(CCS_VALUE) in parse_char_class()'</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: next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type,
enum CCSTATE* state, ScanEnv* env)
{
int r;
if (*state == CCS_RANGE)
return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE;
if (*state == CCS_VALUE && *type != CCV_CLASS) {
if (*type == CCV_SB)
BITSET_SET_BIT(cc->bs, (int )(*vs));
else if (*type == CCV_CODE_POINT) {
r = add_code_range(&(cc->mbuf), env, *vs, *vs);
if (r < 0) return r;
}
}
if (*state != CCS_START)
*state = CCS_VALUE;
*type = CCV_CLASS;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 're-fix #60 by check val_type'</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: entry_guard_obeys_restriction(const entry_guard_t *guard,
const entry_guard_restriction_t *rst)
{
tor_assert(guard);
if (! rst)
return 1; // No restriction? No problem.
// Only one kind of restriction exists right now
return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Consider the exit family when applying guard restrictions.
When the new path selection logic went into place, I accidentally
dropped the code that considered the _family_ of the exit node when
deciding if the guard was usable, and we didn't catch that during
code review.
This patch makes the guard_restriction_t code consider the exit
family as well, and adds some (hopefully redundant) checks for the
case where we lack a node_t for a guard but we have a bridge_info_t
for it.
Fixes bug 22753; bugfix on 0.3.0.1-alpha. Tracked as TROVE-2016-006
and CVE-2017-0377.'</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 fsnotify_oldname_free(const unsigned char *old_name)
{
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362', 'CWE-399'], 'message': 'dentry name snapshots
take_dentry_name_snapshot() takes a safe snapshot of dentry name;
if the name is a short one, it gets copied into caller-supplied
structure, otherwise an extra reference to external name is grabbed
(those are never modified). In either case the pointer to stable
string is stored into the same structure.
dentry must be held by the caller of take_dentry_name_snapshot(),
but may be freely dropped afterwards - the snapshot will stay
until destroyed by release_dentry_name_snapshot().
Intended use:
struct name_snapshot s;
take_dentry_name_snapshot(&s, dentry);
...
access s.name
...
release_dentry_name_snapshot(&s);
Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name
to pass down with event.
Signed-off-by: Al Viro <[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 inline void fsnotify_oldname_free(const unsigned char *old_name)
{
kfree(old_name);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362', 'CWE-399'], 'message': 'dentry name snapshots
take_dentry_name_snapshot() takes a safe snapshot of dentry name;
if the name is a short one, it gets copied into caller-supplied
structure, otherwise an extra reference to external name is grabbed
(those are never modified). In either case the pointer to stable
string is stored into the same structure.
dentry must be held by the caller of take_dentry_name_snapshot(),
but may be freely dropped afterwards - the snapshot will stay
until destroyed by release_dentry_name_snapshot().
Intended use:
struct name_snapshot s;
take_dentry_name_snapshot(&s, dentry);
...
access s.name
...
release_dentry_name_snapshot(&s);
Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name
to pass down with event.
Signed-off-by: Al Viro <[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 inline const char *fsnotify_oldname_init(const unsigned char *name)
{
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362', 'CWE-399'], 'message': 'dentry name snapshots
take_dentry_name_snapshot() takes a safe snapshot of dentry name;
if the name is a short one, it gets copied into caller-supplied
structure, otherwise an extra reference to external name is grabbed
(those are never modified). In either case the pointer to stable
string is stored into the same structure.
dentry must be held by the caller of take_dentry_name_snapshot(),
but may be freely dropped afterwards - the snapshot will stay
until destroyed by release_dentry_name_snapshot().
Intended use:
struct name_snapshot s;
take_dentry_name_snapshot(&s, dentry);
...
access s.name
...
release_dentry_name_snapshot(&s);
Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name
to pass down with event.
Signed-off-by: Al Viro <[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: _krb5_extract_ticket(krb5_context context,
krb5_kdc_rep *rep,
krb5_creds *creds,
krb5_keyblock *key,
krb5_const_pointer keyseed,
krb5_key_usage key_usage,
krb5_addresses *addrs,
unsigned nonce,
unsigned flags,
krb5_data *request,
krb5_decrypt_proc decrypt_proc,
krb5_const_pointer decryptarg)
{
krb5_error_code ret;
krb5_principal tmp_principal;
size_t len = 0;
time_t tmp_time;
krb5_timestamp sec_now;
/* decrypt */
if (decrypt_proc == NULL)
decrypt_proc = decrypt_tkt;
ret = (*decrypt_proc)(context, key, key_usage, decryptarg, rep);
if (ret)
goto out;
if (rep->enc_part.flags.enc_pa_rep && request) {
krb5_crypto crypto = NULL;
Checksum cksum;
PA_DATA *pa = NULL;
int idx = 0;
_krb5_debug(context, 5, "processing enc-ap-rep");
if (rep->enc_part.encrypted_pa_data == NULL ||
(pa = krb5_find_padata(rep->enc_part.encrypted_pa_data->val,
rep->enc_part.encrypted_pa_data->len,
KRB5_PADATA_REQ_ENC_PA_REP,
&idx)) == NULL)
{
_krb5_debug(context, 5, "KRB5_PADATA_REQ_ENC_PA_REP missing");
ret = KRB5KRB_AP_ERR_MODIFIED;
goto out;
}
ret = krb5_crypto_init(context, key, 0, &crypto);
if (ret)
goto out;
ret = decode_Checksum(pa->padata_value.data,
pa->padata_value.length,
&cksum, NULL);
if (ret) {
krb5_crypto_destroy(context, crypto);
goto out;
}
ret = krb5_verify_checksum(context, crypto,
KRB5_KU_AS_REQ,
request->data, request->length,
&cksum);
krb5_crypto_destroy(context, crypto);
free_Checksum(&cksum);
_krb5_debug(context, 5, "enc-ap-rep: %svalid", (ret == 0) ? "" : "in");
if (ret)
goto out;
}
/* save session key */
creds->session.keyvalue.length = 0;
creds->session.keyvalue.data = NULL;
creds->session.keytype = rep->enc_part.key.keytype;
ret = krb5_data_copy (&creds->session.keyvalue,
rep->enc_part.key.keyvalue.data,
rep->enc_part.key.keyvalue.length);
if (ret) {
krb5_clear_error_message(context);
goto out;
}
/* compare client and save */
ret = _krb5_principalname2krb5_principal(context,
&tmp_principal,
rep->kdc_rep.cname,
rep->kdc_rep.crealm);
if (ret)
goto out;
/* check client referral and save principal */
/* anonymous here ? */
if((flags & EXTRACT_TICKET_ALLOW_CNAME_MISMATCH) == 0) {
ret = check_client_referral(context, rep,
creds->client,
tmp_principal,
&creds->session);
if (ret) {
krb5_free_principal (context, tmp_principal);
goto out;
}
}
krb5_free_principal (context, creds->client);
creds->client = tmp_principal;
/* check server referral and save principal */
ret = _krb5_principalname2krb5_principal (context,
&tmp_principal,
rep->kdc_rep.ticket.sname,
rep->kdc_rep.ticket.realm);
if (ret)
goto out;
if((flags & EXTRACT_TICKET_ALLOW_SERVER_MISMATCH) == 0){
ret = check_server_referral(context,
rep,
flags,
creds->server,
tmp_principal,
&creds->session);
if (ret) {
krb5_free_principal (context, tmp_principal);
goto out;
}
}
krb5_free_principal(context, creds->server);
creds->server = tmp_principal;
/* verify names */
if(flags & EXTRACT_TICKET_MATCH_REALM){
const char *srealm = krb5_principal_get_realm(context, creds->server);
const char *crealm = krb5_principal_get_realm(context, creds->client);
if (strcmp(rep->enc_part.srealm, srealm) != 0 ||
strcmp(rep->enc_part.srealm, crealm) != 0)
{
ret = KRB5KRB_AP_ERR_MODIFIED;
krb5_clear_error_message(context);
goto out;
}
}
/* compare nonces */
if (nonce != (unsigned)rep->enc_part.nonce) {
ret = KRB5KRB_AP_ERR_MODIFIED;
krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
goto out;
}
/* set kdc-offset */
krb5_timeofday (context, &sec_now);
if (rep->enc_part.flags.initial
&& (flags & EXTRACT_TICKET_TIMESYNC)
&& context->kdc_sec_offset == 0
&& krb5_config_get_bool (context, NULL,
"libdefaults",
"kdc_timesync",
NULL)) {
context->kdc_sec_offset = rep->enc_part.authtime - sec_now;
krb5_timeofday (context, &sec_now);
}
/* check all times */
if (rep->enc_part.starttime) {
tmp_time = *rep->enc_part.starttime;
} else
tmp_time = rep->enc_part.authtime;
if (creds->times.starttime == 0
&& labs(tmp_time - sec_now) > context->max_skew) {
ret = KRB5KRB_AP_ERR_SKEW;
krb5_set_error_message (context, ret,
N_("time skew (%ld) larger than max (%ld)", ""),
labs(tmp_time - sec_now),
(long)context->max_skew);
goto out;
}
if (creds->times.starttime != 0
&& tmp_time != creds->times.starttime) {
krb5_clear_error_message (context);
ret = KRB5KRB_AP_ERR_MODIFIED;
goto out;
}
creds->times.starttime = tmp_time;
if (rep->enc_part.renew_till) {
tmp_time = *rep->enc_part.renew_till;
} else
tmp_time = 0;
if (creds->times.renew_till != 0
&& tmp_time > creds->times.renew_till) {
krb5_clear_error_message (context);
ret = KRB5KRB_AP_ERR_MODIFIED;
goto out;
}
creds->times.renew_till = tmp_time;
creds->times.authtime = rep->enc_part.authtime;
if (creds->times.endtime != 0
&& rep->enc_part.endtime > creds->times.endtime) {
krb5_clear_error_message (context);
ret = KRB5KRB_AP_ERR_MODIFIED;
goto out;
}
creds->times.endtime = rep->enc_part.endtime;
if(rep->enc_part.caddr)
krb5_copy_addresses (context, rep->enc_part.caddr, &creds->addresses);
else if(addrs)
krb5_copy_addresses (context, addrs, &creds->addresses);
else {
creds->addresses.len = 0;
creds->addresses.val = NULL;
}
creds->flags.b = rep->enc_part.flags;
creds->authdata.len = 0;
creds->authdata.val = NULL;
/* extract ticket */
ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length,
&rep->kdc_rep.ticket, &len, ret);
if(ret)
goto out;
if (creds->ticket.length != len)
krb5_abortx(context, "internal error in ASN.1 encoder");
creds->second_ticket.length = 0;
creds->second_ticket.data = NULL;
out:
memset (rep->enc_part.key.keyvalue.data, 0,
rep->enc_part.key.keyvalue.length);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-345'], 'message': 'CVE-2017-11103: Orpheus' Lyre KDC-REP service name validation
In _krb5_extract_ticket() the KDC-REP service name must be obtained from
encrypted version stored in 'enc_part' instead of the unencrypted version
stored in 'ticket'. Use of the unecrypted version provides an
opportunity for successful server impersonation and other attacks.
Identified by Jeffrey Altman, Viktor Duchovni and Nico Williams.
Change-Id: I45ef61e8a46e0f6588d64b5bd572a24c7432547c'</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 Image *ReadTGAImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
PixelInfo
pixel;
Quantum
index;
register Quantum
*q;
register ssize_t
i,
x;
size_t
base,
flag,
offset,
real,
skip;
ssize_t
count,
y;
TGAInfo
tga_info;
unsigned char
j,
k,
pixels[4],
runlength;
unsigned int
alpha_bits;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read TGA header information.
*/
count=ReadBlob(image,1,&tga_info.id_length);
tga_info.colormap_type=(unsigned char) ReadBlobByte(image);
tga_info.image_type=(TGAImageType) ReadBlobByte(image);
if ((count != 1) ||
((tga_info.image_type != TGAColormap) &&
(tga_info.image_type != TGARGB) &&
(tga_info.image_type != TGAMonochrome) &&
(tga_info.image_type != TGARLEColormap) &&
(tga_info.image_type != TGARLERGB) &&
(tga_info.image_type != TGARLEMonochrome)) ||
(((tga_info.image_type == TGAColormap) ||
(tga_info.image_type == TGARLEColormap)) &&
(tga_info.colormap_type == 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
tga_info.colormap_index=ReadBlobLSBShort(image);
tga_info.colormap_length=ReadBlobLSBShort(image);
tga_info.colormap_size=(unsigned char) ReadBlobByte(image);
tga_info.x_origin=ReadBlobLSBShort(image);
tga_info.y_origin=ReadBlobLSBShort(image);
tga_info.width=(unsigned short) ReadBlobLSBShort(image);
tga_info.height=(unsigned short) ReadBlobLSBShort(image);
tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image);
tga_info.attributes=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) &&
(tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image structure.
*/
image->columns=tga_info.width;
image->rows=tga_info.height;
alpha_bits=(tga_info.attributes & 0x0FU);
image->alpha_trait=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) ||
(tga_info.colormap_size == 32) ? BlendPixelTrait : UndefinedPixelTrait;
if ((tga_info.image_type != TGAColormap) &&
(tga_info.image_type != TGARLEColormap))
image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 :
(tga_info.bits_per_pixel <= 16) ? 5 : 8);
else
image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 :
(tga_info.colormap_size <= 16) ? 5 : 8);
if ((tga_info.image_type == TGAColormap) ||
(tga_info.image_type == TGAMonochrome) ||
(tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLEMonochrome))
image->storage_class=PseudoClass;
image->compression=NoCompression;
if ((tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLEMonochrome) ||
(tga_info.image_type == TGARLERGB))
image->compression=RLECompression;
if (image->storage_class == PseudoClass)
{
if (tga_info.colormap_type != 0)
image->colors=tga_info.colormap_index+tga_info.colormap_length;
else
{
size_t
one;
one=1;
image->colors=one << tga_info.bits_per_pixel;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (tga_info.id_length != 0)
{
char
*comment;
size_t
length;
/*
TGA image comment.
*/
length=(size_t) tga_info.id_length;
comment=(char *) NULL;
if (~length >= (MagickPathExtent-1))
comment=(char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,tga_info.id_length,(unsigned char *) comment);
comment[tga_info.id_length]='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
}
if (tga_info.attributes & (1UL << 4))
{
if (tga_info.attributes & (1UL << 5))
SetImageArtifact(image,"tga:image-origin","TopRight");
else
SetImageArtifact(image,"tga:image-origin","BottomRight");
}
else
{
if (tga_info.attributes & (1UL << 5))
SetImageArtifact(image,"tga:image-origin","TopLeft");
else
SetImageArtifact(image,"tga:image-origin","BottomLeft");
}
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(image);
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
pixel.alpha=(MagickRealType) OpaqueAlpha;
if (tga_info.colormap_type != 0)
{
/*
Read TGA raster colormap.
*/
if (image->colors < tga_info.colormap_index)
image->colors=tga_info.colormap_index;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) tga_info.colormap_index; i++)
image->colormap[i]=pixel;
for ( ; i < (ssize_t) image->colors; i++)
{
switch (tga_info.colormap_size)
{
case 8:
default:
{
/*
Gray scale.
*/
pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
pixel.green=pixel.red;
pixel.blue=pixel.red;
break;
}
case 15:
case 16:
{
QuantumAny
range;
/*
5 bits each of red green and blue.
*/
j=(unsigned char) ReadBlobByte(image);
k=(unsigned char) ReadBlobByte(image);
range=GetQuantumRange(5UL);
pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*(k & 0x03)
<< 3)+(1UL*(j & 0xe0) >> 5),range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);
break;
}
case 24:
{
/*
8 bits each of blue, green and red.
*/
pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
break;
}
case 32:
{
/*
8 bits each of blue, green, red, and alpha.
*/
pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
pixel.alpha=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
break;
}
}
image->colormap[i]=pixel;
}
}
/*
Convert TGA pixels to pixel packets.
*/
base=0;
flag=0;
skip=MagickFalse;
real=0;
index=0;
runlength=0;
offset=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
real=offset;
if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0)
real=image->rows-real-1;
q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLERGB) ||
(tga_info.image_type == TGARLEMonochrome))
{
if (runlength != 0)
{
runlength--;
skip=flag != 0;
}
else
{
count=ReadBlob(image,1,&runlength);
if (count != 1)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
flag=runlength & 0x80;
if (flag != 0)
runlength-=128;
skip=MagickFalse;
}
}
if (skip == MagickFalse)
switch (tga_info.bits_per_pixel)
{
case 8:
default:
{
/*
Gray scale.
*/
index=(Quantum) ReadBlobByte(image);
if (tga_info.colormap_type != 0)
pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image,
(ssize_t) index,exception)];
else
{
pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
index);
pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)
index);
pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)
index);
}
break;
}
case 15:
case 16:
{
QuantumAny
range;
/*
5 bits each of RGB.
*/
if (ReadBlob(image,2,pixels) != 2)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
j=pixels[0];
k=pixels[1];
range=GetQuantumRange(5UL);
pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*
(k & 0x03) << 3)+(1UL*(j & 0xe0) >> 5),range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);
if (image->alpha_trait != UndefinedPixelTrait)
pixel.alpha=(MagickRealType) ((k & 0x80) == 0 ? (Quantum)
TransparentAlpha : (Quantum) OpaqueAlpha);
if (image->storage_class == PseudoClass)
index=(Quantum) ConstrainColormapIndex(image,((ssize_t) (k << 8))+
j,exception);
break;
}
case 24:
{
/*
BGR pixels.
*/
if (ReadBlob(image,3,pixels) != 3)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);
pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);
pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);
break;
}
case 32:
{
/*
BGRA pixels.
*/
if (ReadBlob(image,4,pixels) != 4)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);
pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);
pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);
pixel.alpha=(MagickRealType) ScaleCharToQuantum(pixels[3]);
break;
}
}
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
if (image->storage_class == PseudoClass)
SetPixelIndex(image,index,q);
SetPixelRed(image,ClampToQuantum(pixel.red),q);
SetPixelGreen(image,ClampToQuantum(pixel.green),q);
SetPixelBlue(image,ClampToQuantum(pixel.blue),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
/*
if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 4)
offset+=4;
else
*/
if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 2)
offset+=2;
else
offset++;
if (offset >= image->rows)
{
base++;
offset=base;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-772'], 'message': '...'</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: _client_protocol_timeout (GsmXSMPClient *client)
{
g_debug ("GsmXSMPClient: client_protocol_timeout for client '%s' in ICE status %d",
client->priv->description,
IceConnectionStatus (client->priv->ice_connection));
gsm_client_set_status (GSM_CLIENT (client), GSM_CLIENT_FAILED);
gsm_client_disconnected (GSM_CLIENT (client));
return FALSE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-835'], 'message': '[gsm] Delay the creation of the GsmXSMPClient until it really exists
We used to create the GsmXSMPClient before the XSMP connection is really
accepted. This can lead to some issues, though. An example is:
https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:
"What is happening is that a new client (probably metacity in your
case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION
phase, which causes a new GsmXSMPClient to be added to the client
store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client
has had a chance to establish a xsmp connection, which means that
client->priv->conn will not be initialized at the point that xsmp_stop
is called on the new unregistered client."
The fix is to create the GsmXSMPClient object when there's a real XSMP
connection. This implies moving the timeout that makes sure we don't
have an empty client to the XSMP server.
https://bugzilla.gnome.org/show_bug.cgi?id=598211'</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: accept_xsmp_connection (SmsConn sms_conn,
GsmXsmpServer *server,
unsigned long *mask_ret,
SmsCallbacks *callbacks_ret,
char **failure_reason_ret)
{
IceConn ice_conn;
GsmXSMPClient *client;
/* FIXME: what about during shutdown but before gsm_xsmp_shutdown? */
if (server->priv->xsmp_sockets == NULL) {
g_debug ("GsmXsmpServer: In shutdown, rejecting new client");
*failure_reason_ret = strdup (_("Refusing new client connection because the session is currently being shut down\n"));
return FALSE;
}
ice_conn = SmsGetIceConnection (sms_conn);
client = ice_conn->context;
g_return_val_if_fail (client != NULL, TRUE);
gsm_xsmp_client_connect (client, sms_conn, mask_ret, callbacks_ret);
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-835'], 'message': '[gsm] Delay the creation of the GsmXSMPClient until it really exists
We used to create the GsmXSMPClient before the XSMP connection is really
accepted. This can lead to some issues, though. An example is:
https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:
"What is happening is that a new client (probably metacity in your
case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION
phase, which causes a new GsmXSMPClient to be added to the client
store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client
has had a chance to establish a xsmp connection, which means that
client->priv->conn will not be initialized at the point that xsmp_stop
is called on the new unregistered client."
The fix is to create the GsmXSMPClient object when there's a real XSMP
connection. This implies moving the timeout that makes sure we don't
have an empty client to the XSMP server.
https://bugzilla.gnome.org/show_bug.cgi?id=598211'</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: gsm_xsmp_client_disconnect (GsmXSMPClient *client)
{
if (client->priv->watch_id > 0) {
g_source_remove (client->priv->watch_id);
}
if (client->priv->conn != NULL) {
SmsCleanUp (client->priv->conn);
}
if (client->priv->ice_connection != NULL) {
IceSetShutdownNegotiation (client->priv->ice_connection, FALSE);
IceCloseConnection (client->priv->ice_connection);
}
if (client->priv->protocol_timeout > 0) {
g_source_remove (client->priv->protocol_timeout);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125', 'CWE-835'], 'message': '[gsm] Delay the creation of the GsmXSMPClient until it really exists
We used to create the GsmXSMPClient before the XSMP connection is really
accepted. This can lead to some issues, though. An example is:
https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:
"What is happening is that a new client (probably metacity in your
case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION
phase, which causes a new GsmXSMPClient to be added to the client
store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client
has had a chance to establish a xsmp connection, which means that
client->priv->conn will not be initialized at the point that xsmp_stop
is called on the new unregistered client."
The fix is to create the GsmXSMPClient object when there's a real XSMP
connection. This implies moving the timeout that makes sure we don't
have an empty client to the XSMP server.
https://bugzilla.gnome.org/show_bug.cgi?id=598211'</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: MemTxResult address_space_read_continue(AddressSpace *as, hwaddr addr,
MemTxAttrs attrs, uint8_t *buf,
int len, hwaddr addr1, hwaddr l,
MemoryRegion *mr)
{
uint8_t *ptr;
uint64_t val;
MemTxResult result = MEMTX_OK;
bool release_lock = false;
for (;;) {
if (!memory_access_is_direct(mr, false)) {
/* I/O case */
release_lock |= prepare_mmio_access(mr);
l = memory_access_size(mr, l, addr1);
switch (l) {
case 8:
/* 64 bit read access */
result |= memory_region_dispatch_read(mr, addr1, &val, 8,
attrs);
stq_p(buf, val);
break;
case 4:
/* 32 bit read access */
result |= memory_region_dispatch_read(mr, addr1, &val, 4,
attrs);
stl_p(buf, val);
break;
case 2:
/* 16 bit read access */
result |= memory_region_dispatch_read(mr, addr1, &val, 2,
attrs);
stw_p(buf, val);
break;
case 1:
/* 8 bit read access */
result |= memory_region_dispatch_read(mr, addr1, &val, 1,
attrs);
stb_p(buf, val);
break;
default:
abort();
}
} else {
/* RAM case */
ptr = qemu_map_ram_ptr(mr->ram_block, addr1);
memcpy(buf, ptr, l);
}
if (release_lock) {
qemu_mutex_unlock_iothread();
release_lock = false;
}
len -= l;
buf += l;
addr += l;
if (!len) {
break;
}
l = len;
mr = address_space_translate(as, addr, &addr1, &l, false);
}
return result;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'exec: use qemu_ram_ptr_length to access guest ram
When accessing guest's ram block during DMA operation, use
'qemu_ram_ptr_length' to get ram block pointer. It ensures
that DMA operation of given length is possible; And avoids
any OOB memory access situations.
Reported-by: Alex <[email protected]>
Signed-off-by: Prasad J Pandit <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Paolo Bonzini <[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 zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof)
{
char *ksep, *vsep, *val;
size_t klen, vlen;
size_t new_vlen;
if (var->ptr >= var->end) {
return 0;
}
vsep = memchr(var->ptr, '&', var->end - var->ptr);
if (!vsep) {
if (!eof) {
return 0;
} else {
vsep = var->end;
}
}
ksep = memchr(var->ptr, '=', vsep - var->ptr);
if (ksep) {
*ksep = '\0';
/* "foo=bar&" or "foo=&" */
klen = ksep - var->ptr;
vlen = vsep - ++ksep;
} else {
ksep = "";
/* "foo&" */
klen = vsep - var->ptr;
vlen = 0;
}
php_url_decode(var->ptr, klen);
val = estrndup(ksep, vlen);
if (vlen) {
vlen = php_url_decode(val, vlen);
}
if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen)) {
php_register_variable_safe(var->ptr, val, new_vlen, arr);
}
efree(val);
var->ptr = vsep + (vsep != var->end);
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Fix bug #73807'</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_seal)
{
zval *pubkeys, **pubkey, *sealdata, *ekeys;
HashTable *pubkeysht;
HashPosition pos;
EVP_PKEY **pkeys;
long * key_resources; /* so we know what to cleanup */
int i, len1, len2, *eksl, nkeys;
unsigned char *buf = NULL, **eks;
char * data; int data_len;
char *method =NULL;
int method_len = 0;
const EVP_CIPHER *cipher;
EVP_CIPHER_CTX ctx;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szza/|s", &data, &data_len, &sealdata, &ekeys, &pubkeys, &method, &method_len) == FAILURE) {
return;
}
pubkeysht = HASH_OF(pubkeys);
nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0;
if (!nkeys) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array");
RETURN_FALSE;
}
if (method) {
cipher = EVP_get_cipherbyname(method);
if (!cipher) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown signature algorithm.");
RETURN_FALSE;
}
if (EVP_CIPHER_iv_length(cipher) > 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Ciphers with modes requiring IV are not supported");
RETURN_FALSE;
}
} else {
cipher = EVP_rc4();
}
pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0);
eksl = safe_emalloc(nkeys, sizeof(*eksl), 0);
eks = safe_emalloc(nkeys, sizeof(*eks), 0);
memset(eks, 0, sizeof(*eks) * nkeys);
key_resources = safe_emalloc(nkeys, sizeof(long), 0);
memset(key_resources, 0, sizeof(*key_resources) * nkeys);
/* get the public keys we are using to seal this data */
zend_hash_internal_pointer_reset_ex(pubkeysht, &pos);
i = 0;
while (zend_hash_get_current_data_ex(pubkeysht, (void **) &pubkey,
&pos) == SUCCESS) {
pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, &key_resources[i] TSRMLS_CC);
if (pkeys[i] == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "not a public key (%dth member of pubkeys)", i+1);
RETVAL_FALSE;
goto clean_exit;
}
eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1);
zend_hash_move_forward_ex(pubkeysht, &pos);
i++;
}
if (!EVP_EncryptInit(&ctx,cipher,NULL,NULL)) {
RETVAL_FALSE;
EVP_CIPHER_CTX_cleanup(&ctx);
goto clean_exit;
}
#if 0
/* Need this if allow ciphers that require initialization vector */
ivlen = EVP_CIPHER_CTX_iv_length(&ctx);
iv = ivlen ? emalloc(ivlen + 1) : NULL;
#endif
/* allocate one byte extra to make room for \0 */
buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(&ctx));
EVP_CIPHER_CTX_cleanup(&ctx);
if (!EVP_SealInit(&ctx, cipher, eks, eksl, NULL, pkeys, nkeys) || !EVP_SealUpdate(&ctx, buf, &len1, (unsigned char *)data, data_len)) {
RETVAL_FALSE;
efree(buf);
EVP_CIPHER_CTX_cleanup(&ctx);
goto clean_exit;
}
EVP_SealFinal(&ctx, buf + len1, &len2);
if (len1 + len2 > 0) {
zval_dtor(sealdata);
buf[len1 + len2] = '\0';
buf = erealloc(buf, len1 + len2 + 1);
ZVAL_STRINGL(sealdata, (char *)buf, len1 + len2, 0);
zval_dtor(ekeys);
array_init(ekeys);
for (i=0; i<nkeys; i++) {
eks[i][eksl[i]] = '\0';
add_next_index_stringl(ekeys, erealloc(eks[i], eksl[i] + 1), eksl[i], 0);
eks[i] = NULL;
}
#if 0
/* If allow ciphers that need IV, we need this */
zval_dtor(*ivec);
if (ivlen) {
iv[ivlen] = '\0';
ZVAL_STRINGL(*ivec, erealloc(iv, ivlen + 1), ivlen, 0);
} else {
ZVAL_EMPTY_STRING(*ivec);
}
#endif
} else {
efree(buf);
}
RETVAL_LONG(len1 + len2);
EVP_CIPHER_CTX_cleanup(&ctx);
clean_exit:
for (i=0; i<nkeys; i++) {
if (key_resources[i] == -1) {
EVP_PKEY_free(pkeys[i]);
}
if (eks[i]) {
efree(eks[i]);
}
}
efree(eks);
efree(eksl);
efree(pkeys);
efree(key_resources);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-754'], 'message': 'Fix bug #74651 - check EVP_SealInit as it can return -1'</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 test_modules()
{
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.constants.one + 1 == tests.constants.two \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.constants.foo == \"foo\" \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.constants.empty == \"\" \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.empty() == \"\" \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.struct_array[1].i == 1 \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.struct_array[0].i == 1 or true \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.integer_array[0] == 0 \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.integer_array[1] == 1 \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.string_array[0] == \"foo\" \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.string_array[2] == \"baz\" \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.string_dict[\"foo\"] == \"foo\" \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.string_dict[\"bar\"] == \"bar\" \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.isum(1,2) == 3 \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.isum(1,2,3) == 6 \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.fsum(1.0,2.0) == 3.0 \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.fsum(1.0,2.0,3.0) == 6.0 \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.foobar(1) == tests.foobar(1) \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.foobar(1) != tests.foobar(2) \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { \
condition: tests.length(\"dummy\") == 5 \
}",
NULL);
assert_false_rule(
"import \"tests\" \
rule test { condition: tests.struct_array[0].i == 1 \
}",
NULL);
assert_false_rule(
"import \"tests\" \
rule test { condition: tests.isum(1,1) == 3 \
}",
NULL);
assert_false_rule(
"import \"tests\" \
rule test { condition: tests.fsum(1.0,1.0) == 3.0 \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { condition: tests.match(/foo/,\"foo\") == 3 \
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { condition: tests.match(/foo/,\"bar\") == -1\
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { condition: tests.match(/foo.bar/i,\"FOO\\nBAR\") == -1\
}",
NULL);
assert_true_rule(
"import \"tests\" \
rule test { condition: tests.match(/foo.bar/is,\"FOO\\nBAR\") == 7\
}",
NULL);
assert_error(
"import \"\\x00\"",
ERROR_INVALID_MODULE_NAME);
assert_error(
"import \"\"",
ERROR_INVALID_MODULE_NAME);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix heap overflow (reported by Jurriaan Bremer)
When setting a new array item with yr_object_array_set_item() the array size is doubled if the index for the new item is larger than the already allocated ones. No further checks were made to ensure that the index fits into the array after doubling its capacity. If the array capacity was for example 64, and a new object is assigned to an index larger than 128 the overflow occurs. As yr_object_array_set_item() is usually invoked with indexes that increase monotonically by one, this bug never triggered before. But the new "dotnet" module has the potential to allow the exploitation of this bug by scanning a specially crafted .NET binary.'</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 yr_object_array_set_item(
YR_OBJECT* object,
YR_OBJECT* item,
int index)
{
YR_OBJECT_ARRAY* array;
int i;
int count;
assert(index >= 0);
assert(object->type == OBJECT_TYPE_ARRAY);
array = object_as_array(object);
if (array->items == NULL)
{
count = yr_max(64, (index + 1) * 2);
array->items = (YR_ARRAY_ITEMS*) yr_malloc(
sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*));
if (array->items == NULL)
return ERROR_INSUFFICIENT_MEMORY;
memset(array->items->objects, 0, count * sizeof(YR_OBJECT*));
array->items->count = count;
}
else if (index >= array->items->count)
{
count = array->items->count * 2;
array->items = (YR_ARRAY_ITEMS*) yr_realloc(
array->items,
sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*));
if (array->items == NULL)
return ERROR_INSUFFICIENT_MEMORY;
for (i = array->items->count; i < count; i++)
array->items->objects[i] = NULL;
array->items->count = count;
}
item->parent = object;
array->items->objects[index] = item;
return ERROR_SUCCESS;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix heap overflow (reported by Jurriaan Bremer)
When setting a new array item with yr_object_array_set_item() the array size is doubled if the index for the new item is larger than the already allocated ones. No further checks were made to ensure that the index fits into the array after doubling its capacity. If the array capacity was for example 64, and a new object is assigned to an index larger than 128 the overflow occurs. As yr_object_array_set_item() is usually invoked with indexes that increase monotonically by one, this bug never triggered before. But the new "dotnet" module has the potential to allow the exploitation of this bug by scanning a specially crafted .NET binary.'</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: brcmf_cfg80211_mgmt_tx(struct wiphy *wiphy, struct wireless_dev *wdev,
struct cfg80211_mgmt_tx_params *params, u64 *cookie)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct ieee80211_channel *chan = params->chan;
const u8 *buf = params->buf;
size_t len = params->len;
const struct ieee80211_mgmt *mgmt;
struct brcmf_cfg80211_vif *vif;
s32 err = 0;
s32 ie_offset;
s32 ie_len;
struct brcmf_fil_action_frame_le *action_frame;
struct brcmf_fil_af_params_le *af_params;
bool ack;
s32 chan_nr;
u32 freq;
brcmf_dbg(TRACE, "Enter\n");
*cookie = 0;
mgmt = (const struct ieee80211_mgmt *)buf;
if (!ieee80211_is_mgmt(mgmt->frame_control)) {
brcmf_err("Driver only allows MGMT packet type\n");
return -EPERM;
}
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
if (ieee80211_is_probe_resp(mgmt->frame_control)) {
/* Right now the only reason to get a probe response */
/* is for p2p listen response or for p2p GO from */
/* wpa_supplicant. Unfortunately the probe is send */
/* on primary ndev, while dongle wants it on the p2p */
/* vif. Since this is only reason for a probe */
/* response to be sent, the vif is taken from cfg. */
/* If ever desired to send proberesp for non p2p */
/* response then data should be checked for */
/* "DIRECT-". Note in future supplicant will take */
/* dedicated p2p wdev to do this and then this 'hack'*/
/* is not needed anymore. */
ie_offset = DOT11_MGMT_HDR_LEN +
DOT11_BCN_PRB_FIXED_LEN;
ie_len = len - ie_offset;
if (vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif)
vif = cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
err = brcmf_vif_set_mgmt_ie(vif,
BRCMF_VNDR_IE_PRBRSP_FLAG,
&buf[ie_offset],
ie_len);
cfg80211_mgmt_tx_status(wdev, *cookie, buf, len, true,
GFP_KERNEL);
} else if (ieee80211_is_action(mgmt->frame_control)) {
af_params = kzalloc(sizeof(*af_params), GFP_KERNEL);
if (af_params == NULL) {
brcmf_err("unable to allocate frame\n");
err = -ENOMEM;
goto exit;
}
action_frame = &af_params->action_frame;
/* Add the packet Id */
action_frame->packet_id = cpu_to_le32(*cookie);
/* Add BSSID */
memcpy(&action_frame->da[0], &mgmt->da[0], ETH_ALEN);
memcpy(&af_params->bssid[0], &mgmt->bssid[0], ETH_ALEN);
/* Add the length exepted for 802.11 header */
action_frame->len = cpu_to_le16(len - DOT11_MGMT_HDR_LEN);
/* Add the channel. Use the one specified as parameter if any or
* the current one (got from the firmware) otherwise
*/
if (chan)
freq = chan->center_freq;
else
brcmf_fil_cmd_int_get(vif->ifp, BRCMF_C_GET_CHANNEL,
&freq);
chan_nr = ieee80211_frequency_to_channel(freq);
af_params->channel = cpu_to_le32(chan_nr);
memcpy(action_frame->data, &buf[DOT11_MGMT_HDR_LEN],
le16_to_cpu(action_frame->len));
brcmf_dbg(TRACE, "Action frame, cookie=%lld, len=%d, freq=%d\n",
*cookie, le16_to_cpu(action_frame->len), freq);
ack = brcmf_p2p_send_action_frame(cfg, cfg_to_ndev(cfg),
af_params);
cfg80211_mgmt_tx_status(wdev, *cookie, buf, len, ack,
GFP_KERNEL);
kfree(af_params);
} else {
brcmf_dbg(TRACE, "Unhandled, fc=%04x!!\n", mgmt->frame_control);
brcmf_dbg_hex_dump(true, buf, len, "payload, len=%zu\n", len);
}
exit:
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'brcmfmac: fix possible buffer overflow in brcmf_cfg80211_mgmt_tx()
The lower level nl80211 code in cfg80211 ensures that "len" is between
25 and NL80211_ATTR_FRAME (2304). We subtract DOT11_MGMT_HDR_LEN (24) from
"len" so thats's max of 2280. However, the action_frame->data[] buffer is
only BRCMF_FIL_ACTION_FRAME_SIZE (1800) bytes long so this memcpy() can
overflow.
memcpy(action_frame->data, &buf[DOT11_MGMT_HDR_LEN],
le16_to_cpu(action_frame->len));
Cc: [email protected] # 3.9.x
Fixes: 18e2f61db3b70 ("brcmfmac: P2P action frame tx.")
Reported-by: "freenerguo(郭大兴)" <[email protected]>
Signed-off-by: Arend van Spriel <[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 acpi_ns_terminate(void)
{
acpi_status status;
ACPI_FUNCTION_TRACE(ns_terminate);
#ifdef ACPI_EXEC_APP
{
union acpi_operand_object *prev;
union acpi_operand_object *next;
/* Delete any module-level code blocks */
next = acpi_gbl_module_code_list;
while (next) {
prev = next;
next = next->method.mutex;
prev->method.mutex = NULL; /* Clear the Mutex (cheated) field */
acpi_ut_remove_reference(prev);
}
}
#endif
/*
* Free the entire namespace -- all nodes and all objects
* attached to the nodes
*/
acpi_ns_delete_namespace_subtree(acpi_gbl_root_node);
/* Delete any objects attached to the root node */
status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE(status)) {
return_VOID;
}
acpi_ns_delete_node(acpi_gbl_root_node);
(void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE);
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Namespace freed\n"));
return_VOID;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200', 'CWE-755'], 'message': 'ACPICA: Namespace: fix operand cache leak
ACPICA commit a23325b2e583556eae88ed3f764e457786bf4df6
I found some ACPI operand cache leaks in ACPI early abort cases.
Boot log of ACPI operand cache leak is as follows:
>[ 0.174332] ACPI: Added _OSI(Module Device)
>[ 0.175504] ACPI: Added _OSI(Processor Device)
>[ 0.176010] ACPI: Added _OSI(3.0 _SCP Extensions)
>[ 0.177032] ACPI: Added _OSI(Processor Aggregator Device)
>[ 0.178284] ACPI: SCI (IRQ16705) allocation failed
>[ 0.179352] ACPI Exception: AE_NOT_ACQUIRED, Unable to install
System Control Interrupt handler (20160930/evevent-131)
>[ 0.180008] ACPI: Unable to start the ACPI Interpreter
>[ 0.181125] ACPI Error: Could not remove SCI handler
(20160930/evmisc-281)
>[ 0.184068] kmem_cache_destroy Acpi-Operand: Slab cache still has
objects
>[ 0.185358] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.10.0-rc3 #2
>[ 0.186820] Hardware name: innotek gmb_h virtual_box/virtual_box, BIOS
virtual_box 12/01/2006
>[ 0.188000] Call Trace:
>[ 0.188000] ? dump_stack+0x5c/0x7d
>[ 0.188000] ? kmem_cache_destroy+0x224/0x230
>[ 0.188000] ? acpi_sleep_proc_init+0x22/0x22
>[ 0.188000] ? acpi_os_delete_cache+0xa/0xd
>[ 0.188000] ? acpi_ut_delete_caches+0x3f/0x7b
>[ 0.188000] ? acpi_terminate+0x5/0xf
>[ 0.188000] ? acpi_init+0x288/0x32e
>[ 0.188000] ? __class_create+0x4c/0x80
>[ 0.188000] ? video_setup+0x7a/0x7a
>[ 0.188000] ? do_one_initcall+0x4e/0x1b0
>[ 0.188000] ? kernel_init_freeable+0x194/0x21a
>[ 0.188000] ? rest_init+0x80/0x80
>[ 0.188000] ? kernel_init+0xa/0x100
>[ 0.188000] ? ret_from_fork+0x25/0x30
When early abort is occurred due to invalid ACPI information, Linux kernel
terminates ACPI by calling acpi_terminate() function. The function calls
acpi_ns_terminate() function to delete namespace data and ACPI operand cache
(acpi_gbl_module_code_list).
But the deletion code in acpi_ns_terminate() function is wrapped in
ACPI_EXEC_APP definition, therefore the code is only executed when the
definition exists. If the define doesn't exist, ACPI operand cache
(acpi_gbl_module_code_list) is leaked, and stack dump is shown in kernel log.
This causes a security threat because the old kernel (<= 4.9) shows memory
locations of kernel functions in stack dump, therefore kernel ASLR can be
neutralized.
To fix ACPI operand leak for enhancing security, I made a patch which
removes the ACPI_EXEC_APP define in acpi_ns_terminate() function for
executing the deletion code unconditionally.
Link: https://github.com/acpica/acpica/commit/a23325b2
Signed-off-by: Seunghun Han <[email protected]>
Signed-off-by: Lv Zheng <[email protected]>
Signed-off-by: Bob Moore <[email protected]>
Signed-off-by: Rafael J. Wysocki <[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 nbd_negotiate_options(NBDClient *client)
{
uint32_t flags;
bool fixedNewstyle = false;
/* Client sends:
[ 0 .. 3] client flags
[ 0 .. 7] NBD_OPTS_MAGIC
[ 8 .. 11] NBD option
[12 .. 15] Data length
... Rest of request
[ 0 .. 7] NBD_OPTS_MAGIC
[ 8 .. 11] Second NBD option
[12 .. 15] Data length
... Rest of request
*/
if (nbd_negotiate_read(client->ioc, &flags, sizeof(flags)) < 0) {
LOG("read failed");
return -EIO;
}
TRACE("Checking client flags");
be32_to_cpus(&flags);
if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
TRACE("Client supports fixed newstyle handshake");
fixedNewstyle = true;
flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
}
if (flags & NBD_FLAG_C_NO_ZEROES) {
TRACE("Client supports no zeroes at handshake end");
client->no_zeroes = true;
flags &= ~NBD_FLAG_C_NO_ZEROES;
}
if (flags != 0) {
TRACE("Unknown client flags 0x%" PRIx32 " received", flags);
return -EIO;
}
while (1) {
int ret;
uint32_t clientflags, length;
uint64_t magic;
if (nbd_negotiate_read(client->ioc, &magic, sizeof(magic)) < 0) {
LOG("read failed");
return -EINVAL;
}
TRACE("Checking opts magic");
if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {
LOG("Bad magic received");
return -EINVAL;
}
if (nbd_negotiate_read(client->ioc, &clientflags,
sizeof(clientflags)) < 0)
{
LOG("read failed");
return -EINVAL;
}
clientflags = be32_to_cpu(clientflags);
if (nbd_negotiate_read(client->ioc, &length, sizeof(length)) < 0) {
LOG("read failed");
return -EINVAL;
}
length = be32_to_cpu(length);
TRACE("Checking option 0x%" PRIx32, clientflags);
if (client->tlscreds &&
client->ioc == (QIOChannel *)client->sioc) {
QIOChannel *tioc;
if (!fixedNewstyle) {
TRACE("Unsupported option 0x%" PRIx32, clientflags);
return -EINVAL;
}
switch (clientflags) {
case NBD_OPT_STARTTLS:
tioc = nbd_negotiate_handle_starttls(client, length);
if (!tioc) {
return -EIO;
}
object_unref(OBJECT(client->ioc));
client->ioc = QIO_CHANNEL(tioc);
break;
case NBD_OPT_EXPORT_NAME:
/* No way to return an error to client, so drop connection */
TRACE("Option 0x%x not permitted before TLS", clientflags);
return -EINVAL;
default:
if (nbd_negotiate_drop_sync(client->ioc, length) < 0) {
return -EIO;
}
ret = nbd_negotiate_send_rep_err(client->ioc,
NBD_REP_ERR_TLS_REQD,
clientflags,
"Option 0x%" PRIx32
"not permitted before TLS",
clientflags);
if (ret < 0) {
return ret;
}
/* Let the client keep trying, unless they asked to quit */
if (clientflags == NBD_OPT_ABORT) {
return -EINVAL;
}
break;
}
} else if (fixedNewstyle) {
switch (clientflags) {
case NBD_OPT_LIST:
ret = nbd_negotiate_handle_list(client, length);
if (ret < 0) {
return ret;
}
break;
case NBD_OPT_ABORT:
/* NBD spec says we must try to reply before
* disconnecting, but that we must also tolerate
* guests that don't wait for our reply. */
nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, clientflags);
return -EINVAL;
case NBD_OPT_EXPORT_NAME:
return nbd_negotiate_handle_export_name(client, length);
case NBD_OPT_STARTTLS:
if (nbd_negotiate_drop_sync(client->ioc, length) < 0) {
return -EIO;
}
if (client->tlscreds) {
ret = nbd_negotiate_send_rep_err(client->ioc,
NBD_REP_ERR_INVALID,
clientflags,
"TLS already enabled");
} else {
ret = nbd_negotiate_send_rep_err(client->ioc,
NBD_REP_ERR_POLICY,
clientflags,
"TLS not configured");
}
if (ret < 0) {
return ret;
}
break;
default:
if (nbd_negotiate_drop_sync(client->ioc, length) < 0) {
return -EIO;
}
ret = nbd_negotiate_send_rep_err(client->ioc,
NBD_REP_ERR_UNSUP,
clientflags,
"Unsupported option 0x%"
PRIx32,
clientflags);
if (ret < 0) {
return ret;
}
break;
}
} else {
/*
* If broken new-style we should drop the connection
* for anything except NBD_OPT_EXPORT_NAME
*/
switch (clientflags) {
case NBD_OPT_EXPORT_NAME:
return nbd_negotiate_handle_export_name(client, length);
default:
TRACE("Unsupported option 0x%" PRIx32, clientflags);
return -EINVAL;
}
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'nbd/server: get rid of nbd_negotiate_read and friends
Functions nbd_negotiate_{read,write,drop_sync} were introduced in
1a6245a5b, when nbd_rwv (was nbd_wr_sync) was working through
qemu_co_sendv_recvv (the path is nbd_wr_sync -> qemu_co_{recv/send} ->
qemu_co_send_recv -> qemu_co_sendv_recvv), which just yields, without
setting any handlers. But starting from ff82911cd nbd_rwv (was
nbd_wr_syncv) works through qio_channel_yield() which sets handlers, so
watchers are redundant in nbd_negotiate_{read,write,drop_sync}, then,
let's just use nbd_{read,write,drop} functions.
Functions nbd_{read,write,drop} has errp parameter, which is unused in
this patch. This will be fixed later.
Signed-off-by: Vladimir Sementsov-Ogievskiy <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Paolo Bonzini <[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 nbd_negotiate_handle_list(NBDClient *client, uint32_t length)
{
NBDExport *exp;
if (length) {
if (nbd_negotiate_drop_sync(client->ioc, length) < 0) {
return -EIO;
}
return nbd_negotiate_send_rep_err(client->ioc,
NBD_REP_ERR_INVALID, NBD_OPT_LIST,
"OPT_LIST should not have length");
}
/* For each export, send a NBD_REP_SERVER reply. */
QTAILQ_FOREACH(exp, &exports, next) {
if (nbd_negotiate_send_rep_list(client->ioc, exp)) {
return -EINVAL;
}
}
/* Finish with a NBD_REP_ACK. */
return nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, NBD_OPT_LIST);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'nbd/server: get rid of nbd_negotiate_read and friends
Functions nbd_negotiate_{read,write,drop_sync} were introduced in
1a6245a5b, when nbd_rwv (was nbd_wr_sync) was working through
qemu_co_sendv_recvv (the path is nbd_wr_sync -> qemu_co_{recv/send} ->
qemu_co_send_recv -> qemu_co_sendv_recvv), which just yields, without
setting any handlers. But starting from ff82911cd nbd_rwv (was
nbd_wr_syncv) works through qio_channel_yield() which sets handlers, so
watchers are redundant in nbd_negotiate_{read,write,drop_sync}, then,
let's just use nbd_{read,write,drop} functions.
Functions nbd_{read,write,drop} has errp parameter, which is unused in
this patch. This will be fixed later.
Signed-off-by: Vladimir Sementsov-Ogievskiy <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Paolo Bonzini <[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 gboolean nbd_negotiate_continue(QIOChannel *ioc,
GIOCondition condition,
void *opaque)
{
qemu_coroutine_enter(opaque);
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'nbd/server: get rid of nbd_negotiate_read and friends
Functions nbd_negotiate_{read,write,drop_sync} were introduced in
1a6245a5b, when nbd_rwv (was nbd_wr_sync) was working through
qemu_co_sendv_recvv (the path is nbd_wr_sync -> qemu_co_{recv/send} ->
qemu_co_send_recv -> qemu_co_sendv_recvv), which just yields, without
setting any handlers. But starting from ff82911cd nbd_rwv (was
nbd_wr_syncv) works through qio_channel_yield() which sets handlers, so
watchers are redundant in nbd_negotiate_{read,write,drop_sync}, then,
let's just use nbd_{read,write,drop} functions.
Functions nbd_{read,write,drop} has errp parameter, which is unused in
this patch. This will be fixed later.
Signed-off-by: Vladimir Sementsov-Ogievskiy <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Paolo Bonzini <[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 nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
{
ssize_t ret;
uint8_t *buffer = g_malloc(MIN(65536, size));
while (size > 0) {
size_t count = MIN(65536, size);
ret = nbd_negotiate_read(ioc, buffer, count);
if (ret < 0) {
g_free(buffer);
return ret;
}
size -= count;
}
g_free(buffer);
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'nbd/server: get rid of nbd_negotiate_read and friends
Functions nbd_negotiate_{read,write,drop_sync} were introduced in
1a6245a5b, when nbd_rwv (was nbd_wr_sync) was working through
qemu_co_sendv_recvv (the path is nbd_wr_sync -> qemu_co_{recv/send} ->
qemu_co_send_recv -> qemu_co_sendv_recvv), which just yields, without
setting any handlers. But starting from ff82911cd nbd_rwv (was
nbd_wr_syncv) works through qio_channel_yield() which sets handlers, so
watchers are redundant in nbd_negotiate_{read,write,drop_sync}, then,
let's just use nbd_{read,write,drop} functions.
Functions nbd_{read,write,drop} has errp parameter, which is unused in
this patch. This will be fixed later.
Signed-off-by: Vladimir Sementsov-Ogievskiy <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Paolo Bonzini <[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 nbd_negotiate_write(QIOChannel *ioc, const void *buffer, size_t size)
{
ssize_t ret;
guint watch;
assert(qemu_in_coroutine());
/* Negotiation are always in main loop. */
watch = qio_channel_add_watch(ioc,
G_IO_OUT,
nbd_negotiate_continue,
qemu_coroutine_self(),
NULL);
ret = nbd_write(ioc, buffer, size, NULL);
g_source_remove(watch);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'nbd/server: get rid of nbd_negotiate_read and friends
Functions nbd_negotiate_{read,write,drop_sync} were introduced in
1a6245a5b, when nbd_rwv (was nbd_wr_sync) was working through
qemu_co_sendv_recvv (the path is nbd_wr_sync -> qemu_co_{recv/send} ->
qemu_co_send_recv -> qemu_co_sendv_recvv), which just yields, without
setting any handlers. But starting from ff82911cd nbd_rwv (was
nbd_wr_syncv) works through qio_channel_yield() which sets handlers, so
watchers are redundant in nbd_negotiate_{read,write,drop_sync}, then,
let's just use nbd_{read,write,drop} functions.
Functions nbd_{read,write,drop} has errp parameter, which is unused in
this patch. This will be fixed later.
Signed-off-by: Vladimir Sementsov-Ogievskiy <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Paolo Bonzini <[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 nbd_negotiate_send_rep_len(QIOChannel *ioc, uint32_t type,
uint32_t opt, uint32_t len)
{
uint64_t magic;
TRACE("Reply opt=%" PRIx32 " type=%" PRIx32 " len=%" PRIu32,
type, opt, len);
magic = cpu_to_be64(NBD_REP_MAGIC);
if (nbd_negotiate_write(ioc, &magic, sizeof(magic)) < 0) {
LOG("write failed (rep magic)");
return -EINVAL;
}
opt = cpu_to_be32(opt);
if (nbd_negotiate_write(ioc, &opt, sizeof(opt)) < 0) {
LOG("write failed (rep opt)");
return -EINVAL;
}
type = cpu_to_be32(type);
if (nbd_negotiate_write(ioc, &type, sizeof(type)) < 0) {
LOG("write failed (rep type)");
return -EINVAL;
}
len = cpu_to_be32(len);
if (nbd_negotiate_write(ioc, &len, sizeof(len)) < 0) {
LOG("write failed (rep data length)");
return -EINVAL;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'nbd/server: get rid of nbd_negotiate_read and friends
Functions nbd_negotiate_{read,write,drop_sync} were introduced in
1a6245a5b, when nbd_rwv (was nbd_wr_sync) was working through
qemu_co_sendv_recvv (the path is nbd_wr_sync -> qemu_co_{recv/send} ->
qemu_co_send_recv -> qemu_co_sendv_recvv), which just yields, without
setting any handlers. But starting from ff82911cd nbd_rwv (was
nbd_wr_syncv) works through qio_channel_yield() which sets handlers, so
watchers are redundant in nbd_negotiate_{read,write,drop_sync}, then,
let's just use nbd_{read,write,drop} functions.
Functions nbd_{read,write,drop} has errp parameter, which is unused in
this patch. This will be fixed later.
Signed-off-by: Vladimir Sementsov-Ogievskiy <[email protected]>
Reviewed-by: Eric Blake <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Paolo Bonzini <[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: MagickExport void GetNextToken(const char *start,const char **end,
const size_t extent,char *token)
{
double
value;
register const char
*p;
register ssize_t
i;
assert(start != (const char *) NULL);
assert(token != (char *) NULL);
i=0;
p=start;
while ((isspace((int) ((unsigned char) *p)) != 0) && (*p != '\0'))
p++;
switch (*p)
{
case '\0':
break;
case '"':
case '\'':
case '`':
case '{':
{
register char
escape;
switch (*p)
{
case '"': escape='"'; break;
case '\'': escape='\''; break;
case '`': escape='\''; break;
case '{': escape='}'; break;
default: escape=(*p); break;
}
for (p++; *p != '\0'; p++)
{
if ((*p == '\\') && ((*(p+1) == escape) || (*(p+1) == '\\')))
p++;
else
if (*p == escape)
{
p++;
break;
}
if (i < (ssize_t) (extent-1))
token[i++]=(*p);
}
break;
}
case '/':
{
if (i < (ssize_t) (extent-1))
token[i++]=(*p++);
if ((*p == '>') || (*p == '/'))
if (i < (ssize_t) (extent-1))
token[i++]=(*p++);
break;
}
default:
{
char
*q;
value=StringToDouble(p,&q);
(void) value;
if ((p != q) && (*p != ','))
{
for ( ; (p < q) && (*p != ','); p++)
if (i < (ssize_t) (extent-1))
token[i++]=(*p);
if (*p == '%')
if (i < (ssize_t) (extent-1))
token[i++]=(*p++);
break;
}
if ((*p != '\0') && (isalpha((int) ((unsigned char) *p)) == 0) &&
(*p != *DirectorySeparator) && (*p != '#') && (*p != '<'))
{
if (i < (ssize_t) (extent-1))
token[i++]=(*p++);
break;
}
for ( ; *p != '\0'; p++)
{
if (((isspace((int) ((unsigned char) *p)) != 0) || (*p == '=') ||
(*p == ',') || (*p == ':') || (*p == ';')) && (*(p-1) != '\\'))
break;
if ((i > 0) && (*p == '<'))
break;
if (i < (ssize_t) (extent-1))
token[i++]=(*p);
if (*p == '>')
break;
if (*p == '(')
for (p++; *p != '\0'; p++)
{
if (i < (ssize_t) (extent-1))
token[i++]=(*p);
if ((*p == ')') && (*(p-1) != '\\'))
break;
}
}
break;
}
}
token[i]='\0';
if (LocaleNCompare(token,"url(",4) == 0)
{
ssize_t
offset;
offset=4;
if (token[offset] == '#')
offset++;
i=(ssize_t) strlen(token);
(void) CopyMagickString(token,token+offset,MagickPathExtent);
token[i-offset-1]='\0';
}
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (end != (const char **) NULL)
*end=(const char *) p;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/539'</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: gdImagePtr gdImageCreateFromGifCtx(gdIOCtxPtr fd) /* {{{ */
{
int BitPixel;
#if 0
int ColorResolution;
int Background;
int AspectRatio;
#endif
int Transparent = (-1);
unsigned char buf[16];
unsigned char c;
unsigned char ColorMap[3][MAXCOLORMAPSIZE];
unsigned char localColorMap[3][MAXCOLORMAPSIZE];
int imw, imh, screen_width, screen_height;
int gif87a, useGlobalColormap;
int bitPixel;
int i;
/*1.4//int imageCount = 0; */
int ZeroDataBlock = FALSE;
int haveGlobalColormap;
gdImagePtr im = 0;
/*1.4//imageNumber = 1; */
if (! ReadOK(fd,buf,6)) {
return 0;
}
if (strncmp((char *)buf,"GIF",3) != 0) {
return 0;
}
if (memcmp((char *)buf+3, "87a", 3) == 0) {
gif87a = 1;
} else if (memcmp((char *)buf+3, "89a", 3) == 0) {
gif87a = 0;
} else {
return 0;
}
if (! ReadOK(fd,buf,7)) {
return 0;
}
BitPixel = 2<<(buf[4]&0x07);
#if 0
ColorResolution = (int) (((buf[4]&0x70)>>3)+1);
Background = buf[5];
AspectRatio = buf[6];
#endif
screen_width = imw = LM_to_uint(buf[0],buf[1]);
screen_height = imh = LM_to_uint(buf[2],buf[3]);
haveGlobalColormap = BitSet(buf[4], LOCALCOLORMAP); /* Global Colormap */
if (haveGlobalColormap) {
if (ReadColorMap(fd, BitPixel, ColorMap)) {
return 0;
}
}
for (;;) {
int top, left;
int width, height;
if (! ReadOK(fd,&c,1)) {
return 0;
}
if (c == ';') { /* GIF terminator */
goto terminated;
}
if (c == '!') { /* Extension */
if (! ReadOK(fd,&c,1)) {
return 0;
}
DoExtension(fd, c, &Transparent, &ZeroDataBlock);
continue;
}
if (c != ',') { /* Not a valid start character */
continue;
}
/*1.4//++imageCount; */
if (! ReadOK(fd,buf,9)) {
return 0;
}
useGlobalColormap = ! BitSet(buf[8], LOCALCOLORMAP);
bitPixel = 1<<((buf[8]&0x07)+1);
left = LM_to_uint(buf[0], buf[1]);
top = LM_to_uint(buf[2], buf[3]);
width = LM_to_uint(buf[4], buf[5]);
height = LM_to_uint(buf[6], buf[7]);
if (left + width > screen_width || top + height > screen_height) {
if (VERBOSE) {
printf("Frame is not confined to screen dimension.\n");
}
return 0;
}
if (!(im = gdImageCreate(width, height))) {
return 0;
}
im->interlace = BitSet(buf[8], INTERLACE);
if (!useGlobalColormap) {
if (ReadColorMap(fd, bitPixel, localColorMap)) {
gdImageDestroy(im);
return 0;
}
ReadImage(im, fd, width, height, localColorMap,
BitSet(buf[8], INTERLACE), &ZeroDataBlock);
} else {
if (!haveGlobalColormap) {
gdImageDestroy(im);
return 0;
}
ReadImage(im, fd, width, height,
ColorMap,
BitSet(buf[8], INTERLACE), &ZeroDataBlock);
}
if (Transparent != (-1)) {
gdImageColorTransparent(im, Transparent);
}
goto terminated;
}
terminated:
/* Terminator before any image was declared! */
if (!im) {
return 0;
}
if (!im->colorsTotal) {
gdImageDestroy(im);
return 0;
}
/* Check for open colors at the end, so
we can reduce colorsTotal and ultimately
BitsPerPixel */
for (i=((im->colorsTotal-1)); (i>=0); i--) {
if (im->open[i]) {
im->colorsTotal--;
} else {
break;
}
}
return im;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'Fix #74435: Buffer over-read into uninitialized memory
The stack allocated color map buffers were not zeroed before usage, and
so undefined palette indexes could cause information leakage.'</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 Image *ReadDPXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
magick[4],
value[MagickPathExtent];
DPXInfo
dpx;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
offset;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
extent,
samples_per_pixel;
ssize_t
count,
n,
row,
y;
unsigned char
component_type;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read DPX file header.
*/
offset=0;
count=ReadBlob(image,4,(unsigned char *) magick);
offset+=count;
if ((count != 4) || ((LocaleNCompare(magick,"SDPX",4) != 0) &&
(LocaleNCompare((char *) magick,"XPDS",4) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->endian=LSBEndian;
if (LocaleNCompare(magick,"SDPX",4) == 0)
image->endian=MSBEndian;
(void) ResetMagickMemory(&dpx,0,sizeof(dpx));
dpx.file.image_offset=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(dpx.file.version),(unsigned char *)
dpx.file.version);
(void) FormatImageProperty(image,"dpx:file.version","%.8s",dpx.file.version);
dpx.file.file_size=ReadBlobLong(image);
offset+=4;
dpx.file.ditto_key=ReadBlobLong(image);
offset+=4;
if (dpx.file.ditto_key != ~0U)
(void) FormatImageProperty(image,"dpx:file.ditto.key","%u",
dpx.file.ditto_key);
dpx.file.generic_size=ReadBlobLong(image);
offset+=4;
dpx.file.industry_size=ReadBlobLong(image);
offset+=4;
dpx.file.user_size=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(dpx.file.filename),(unsigned char *)
dpx.file.filename);
(void) FormatImageProperty(image,"dpx:file.filename","%.100s",
dpx.file.filename);
(void) FormatImageProperty(image,"document","%.100s",dpx.file.filename);
offset+=ReadBlob(image,sizeof(dpx.file.timestamp),(unsigned char *)
dpx.file.timestamp);
if (*dpx.file.timestamp != '\0')
(void) FormatImageProperty(image,"dpx:file.timestamp","%.24s",
dpx.file.timestamp);
offset+=ReadBlob(image,sizeof(dpx.file.creator),(unsigned char *)
dpx.file.creator);
if (*dpx.file.creator != '\0')
{
(void) FormatImageProperty(image,"dpx:file.creator","%.100s",
dpx.file.creator);
(void) FormatImageProperty(image,"software","%.100s",dpx.file.creator);
}
offset+=ReadBlob(image,sizeof(dpx.file.project),(unsigned char *)
dpx.file.project);
if (*dpx.file.project != '\0')
{
(void) FormatImageProperty(image,"dpx:file.project","%.200s",
dpx.file.project);
(void) FormatImageProperty(image,"comment","%.100s",dpx.file.project);
}
offset+=ReadBlob(image,sizeof(dpx.file.copyright),(unsigned char *)
dpx.file.copyright);
if (*dpx.file.copyright != '\0')
{
(void) FormatImageProperty(image,"dpx:file.copyright","%.200s",
dpx.file.copyright);
(void) FormatImageProperty(image,"copyright","%.100s",
dpx.file.copyright);
}
dpx.file.encrypt_key=ReadBlobLong(image);
offset+=4;
if (dpx.file.encrypt_key != ~0U)
(void) FormatImageProperty(image,"dpx:file.encrypt_key","%u",
dpx.file.encrypt_key);
offset+=ReadBlob(image,sizeof(dpx.file.reserve),(unsigned char *)
dpx.file.reserve);
/*
Read DPX image header.
*/
dpx.image.orientation=ReadBlobShort(image);
if (dpx.image.orientation > 7)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
offset+=2;
if (dpx.image.orientation != (unsigned short) ~0)
(void) FormatImageProperty(image,"dpx:image.orientation","%d",
dpx.image.orientation);
switch (dpx.image.orientation)
{
default:
case 0: image->orientation=TopLeftOrientation; break;
case 1: image->orientation=TopRightOrientation; break;
case 2: image->orientation=BottomLeftOrientation; break;
case 3: image->orientation=BottomRightOrientation; break;
case 4: image->orientation=LeftTopOrientation; break;
case 5: image->orientation=RightTopOrientation; break;
case 6: image->orientation=LeftBottomOrientation; break;
case 7: image->orientation=RightBottomOrientation; break;
}
dpx.image.number_elements=ReadBlobShort(image);
if (dpx.image.number_elements > MaxNumberImageElements)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
offset+=2;
dpx.image.pixels_per_line=ReadBlobLong(image);
offset+=4;
image->columns=dpx.image.pixels_per_line;
dpx.image.lines_per_element=ReadBlobLong(image);
offset+=4;
image->rows=dpx.image.lines_per_element;
for (i=0; i < 8; i++)
{
char
property[MagickPathExtent];
dpx.image.image_element[i].data_sign=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].low_data=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].low_quantity=ReadBlobFloat(image);
offset+=4;
dpx.image.image_element[i].high_data=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].high_quantity=ReadBlobFloat(image);
offset+=4;
dpx.image.image_element[i].descriptor=(unsigned char) ReadBlobByte(image);
offset++;
dpx.image.image_element[i].transfer_characteristic=(unsigned char)
ReadBlobByte(image);
(void) FormatLocaleString(property,MagickPathExtent,
"dpx:image.element[%lu].transfer-characteristic",(long) i);
(void) FormatImageProperty(image,property,"%s",
GetImageTransferCharacteristic((DPXTransferCharacteristic)
dpx.image.image_element[i].transfer_characteristic));
offset++;
dpx.image.image_element[i].colorimetric=(unsigned char) ReadBlobByte(image);
offset++;
dpx.image.image_element[i].bit_size=(unsigned char) ReadBlobByte(image);
offset++;
dpx.image.image_element[i].packing=ReadBlobShort(image);
offset+=2;
dpx.image.image_element[i].encoding=ReadBlobShort(image);
offset+=2;
dpx.image.image_element[i].data_offset=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].end_of_line_padding=ReadBlobLong(image);
offset+=4;
dpx.image.image_element[i].end_of_image_padding=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(dpx.image.image_element[i].description),
(unsigned char *) dpx.image.image_element[i].description);
}
SetImageColorspace(image,RGBColorspace,exception);
offset+=ReadBlob(image,sizeof(dpx.image.reserve),(unsigned char *)
dpx.image.reserve);
if (dpx.file.image_offset >= 1664U)
{
/*
Read DPX orientation header.
*/
dpx.orientation.x_offset=ReadBlobLong(image);
offset+=4;
if (dpx.orientation.x_offset != ~0U)
(void) FormatImageProperty(image,"dpx:orientation.x_offset","%u",
dpx.orientation.x_offset);
dpx.orientation.y_offset=ReadBlobLong(image);
offset+=4;
if (dpx.orientation.y_offset != ~0U)
(void) FormatImageProperty(image,"dpx:orientation.y_offset","%u",
dpx.orientation.y_offset);
dpx.orientation.x_center=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.orientation.x_center) != MagickFalse)
(void) FormatImageProperty(image,"dpx:orientation.x_center","%g",
dpx.orientation.x_center);
dpx.orientation.y_center=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.orientation.y_center) != MagickFalse)
(void) FormatImageProperty(image,"dpx:orientation.y_center","%g",
dpx.orientation.y_center);
dpx.orientation.x_size=ReadBlobLong(image);
offset+=4;
if (dpx.orientation.x_size != ~0U)
(void) FormatImageProperty(image,"dpx:orientation.x_size","%u",
dpx.orientation.x_size);
dpx.orientation.y_size=ReadBlobLong(image);
offset+=4;
if (dpx.orientation.y_size != ~0U)
(void) FormatImageProperty(image,"dpx:orientation.y_size","%u",
dpx.orientation.y_size);
offset+=ReadBlob(image,sizeof(dpx.orientation.filename),(unsigned char *)
dpx.orientation.filename);
if (*dpx.orientation.filename != '\0')
(void) FormatImageProperty(image,"dpx:orientation.filename","%.100s",
dpx.orientation.filename);
offset+=ReadBlob(image,sizeof(dpx.orientation.timestamp),(unsigned char *)
dpx.orientation.timestamp);
if (*dpx.orientation.timestamp != '\0')
(void) FormatImageProperty(image,"dpx:orientation.timestamp","%.24s",
dpx.orientation.timestamp);
offset+=ReadBlob(image,sizeof(dpx.orientation.device),(unsigned char *)
dpx.orientation.device);
if (*dpx.orientation.device != '\0')
(void) FormatImageProperty(image,"dpx:orientation.device","%.32s",
dpx.orientation.device);
offset+=ReadBlob(image,sizeof(dpx.orientation.serial),(unsigned char *)
dpx.orientation.serial);
if (*dpx.orientation.serial != '\0')
(void) FormatImageProperty(image,"dpx:orientation.serial","%.32s",
dpx.orientation.serial);
for (i=0; i < 4; i++)
{
dpx.orientation.border[i]=ReadBlobShort(image);
offset+=2;
}
if ((dpx.orientation.border[0] != (unsigned short) (~0)) &&
(dpx.orientation.border[1] != (unsigned short) (~0)))
(void) FormatImageProperty(image,"dpx:orientation.border","%dx%d%+d%+d",
dpx.orientation.border[0],dpx.orientation.border[1],
dpx.orientation.border[2],dpx.orientation.border[3]);
for (i=0; i < 2; i++)
{
dpx.orientation.aspect_ratio[i]=ReadBlobLong(image);
offset+=4;
}
if ((dpx.orientation.aspect_ratio[0] != ~0U) &&
(dpx.orientation.aspect_ratio[1] != ~0U))
(void) FormatImageProperty(image,"dpx:orientation.aspect_ratio",
"%ux%u",dpx.orientation.aspect_ratio[0],
dpx.orientation.aspect_ratio[1]);
offset+=ReadBlob(image,sizeof(dpx.orientation.reserve),(unsigned char *)
dpx.orientation.reserve);
}
if (dpx.file.image_offset >= 1920U)
{
/*
Read DPX film header.
*/
offset+=ReadBlob(image,sizeof(dpx.film.id),(unsigned char *) dpx.film.id);
if (*dpx.film.id != '\0')
(void) FormatImageProperty(image,"dpx:film.id","%.2s",dpx.film.id);
offset+=ReadBlob(image,sizeof(dpx.film.type),(unsigned char *)
dpx.film.type);
if (*dpx.film.type != '\0')
(void) FormatImageProperty(image,"dpx:film.type","%.2s",dpx.film.type);
offset+=ReadBlob(image,sizeof(dpx.film.offset),(unsigned char *)
dpx.film.offset);
if (*dpx.film.offset != '\0')
(void) FormatImageProperty(image,"dpx:film.offset","%.2s",
dpx.film.offset);
offset+=ReadBlob(image,sizeof(dpx.film.prefix),(unsigned char *)
dpx.film.prefix);
if (*dpx.film.prefix != '\0')
(void) FormatImageProperty(image,"dpx:film.prefix","%.6s",
dpx.film.prefix);
offset+=ReadBlob(image,sizeof(dpx.film.count),(unsigned char *)
dpx.film.count);
if (*dpx.film.count != '\0')
(void) FormatImageProperty(image,"dpx:film.count","%.4s",
dpx.film.count);
offset+=ReadBlob(image,sizeof(dpx.film.format),(unsigned char *)
dpx.film.format);
if (*dpx.film.format != '\0')
(void) FormatImageProperty(image,"dpx:film.format","%.4s",
dpx.film.format);
dpx.film.frame_position=ReadBlobLong(image);
offset+=4;
if (dpx.film.frame_position != ~0U)
(void) FormatImageProperty(image,"dpx:film.frame_position","%u",
dpx.film.frame_position);
dpx.film.sequence_extent=ReadBlobLong(image);
offset+=4;
if (dpx.film.sequence_extent != ~0U)
(void) FormatImageProperty(image,"dpx:film.sequence_extent","%u",
dpx.film.sequence_extent);
dpx.film.held_count=ReadBlobLong(image);
offset+=4;
if (dpx.film.held_count != ~0U)
(void) FormatImageProperty(image,"dpx:film.held_count","%u",
dpx.film.held_count);
dpx.film.frame_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.film.frame_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:film.frame_rate","%g",
dpx.film.frame_rate);
dpx.film.shutter_angle=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.film.shutter_angle) != MagickFalse)
(void) FormatImageProperty(image,"dpx:film.shutter_angle","%g",
dpx.film.shutter_angle);
offset+=ReadBlob(image,sizeof(dpx.film.frame_id),(unsigned char *)
dpx.film.frame_id);
if (*dpx.film.frame_id != '\0')
(void) FormatImageProperty(image,"dpx:film.frame_id","%.32s",
dpx.film.frame_id);
offset+=ReadBlob(image,sizeof(dpx.film.slate),(unsigned char *)
dpx.film.slate);
if (*dpx.film.slate != '\0')
(void) FormatImageProperty(image,"dpx:film.slate","%.100s",
dpx.film.slate);
offset+=ReadBlob(image,sizeof(dpx.film.reserve),(unsigned char *)
dpx.film.reserve);
}
if (dpx.file.image_offset >= 2048U)
{
/*
Read DPX television header.
*/
dpx.television.time_code=(unsigned int) ReadBlobLong(image);
offset+=4;
TimeCodeToString(dpx.television.time_code,value);
(void) SetImageProperty(image,"dpx:television.time.code",value,exception);
dpx.television.user_bits=(unsigned int) ReadBlobLong(image);
offset+=4;
TimeCodeToString(dpx.television.user_bits,value);
(void) SetImageProperty(image,"dpx:television.user.bits",value,exception);
dpx.television.interlace=(unsigned char) ReadBlobByte(image);
offset++;
if (dpx.television.interlace != 0)
(void) FormatImageProperty(image,"dpx:television.interlace","%.20g",
(double) dpx.television.interlace);
dpx.television.field_number=(unsigned char) ReadBlobByte(image);
offset++;
if (dpx.television.field_number != 0)
(void) FormatImageProperty(image,"dpx:television.field_number","%.20g",
(double) dpx.television.field_number);
dpx.television.video_signal=(unsigned char) ReadBlobByte(image);
offset++;
if (dpx.television.video_signal != 0)
(void) FormatImageProperty(image,"dpx:television.video_signal","%.20g",
(double) dpx.television.video_signal);
dpx.television.padding=(unsigned char) ReadBlobByte(image);
offset++;
if (dpx.television.padding != 0)
(void) FormatImageProperty(image,"dpx:television.padding","%d",
dpx.television.padding);
dpx.television.horizontal_sample_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.horizontal_sample_rate) != MagickFalse)
(void) FormatImageProperty(image,
"dpx:television.horizontal_sample_rate","%g",
dpx.television.horizontal_sample_rate);
dpx.television.vertical_sample_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.vertical_sample_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.vertical_sample_rate",
"%g",dpx.television.vertical_sample_rate);
dpx.television.frame_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.frame_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.frame_rate","%g",
dpx.television.frame_rate);
dpx.television.time_offset=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.time_offset) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.time_offset","%g",
dpx.television.time_offset);
dpx.television.gamma=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.gamma) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.gamma","%g",
dpx.television.gamma);
dpx.television.black_level=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.black_level) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.black_level","%g",
dpx.television.black_level);
dpx.television.black_gain=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.black_gain) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.black_gain","%g",
dpx.television.black_gain);
dpx.television.break_point=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.break_point) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.break_point","%g",
dpx.television.break_point);
dpx.television.white_level=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.white_level) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.white_level","%g",
dpx.television.white_level);
dpx.television.integration_times=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(dpx.television.integration_times) != MagickFalse)
(void) FormatImageProperty(image,"dpx:television.integration_times",
"%g",dpx.television.integration_times);
offset+=ReadBlob(image,sizeof(dpx.television.reserve),(unsigned char *)
dpx.television.reserve);
}
if (dpx.file.image_offset > 2080U)
{
/*
Read DPX user header.
*/
offset+=ReadBlob(image,sizeof(dpx.user.id),(unsigned char *) dpx.user.id);
if (*dpx.user.id != '\0')
(void) FormatImageProperty(image,"dpx:user.id","%.32s",dpx.user.id);
if ((dpx.file.user_size != ~0U) &&
((size_t) dpx.file.user_size > sizeof(dpx.user.id)))
{
StringInfo
*profile;
profile=BlobToStringInfo((const unsigned char *) NULL,
dpx.file.user_size-sizeof(dpx.user.id));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
offset+=ReadBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) SetImageProfile(image,"dpx:user-data",profile,exception);
profile=DestroyStringInfo(profile);
}
}
for ( ; offset < (MagickOffsetType) dpx.file.image_offset; offset++)
(void) ReadBlobByte(image);
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
for (n=0; n < (ssize_t) dpx.image.number_elements; n++)
{
/*
Convert DPX raster image to pixel packets.
*/
if ((dpx.image.image_element[n].data_offset != ~0U) &&
(dpx.image.image_element[n].data_offset != 0U))
{
MagickOffsetType
data_offset;
data_offset=(MagickOffsetType) dpx.image.image_element[n].data_offset;
if (data_offset < offset)
offset=SeekBlob(image,data_offset,SEEK_SET);
else
for ( ; offset < data_offset; offset++)
(void) ReadBlobByte(image);
if (offset != data_offset)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
SetPrimaryChromaticity((DPXColorimetric)
dpx.image.image_element[n].colorimetric,&image->chromaticity);
image->depth=dpx.image.image_element[n].bit_size;
samples_per_pixel=1;
quantum_type=GrayQuantum;
component_type=dpx.image.image_element[n].descriptor;
switch (component_type)
{
case CbYCrY422ComponentType:
{
samples_per_pixel=2;
quantum_type=CbYCrYQuantum;
break;
}
case CbYACrYA4224ComponentType:
case CbYCr444ComponentType:
{
samples_per_pixel=3;
quantum_type=CbYCrQuantum;
break;
}
case RGBComponentType:
{
samples_per_pixel=3;
quantum_type=RGBQuantum;
break;
}
case ABGRComponentType:
case RGBAComponentType:
{
image->alpha_trait=BlendPixelTrait;
samples_per_pixel=4;
quantum_type=RGBAQuantum;
break;
}
default:
break;
}
switch (component_type)
{
case CbYCrY422ComponentType:
case CbYACrYA4224ComponentType:
case CbYCr444ComponentType:
{
SetImageColorspace(image,Rec709YCbCrColorspace,exception);
break;
}
case LumaComponentType:
{
SetImageColorspace(image,GRAYColorspace,exception);
break;
}
default:
{
SetImageColorspace(image,sRGBColorspace,exception);
if (dpx.image.image_element[n].transfer_characteristic == LogarithmicColorimetric)
SetImageColorspace(image,LogColorspace,exception);
if (dpx.image.image_element[n].transfer_characteristic == PrintingDensityColorimetric)
SetImageColorspace(image,LogColorspace,exception);
break;
}
}
extent=GetBytesPerRow(image->columns,samples_per_pixel,image->depth,
dpx.image.image_element[n].packing == 0 ? MagickFalse : MagickTrue);
/*
DPX any-bit pixel format.
*/
status=MagickTrue;
row=0;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumQuantum(quantum_info,32);
SetQuantumPack(quantum_info,dpx.image.image_element[n].packing == 0 ?
MagickTrue : MagickFalse);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register Quantum
*q;
size_t
length;
ssize_t
offset;
if (status == MagickFalse)
continue;
pixels=(const unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if (count != (ssize_t) extent)
status=MagickFalse;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(image->previous == (Image *) NULL))
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
offset=row++;
q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) length;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
SetQuantumImageType(image,quantum_type);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
if ((i+1) < (ssize_t) dpx.image.number_elements)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-834'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/509'</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: ModuleExport size_t RegisterRLEImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("RLE","RLE","Utah Run length encoded image");
entry->decoder=(DecodeImageHandler *) ReadRLEImage;
entry->magick=(IsImageFormatHandler *) IsRLE;
entry->flags^=CoderAdjoinFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-834'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/518'</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 Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MagickPathExtent],
text[MagickPathExtent];
Image
*image;
long
x_offset,
y_offset;
PixelInfo
pixel;
MagickBooleanType
status;
QuantumAny
range;
register ssize_t
i,
x;
register Quantum
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->alpha_trait=UndefinedPixelTrait;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->alpha_trait=BlendPixelTrait;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) SetImageBackgroundColor(image,exception);
(void) SetImageColorspace(image,(ColorspaceType) type,exception);
GetPixelInfo(image,&pixel);
range=GetQuantumRange(image->depth);
for (y=0; y < (ssize_t) image->rows; y++)
{
double
alpha,
black,
blue,
green,
red;
red=0.0;
green=0.0;
blue=0.0;
black=0.0;
alpha=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
break;
switch (image->colorspace)
{
case GRAYColorspace:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&alpha);
green=red;
blue=red;
break;
}
count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,
&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&black,&alpha);
break;
}
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&black);
break;
}
default:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&alpha);
break;
}
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
black*=0.01*range;
alpha*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.black=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (black+0.5),
range);
pixel.alpha=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (alpha+0.5),
range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (Quantum *) NULL)
continue;
SetPixelViaPixelInfo(image,&pixel,q);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/591'</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 xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
struct xfrm_migrate *m, int num_migrate,
struct xfrm_kmaddress *k, struct net *net,
struct xfrm_encap_tmpl *encap)
{
int i, err, nx_cur = 0, nx_new = 0;
struct xfrm_policy *pol = NULL;
struct xfrm_state *x, *xc;
struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
struct xfrm_state *x_new[XFRM_MAX_DEPTH];
struct xfrm_migrate *mp;
if ((err = xfrm_migrate_check(m, num_migrate)) < 0)
goto out;
/* Stage 1 - find policy */
if ((pol = xfrm_migrate_policy_find(sel, dir, type, net)) == NULL) {
err = -ENOENT;
goto out;
}
/* Stage 2 - find and update state(s) */
for (i = 0, mp = m; i < num_migrate; i++, mp++) {
if ((x = xfrm_migrate_state_find(mp, net))) {
x_cur[nx_cur] = x;
nx_cur++;
xc = xfrm_state_migrate(x, mp, encap);
if (xc) {
x_new[nx_new] = xc;
nx_new++;
} else {
err = -ENODATA;
goto restore_state;
}
}
}
/* Stage 3 - update policy */
if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)
goto restore_state;
/* Stage 4 - delete old state(s) */
if (nx_cur) {
xfrm_states_put(x_cur, nx_cur);
xfrm_states_delete(x_cur, nx_cur);
}
/* Stage 5 - announce */
km_migrate(sel, dir, type, m, num_migrate, k, encap);
xfrm_pol_put(pol);
return 0;
out:
return err;
restore_state:
if (pol)
xfrm_pol_put(pol);
if (nx_cur)
xfrm_states_put(x_cur, nx_cur);
if (nx_new)
xfrm_states_delete(x_new, nx_new);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'xfrm: policy: check policy direction value
The 'dir' parameter in xfrm_migrate() is a user-controlled byte which is used
as an array index. This can lead to an out-of-bound access, kernel lockup and
DoS. Add a check for the 'dir' value.
This fixes CVE-2017-11600.
References: https://bugzilla.redhat.com/show_bug.cgi?id=1474928
Fixes: 80c9abaabf42 ("[XFRM]: Extension for dynamic update of endpoint address(es)")
Cc: <[email protected]> # v2.6.21-rc1
Reported-by: "bo Zhang" <[email protected]>
Signed-off-by: Vladis Dronov <[email protected]>
Signed-off-by: Steffen Klassert <[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 MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
Image
*images,
*next,
*pyramid_image;
ImageInfo
*write_info;
MagickBooleanType
status;
PointInfo
resolution;
size_t
columns,
rows;
/*
Create pyramid-encoded TIFF image.
*/
images=NewImageList();
for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
{
Image
*clone_image;
clone_image=CloneImage(next,0,0,MagickFalse,exception);
if (clone_image == (Image *) NULL)
break;
clone_image->previous=NewImageList();
clone_image->next=NewImageList();
(void) SetImageProperty(clone_image,"tiff:subfiletype","none",exception);
AppendImageToList(&images,clone_image);
columns=next->columns;
rows=next->rows;
resolution=next->resolution;
while ((columns > 64) && (rows > 64))
{
columns/=2;
rows/=2;
resolution.x/=2;
resolution.y/=2;
pyramid_image=ResizeImage(next,columns,rows,image->filter,exception);
if (pyramid_image == (Image *) NULL)
break;
pyramid_image->resolution=resolution;
(void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE",
exception);
AppendImageToList(&images,pyramid_image);
}
}
images=GetFirstImageInList(images);
/*
Write pyramid-encoded TIFF image.
*/
write_info=CloneImageInfo(image_info);
write_info->adjoin=MagickTrue;
(void) CopyMagickString(write_info->magick,"TIFF",MagickPathExtent);
(void) CopyMagickString(images->magick,"TIFF",MagickPathExtent);
status=WriteTIFFImage(write_info,images,exception);
images=DestroyImageList(images);
write_info=DestroyImageInfo(write_info);
return(status);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/584'</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 MagickBooleanType WriteCIPImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent];
const char
*value;
MagickBooleanType
status;
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
unsigned char
byte;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
(void) WriteBlobString(image,"<CiscoIPPhoneImage>\n");
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
(void) FormatLocaleString(buffer,MagickPathExtent,"<Title>%s</Title>\n",value);
else
{
char
basename[MagickPathExtent];
GetPathComponent(image->filename,BasePath,basename);
(void) FormatLocaleString(buffer,MagickPathExtent,"<Title>%s</Title>\n",
basename);
}
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"<LocationX>%.20g</LocationX>\n",(double) image->page.x);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"<LocationY>%.20g</LocationY>\n",(double) image->page.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"<Width>%.20g</Width>\n",
(double) (image->columns+(image->columns % 2)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"<Height>%.20g</Height>\n",
(double) image->rows);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,"<Depth>2</Depth>\n");
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,"<Data>");
(void) TransformImageColorspace(image,sRGBColorspace,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-3); x+=4)
{
byte=(unsigned char)
((((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+3*GetPixelChannels(image)))/QuantumRange) & 0x03) << 6) |
(((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+2*GetPixelChannels(image)))/QuantumRange) & 0x03) << 4) |
(((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+1*GetPixelChannels(image)))/QuantumRange) & 0x03) << 2) |
(((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+0*GetPixelChannels(image)))/QuantumRange) & 0x03) << 0));
(void) FormatLocaleString(buffer,MagickPathExtent,"%02x",byte);
(void) WriteBlobString(image,buffer);
p+=GetPixelChannels(image);
}
if ((image->columns % 4) != 0)
{
i=(ssize_t) image->columns % 4;
byte=(unsigned char)
((((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+MagickMin(i,3)*GetPixelChannels(image)))/QuantumRange) & 0x03) << 6) |
(((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+MagickMin(i,2)*GetPixelChannels(image)))/QuantumRange) & 0x03) << 4) |
(((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+MagickMin(i,1)*GetPixelChannels(image)))/QuantumRange) & 0x03) << 2) |
(((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+MagickMin(i,0)*GetPixelChannels(image)))/QuantumRange) & 0x03) << 0));
(void) FormatLocaleString(buffer,MagickPathExtent,"%02x",~byte);
(void) WriteBlobString(image,buffer);
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) WriteBlobString(image,"</Data>\n");
(void) WriteBlobString(image,"</CiscoIPPhoneImage>\n");
(void) CloseBlob(image);
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/588'</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: QPDF::resolve(int objid, int generation)
{
// Check object cache before checking xref table. This allows us
// to insert things into the object cache that don't actually
// exist in the file.
QPDFObjGen og(objid, generation);
if (! this->obj_cache.count(og))
{
if (! this->xref_table.count(og))
{
// PDF spec says unknown objects resolve to the null object.
return new QPDF_Null;
}
QPDFXRefEntry const& entry = this->xref_table[og];
switch (entry.getType())
{
case 1:
{
qpdf_offset_t offset = entry.getOffset();
// Object stored in cache by readObjectAtOffset
int aobjid;
int ageneration;
QPDFObjectHandle oh =
readObjectAtOffset(true, offset, "", objid, generation,
aobjid, ageneration);
}
break;
case 2:
resolveObjectsInStream(entry.getObjStreamNumber());
break;
default:
throw QPDFExc(qpdf_e_damaged_pdf, this->file->getName(), "", 0,
"object " +
QUtil::int_to_string(objid) + "/" +
QUtil::int_to_string(generation) +
" has unexpected xref entry type");
}
}
return this->obj_cache[og].object;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399', 'CWE-835'], 'message': 'Detect recursion loops resolving objects (fixes #51)
During parsing of an object, sometimes parts of the object have to be
resolved. An example is stream lengths. If such an object directly or
indirectly points to the object being parsed, it can cause an infinite
loop. Guard against all cases of re-entrant resolution of objects.'</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: QPDF::readObjectAtOffset(bool try_recovery,
qpdf_offset_t offset, std::string const& description,
int exp_objid, int exp_generation,
int& objid, int& generation)
{
setLastObjectDescription(description, exp_objid, exp_generation);
// Special case: if offset is 0, just return null. Some PDF
// writers, in particular "Mac OS X 10.7.5 Quartz PDFContext", may
// store deleted objects in the xref table as "0000000000 00000
// n", which is not correct, but it won't hurt anything for to
// ignore these.
if (offset == 0)
{
QTC::TC("qpdf", "QPDF bogus 0 offset", 0);
warn(QPDFExc(qpdf_e_damaged_pdf, this->file->getName(),
this->last_object_description, 0,
"object has offset 0"));
return QPDFObjectHandle::newNull();
}
this->file->seek(offset, SEEK_SET);
QPDFTokenizer::Token tobjid = readToken(this->file);
QPDFTokenizer::Token tgen = readToken(this->file);
QPDFTokenizer::Token tobj = readToken(this->file);
bool objidok = (tobjid.getType() == QPDFTokenizer::tt_integer);
int genok = (tgen.getType() == QPDFTokenizer::tt_integer);
int objok = (tobj == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "obj"));
QTC::TC("qpdf", "QPDF check objid", objidok ? 1 : 0);
QTC::TC("qpdf", "QPDF check generation", genok ? 1 : 0);
QTC::TC("qpdf", "QPDF check obj", objok ? 1 : 0);
try
{
if (! (objidok && genok && objok))
{
QTC::TC("qpdf", "QPDF expected n n obj");
throw QPDFExc(qpdf_e_damaged_pdf, this->file->getName(),
this->last_object_description, offset,
"expected n n obj");
}
objid = atoi(tobjid.getValue().c_str());
generation = atoi(tgen.getValue().c_str());
if ((exp_objid >= 0) &&
(! ((objid == exp_objid) && (generation == exp_generation))))
{
QTC::TC("qpdf", "QPDF err wrong objid/generation");
throw QPDFExc(qpdf_e_damaged_pdf, this->file->getName(),
this->last_object_description, offset,
std::string("expected ") +
QUtil::int_to_string(exp_objid) + " " +
QUtil::int_to_string(exp_generation) + " obj");
}
}
catch (QPDFExc& e)
{
if ((exp_objid >= 0) && try_recovery && this->attempt_recovery)
{
// Try again after reconstructing xref table
reconstruct_xref(e);
QPDFObjGen og(exp_objid, exp_generation);
if (this->xref_table.count(og) &&
(this->xref_table[og].getType() == 1))
{
qpdf_offset_t new_offset = this->xref_table[og].getOffset();
QPDFObjectHandle result = readObjectAtOffset(
false, new_offset, description,
exp_objid, exp_generation, objid, generation);
QTC::TC("qpdf", "QPDF recovered in readObjectAtOffset");
return result;
}
else
{
QTC::TC("qpdf", "QPDF object gone after xref reconstruction");
warn(QPDFExc(
qpdf_e_damaged_pdf, this->file->getName(),
"", 0,
std::string(
"object " +
QUtil::int_to_string(exp_objid) +
" " +
QUtil::int_to_string(exp_generation) +
" not found in file after regenerating"
" cross reference table")));
return QPDFObjectHandle::newNull();
}
}
else
{
throw e;
}
}
QPDFObjectHandle oh = readObject(
this->file, description, objid, generation, false);
if (! (readToken(this->file) ==
QPDFTokenizer::Token(QPDFTokenizer::tt_word, "endobj")))
{
QTC::TC("qpdf", "QPDF err expected endobj");
warn(QPDFExc(qpdf_e_damaged_pdf, this->file->getName(),
this->last_object_description, this->file->getLastOffset(),
"expected endobj"));
}
QPDFObjGen og(objid, generation);
if (! this->obj_cache.count(og))
{
// Store the object in the cache here so it gets cached
// whether we first know the offset or whether we first know
// the object ID and generation (in which we case we would get
// here through resolve).
// Determine the end offset of this object before and after
// white space. We use these numbers to validate
// linearization hint tables. Offsets and lengths of objects
// may imply the end of an object to be anywhere between these
// values.
qpdf_offset_t end_before_space = this->file->tell();
// skip over spaces
while (true)
{
char ch;
if (this->file->read(&ch, 1))
{
if (! isspace(static_cast<unsigned char>(ch)))
{
this->file->seek(-1, SEEK_CUR);
break;
}
}
else
{
throw QPDFExc(qpdf_e_damaged_pdf, this->file->getName(),
this->last_object_description, offset,
"EOF after endobj");
}
}
qpdf_offset_t end_after_space = this->file->tell();
this->obj_cache[og] =
ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh),
end_before_space, end_after_space);
}
return oh;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': 'Handle object ID 0 (fixes #99)
This is CVE-2017-9208.
The QPDF library uses object ID 0 internally as a sentinel to
represent a direct object, but prior to this fix, was not blocking
handling of 0 0 obj or 0 0 R as a special case. Creating an object in
the file with 0 0 obj could cause various infinite loops. The PDF spec
doesn't allow for object 0. Having qpdf handle object 0 might be a
better fix, but changing all the places in the code that assumes objid
== 0 means direct would be risky.'</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: QPDF::QPDF() :
encrypted(false),
encryption_initialized(false),
ignore_xref_streams(false),
suppress_warnings(false),
out_stream(&std::cout),
err_stream(&std::cerr),
attempt_recovery(true),
encryption_V(0),
encryption_R(0),
encrypt_metadata(true),
cf_stream(e_none),
cf_string(e_none),
cf_file(e_none),
cached_key_objid(0),
cached_key_generation(0),
pushed_inherited_attributes_to_pages(false),
copied_stream_data_provider(0),
first_xref_item_offset(0),
uncompressed_after_compressed(false)
{
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-835'], 'message': 'Avoid xref reconstruction infinite loop (fixes #100)
This is CVE-2017-9209.'</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: xps_load_sfnt_name(xps_font_t *font, char *namep)
{
byte *namedata;
int offset, length;
/*int format;*/
int count, stringoffset;
int found;
int i, k;
found = 0;
strcpy(namep, "Unknown");
offset = xps_find_sfnt_table(font, "name", &length);
if (offset < 0 || length < 6)
{
gs_warn("cannot find name table");
return;
}
namedata = font->data + offset;
/*format = u16(namedata + 0);*/
count = u16(namedata + 2);
stringoffset = u16(namedata + 4);
if (length < 6 + (count * 12))
{
gs_warn("name table too short");
return;
}
for (i = 0; i < count; i++)
{
byte *record = namedata + 6 + i * 12;
int pid = u16(record + 0);
int eid = u16(record + 2);
int langid = u16(record + 4);
int nameid = u16(record + 6);
length = u16(record + 8);
offset = u16(record + 10);
/* Full font name or postscript name */
if (nameid == 4 || nameid == 6)
{
if (pid == 1 && eid == 0 && langid == 0) /* mac roman, english */
{
if (found < 3)
{
memcpy(namep, namedata + stringoffset + offset, length);
namep[length] = 0;
found = 3;
}
}
if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */
{
if (found < 2)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 2;
for (k = 0; k < n; k ++)
{
int c = u16(s + k * 2);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 2;
}
}
if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */
{
if (found < 1)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 4;
for (k = 0; k < n; k ++)
{
int c = u32(s + k * 4);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 1;
}
}
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Bug 698025: validate offsets reading TTF name table in xps'</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 Ins_IP( INS_ARG )
{
TT_F26Dot6 org_a, org_b, org_x,
cur_a, cur_b, cur_x,
distance;
Int point;
(void)args;
if ( CUR.top < CUR.GS.loop )
{
CUR.error = TT_Err_Invalid_Reference;
return;
}
org_a = CUR_Func_dualproj( CUR.zp0.org_x[CUR.GS.rp1],
CUR.zp0.org_y[CUR.GS.rp1] );
org_b = CUR_Func_dualproj( CUR.zp1.org_x[CUR.GS.rp2],
CUR.zp1.org_y[CUR.GS.rp2] );
cur_a = CUR_Func_project( CUR.zp0.cur_x[CUR.GS.rp1],
CUR.zp0.cur_y[CUR.GS.rp1] );
cur_b = CUR_Func_project( CUR.zp1.cur_x[CUR.GS.rp2],
CUR.zp1.cur_y[CUR.GS.rp2] );
while ( CUR.GS.loop > 0 )
{
CUR.args--;
point = (Int)CUR.stack[CUR.args];
if ( BOUNDS( point, CUR.zp2.n_points ) )
{
CUR.error = TT_Err_Invalid_Reference;
return;
}
org_x = CUR_Func_dualproj( CUR.zp2.org_x[point],
CUR.zp2.org_y[point] );
cur_x = CUR_Func_project( CUR.zp2.cur_x[point],
CUR.zp2.cur_y[point] );
if ( ( org_a <= org_b && org_x <= org_a ) ||
( org_a > org_b && org_x >= org_a ) )
distance = ( cur_a - org_a ) + ( org_x - cur_x );
else if ( ( org_a <= org_b && org_x >= org_b ) ||
( org_a > org_b && org_x < org_b ) )
distance = ( cur_b - org_b ) + ( org_x - cur_x );
else
/* note: it seems that rounding this value isn't a good */
/* idea (cf. width of capital 'S' in Times) */
distance = MulDiv_Round( cur_b - cur_a,
org_x - org_a,
org_b - org_a ) + ( cur_a - cur_x );
CUR_Func_move( &CUR.zp2, point, distance );
CUR.GS.loop--;
}
CUR.GS.loop = 1;
CUR.new_top = CUR.args;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Bug 698026: bounds check zone pointers in Ins_IP()'</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: xps_load_sfnt_name(xps_font_t *font, char *namep)
{
byte *namedata;
int offset, length;
/*int format;*/
int count, stringoffset;
int found;
int i, k;
found = 0;
strcpy(namep, "Unknown");
offset = xps_find_sfnt_table(font, "name", &length);
if (offset < 0 || length < 6)
{
gs_warn("cannot find name table");
return;
}
/* validate the offset, and the data for the two
* values we're about to read
*/
if (offset + 6 > font->length)
{
gs_warn("name table byte offset invalid");
return;
}
namedata = font->data + offset;
/*format = u16(namedata + 0);*/
count = u16(namedata + 2);
stringoffset = u16(namedata + 4);
if (stringoffset + offset > font->length
|| offset + 6 + count * 12 > font->length)
{
gs_warn("name table invalid");
return;
}
if (length < 6 + (count * 12))
{
gs_warn("name table too short");
return;
}
for (i = 0; i < count; i++)
{
byte *record = namedata + 6 + i * 12;
int pid = u16(record + 0);
int eid = u16(record + 2);
int langid = u16(record + 4);
int nameid = u16(record + 6);
length = u16(record + 8);
offset = u16(record + 10);
/* Full font name or postscript name */
if (nameid == 4 || nameid == 6)
{
if (pid == 1 && eid == 0 && langid == 0) /* mac roman, english */
{
if (found < 3)
{
memcpy(namep, namedata + stringoffset + offset, length);
namep[length] = 0;
found = 3;
}
}
if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */
{
if (found < 2)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 2;
for (k = 0; k < n; k ++)
{
int c = u16(s + k * 2);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 2;
}
}
if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */
{
if (found < 1)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 4;
for (k = 0; k < n; k ++)
{
int c = u32(s + k * 4);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 1;
}
}
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Bug 698044: restrict font name length to the buffer size.'</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: xps_select_best_font_encoding(xps_font_t *font)
{
static struct { int pid, eid; } xps_cmap_list[] =
{
{ 3, 10 }, /* Unicode with surrogates */
{ 3, 1 }, /* Unicode without surrogates */
{ 3, 5 }, /* Wansung */
{ 3, 4 }, /* Big5 */
{ 3, 3 }, /* Prc */
{ 3, 2 }, /* ShiftJis */
{ 3, 0 }, /* Symbol */
{ 1, 0 },
{ -1, -1 },
};
int i, k, n, pid, eid;
n = xps_count_font_encodings(font);
for (k = 0; xps_cmap_list[k].pid != -1; k++)
{
for (i = 0; i < n; i++)
{
xps_identify_font_encoding(font, i, &pid, &eid);
if (pid == xps_cmap_list[k].pid && eid == xps_cmap_list[k].eid)
{
xps_select_font_encoding(font, i);
return;
}
}
}
gs_warn("could not find a suitable cmap");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Bug 698050: xps: bounds check offset for requested cmap table'</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 Ins_MDRP( INS_ARG )
{
Int point;
TT_F26Dot6 distance,
org_dist;
point = (Int)args[0];
if ( BOUNDS( args[0], CUR.zp1.n_points ) )
{
/* Current version of FreeType silently ignores this out of bounds error
* and drops the instruction, see bug #691121
CUR.error = TT_Err_Invalid_Reference; */
return;
}
/* XXX: Is there some undocumented feature while in the */
/* twilight zone? */
org_dist = CUR_Func_dualproj( CUR.zp1.org_x[point] -
CUR.zp0.org_x[CUR.GS.rp0],
CUR.zp1.org_y[point] -
CUR.zp0.org_y[CUR.GS.rp0] );
/* single width cutin test */
if ( ABS(org_dist) < CUR.GS.single_width_cutin )
{
if ( org_dist >= 0 )
org_dist = CUR.GS.single_width_value;
else
org_dist = -CUR.GS.single_width_value;
}
/* round flag */
if ( (CUR.opcode & 4) != 0 )
distance = CUR_Func_round( org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
else
distance = Round_None( EXEC_ARGS
org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
/* minimum distance flag */
if ( (CUR.opcode & 8) != 0 )
{
if ( org_dist >= 0 )
{
if ( distance < CUR.GS.minimum_distance )
distance = CUR.GS.minimum_distance;
}
else
{
if ( distance > -CUR.GS.minimum_distance )
distance = -CUR.GS.minimum_distance;
}
}
/* now move the point */
org_dist = CUR_Func_project( CUR.zp1.cur_x[point] -
CUR.zp0.cur_x[CUR.GS.rp0],
CUR.zp1.cur_y[point] -
CUR.zp0.cur_y[CUR.GS.rp0] );
CUR_Func_move( &CUR.zp1, point, distance - org_dist );
CUR.GS.rp1 = CUR.GS.rp0;
CUR.GS.rp2 = point;
if ( (CUR.opcode & 16) != 0 )
CUR.GS.rp0 = point;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Bug 698055: bounds check zone pointer in Ins_MDRP'</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 Ins_JMPR( INS_ARG )
{
CUR.IP += (Int)(args[0]);
CUR.step_ins = FALSE;
if(CUR.IP > CUR.codeSize ||
(CUR.code[CUR.IP] != 0x2D && CUR.code[CUR.IP - 1] == 0x2D))
/* The JPMR is meant to stop at the ENDF instruction to finish
* the function. However the programmer made a mistake, and ended
* up one byte too far. I suspect that some TT interpreters handle this
* by detecting that the IP has gone off the end of the function. We can
* allow for simple cases here by just checking the preceding byte.
* Fonts with this problem are not uncommon.
*/
CUR.IP -= 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Bug 698063: Bounds check Ins_JMPR'</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: xps_decode_font_char_imp(xps_font_t *font, int code)
{
byte *table;
/* no cmap selected: return identity */
if (font->cmapsubtable <= 0)
return code;
table = font->data + font->cmapsubtable;
switch (u16(table))
{
case 0: /* Apple standard 1-to-1 mapping. */
{
int i, length = u16(&table[2]) - 6;
if (length < 0 || length > 256)
return gs_error_invalidfont;
for (i=0;i<length;i++) {
if (table[6 + i] == code)
return i;
}
}
return 0;
case 4: /* Microsoft/Adobe segmented mapping. */
{
int segCount2 = u16(table + 6);
byte *endCount = table + 14;
byte *startCount = endCount + segCount2 + 2;
byte *idDelta = startCount + segCount2;
byte *idRangeOffset = idDelta + segCount2;
int i2;
if (segCount2 < 3 || segCount2 > 65535)
return gs_error_invalidfont;
for (i2 = 0; i2 < segCount2 - 3; i2 += 2)
{
int delta = s16(idDelta + i2), roff = s16(idRangeOffset + i2);
int start = u16(startCount + i2);
int end = u16(endCount + i2);
int glyph, i;
if (end < start)
return gs_error_invalidfont;
for (i=start;i<=end;i++) {
if (roff == 0) {
glyph = (i + delta) & 0xffff;
} else {
glyph = u16(idRangeOffset + i2 + roff + ((i - start) << 1));
}
if (glyph == code) {
return i;
}
}
}
}
return 0;
case 6: /* Single interval lookup. */
{
int ch, i, length = u16(&table[8]);
int firstCode = u16(&table[6]);
if (length < 0 || length > 65535)
return gs_error_invalidfont;
for (i=0;i<length;i++) {
ch = u16(&table[10 + (i * 2)]);
if (ch == code)
return (firstCode + i);
}
}
return 0;
case 10: /* Trimmed array (like 6) */
{
unsigned int ch, i, length = u32(&table[20]);
int firstCode = u32(&table[16]);
for (i=0;i<length;i++) {
ch = u16(&table[10 + (i * 2)]);
if (ch == code)
return (firstCode + i);
}
}
return 0;
case 12: /* Segmented coverage. (like 4) */
{
unsigned int nGroups = u32(&table[12]);
int Group;
for (Group=0;Group<nGroups;Group++)
{
int startCharCode = u32(&table[16 + (Group * 12)]);
int endCharCode = u32(&table[16 + (Group * 12) + 4]);
int startGlyphCode = u32(&table[16 + (Group * 12) + 8]);
if (code >= startGlyphCode && code <= (startGlyphCode + (endCharCode - startCharCode))) {
return startGlyphCode + (code - startCharCode);
}
}
}
return 0;
case 2: /* High-byte mapping through table. */
case 8: /* Mixed 16-bit and 32-bit coverage (like 2) */
default:
gs_warn1("unknown cmap format: %d\n", u16(table));
return 0;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Bug 698064: bounds check xps_encode/decode_font_char_imp'</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: i_alloc_struct_array(gs_memory_t * mem, uint num_elements,
gs_memory_type_ptr_t pstype, client_name_t cname)
{
gs_ref_memory_t * const imem = (gs_ref_memory_t *)mem;
obj_header_t *obj;
#ifdef MEMENTO
if (Memento_failThisEvent())
return NULL;
#endif
ALLOC_CHECK_SIZE(mem,pstype);
#ifdef DEBUG
if (pstype->enum_ptrs == basic_enum_ptrs) {
dmprintf2(mem, " i_alloc_struct_array: called with incorrect structure type (not element), struct='%s', client='%s'\n",
pstype->sname, cname);
return NULL; /* fail */
}
#endif
obj = alloc_obj(imem,
(ulong) num_elements * pstype->ssize,
pstype, ALLOC_DIRECT, cname);
if_debug7m('A', mem, "[a%d:+<.]%s %s*(%lu=%u*%u) = 0x%lx\n",
alloc_trace_space(imem), client_name_string(cname),
struct_type_name_string(pstype),
(ulong) num_elements * pstype->ssize,
num_elements, pstype->ssize, (ulong) obj);
return (char *)obj;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'Bug 697985: bounds check the array allocations methods
The clump allocator has four allocation functions that use 'number of elements'
and 'size of elements' parameters (rather than a simple 'number of bytes').
Those need specific bounds checking.'</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: i_alloc_byte_array(gs_memory_t * mem, uint num_elements, uint elt_size,
client_name_t cname)
{
gs_ref_memory_t * const imem = (gs_ref_memory_t *)mem;
obj_header_t *obj;
#ifdef MEMENTO
if (Memento_failThisEvent())
return NULL;
#endif
obj = alloc_obj(imem, (ulong) num_elements * elt_size,
&st_bytes, ALLOC_DIRECT, cname);
if_debug6m('A', mem, "[a%d:+b.]%s -bytes-*(%lu=%u*%u) = 0x%lx\n",
alloc_trace_space(imem), client_name_string(cname),
(ulong) num_elements * elt_size,
num_elements, elt_size, (ulong) obj);
return (byte *) obj;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'Bug 697985: bounds check the array allocations methods
The clump allocator has four allocation functions that use 'number of elements'
and 'size of elements' parameters (rather than a simple 'number of bytes').
Those need specific bounds checking.'</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 Huff_Compress(msg_t *mbuf, int offset) {
int i, ch, size;
byte seq[65536];
byte* buffer;
huff_t huff;
size = mbuf->cursize - offset;
buffer = mbuf->data+ + offset;
if (size<=0) {
return;
}
Com_Memset(&huff, 0, sizeof(huff_t));
// Add the NYT (not yet transmitted) node into the tree/list */
huff.tree = huff.lhead = huff.loc[NYT] = &(huff.nodeList[huff.blocNode++]);
huff.tree->symbol = NYT;
huff.tree->weight = 0;
huff.lhead->next = huff.lhead->prev = NULL;
huff.tree->parent = huff.tree->left = huff.tree->right = NULL;
seq[0] = (size>>8);
seq[1] = size&0xff;
bloc = 16;
for (i=0; i<size; i++ ) {
ch = buffer[i];
Huff_transmit(&huff, ch, seq); /* Transmit symbol */
Huff_addRef(&huff, (byte)ch); /* Do update */
}
bloc += 8; // next byte
mbuf->cursize = (bloc>>3) + offset;
Com_Memcpy(mbuf->data+offset, seq, (bloc>>3));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits
Prevent reading past end of message in MSG_ReadBits. If read past
end of msg->data buffer (16348 bytes) the engine could SEGFAULT.
Make MSG_WriteBits use an exact buffer overflow check instead of
possibly failing with a few bytes left.'</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 Huff_transmit (huff_t *huff, int ch, byte *fout) {
int i;
if (huff->loc[ch] == NULL) {
/* node_t hasn't been transmitted, send a NYT, then the symbol */
Huff_transmit(huff, NYT, fout);
for (i = 7; i >= 0; i--) {
add_bit((char)((ch >> i) & 0x1), fout);
}
} else {
send(huff->loc[ch], NULL, fout);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits
Prevent reading past end of message in MSG_ReadBits. If read past
end of msg->data buffer (16348 bytes) the engine could SEGFAULT.
Make MSG_WriteBits use an exact buffer overflow check instead of
possibly failing with a few bytes left.'</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 Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset) {
bloc = *offset;
while (node && node->symbol == INTERNAL_NODE) {
if (get_bit(fin)) {
node = node->right;
} else {
node = node->left;
}
}
if (!node) {
*ch = 0;
return;
// Com_Error(ERR_DROP, "Illegal tree!");
}
*ch = node->symbol;
*offset = bloc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits
Prevent reading past end of message in MSG_ReadBits. If read past
end of msg->data buffer (16348 bytes) the engine could SEGFAULT.
Make MSG_WriteBits use an exact buffer overflow check instead of
possibly failing with a few bytes left.'</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 MSG_WriteBits( msg_t *msg, int value, int bits ) {
int i;
oldsize += bits;
// this isn't an exact overflow check, but close enough
if ( msg->maxsize - msg->cursize < 4 ) {
msg->overflowed = qtrue;
return;
}
if ( bits == 0 || bits < -31 || bits > 32 ) {
Com_Error( ERR_DROP, "MSG_WriteBits: bad bits %i", bits );
}
if ( bits < 0 ) {
bits = -bits;
}
if ( msg->oob ) {
if ( bits == 8 ) {
msg->data[msg->cursize] = value;
msg->cursize += 1;
msg->bit += 8;
} else if ( bits == 16 ) {
short temp = value;
CopyLittleShort( &msg->data[msg->cursize], &temp );
msg->cursize += 2;
msg->bit += 16;
} else if ( bits==32 ) {
CopyLittleLong( &msg->data[msg->cursize], &value );
msg->cursize += 4;
msg->bit += 32;
} else {
Com_Error( ERR_DROP, "can't write %d bits", bits );
}
} else {
value &= (0xffffffff >> (32 - bits));
if ( bits&7 ) {
int nbits;
nbits = bits&7;
for( i = 0; i < nbits; i++ ) {
Huff_putBit( (value & 1), msg->data, &msg->bit );
value = (value >> 1);
}
bits = bits - nbits;
}
if ( bits ) {
for( i = 0; i < bits; i += 8 ) {
Huff_offsetTransmit( &msgHuff.compressor, (value & 0xff), msg->data, &msg->bit );
value = (value >> 8);
}
}
msg->cursize = (msg->bit >> 3) + 1;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits
Prevent reading past end of message in MSG_ReadBits. If read past
end of msg->data buffer (16348 bytes) the engine could SEGFAULT.
Make MSG_WriteBits use an exact buffer overflow check instead of
possibly failing with a few bytes left.'</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: soup_filter_input_stream_read_until (SoupFilterInputStream *fstream,
void *buffer,
gsize length,
const void *boundary,
gsize boundary_length,
gboolean blocking,
gboolean include_boundary,
gboolean *got_boundary,
GCancellable *cancellable,
GError **error)
{
gssize nread;
guint8 *p, *buf, *end;
gboolean eof = FALSE;
GError *my_error = NULL;
g_return_val_if_fail (SOUP_IS_FILTER_INPUT_STREAM (fstream), -1);
g_return_val_if_fail (!include_boundary || (boundary_length < length), -1);
*got_boundary = FALSE;
fstream->priv->need_more = FALSE;
if (!fstream->priv->buf || fstream->priv->buf->len < boundary_length) {
guint prev_len;
fill_buffer:
if (!fstream->priv->buf)
fstream->priv->buf = g_byte_array_new ();
prev_len = fstream->priv->buf->len;
g_byte_array_set_size (fstream->priv->buf, length);
buf = fstream->priv->buf->data;
fstream->priv->in_read_until = TRUE;
nread = g_pollable_stream_read (G_INPUT_STREAM (fstream),
buf + prev_len, length - prev_len,
blocking,
cancellable, &my_error);
fstream->priv->in_read_until = FALSE;
if (nread <= 0) {
if (prev_len)
fstream->priv->buf->len = prev_len;
else {
g_byte_array_free (fstream->priv->buf, TRUE);
fstream->priv->buf = NULL;
}
if (nread == 0 && prev_len)
eof = TRUE;
else {
if (g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
fstream->priv->need_more = TRUE;
if (my_error)
g_propagate_error (error, my_error);
return nread;
}
if (my_error)
g_propagate_error (error, my_error);
} else
fstream->priv->buf->len = prev_len + nread;
} else
buf = fstream->priv->buf->data;
/* Scan for the boundary */
end = buf + fstream->priv->buf->len;
if (!eof)
end -= boundary_length;
for (p = buf; p <= end; p++) {
if (*p == *(guint8*)boundary &&
!memcmp (p, boundary, boundary_length)) {
if (include_boundary)
p += boundary_length;
*got_boundary = TRUE;
break;
}
}
if (!*got_boundary && fstream->priv->buf->len < length && !eof)
goto fill_buffer;
/* Return everything up to 'p' (which is either just after the boundary if
* include_boundary is TRUE, just before the boundary if include_boundary is
* FALSE, @boundary_len - 1 bytes before the end of the buffer, or end-of-
* file).
*/
return read_from_buf (fstream, buffer, p - buf);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'Fix chunked decoding buffer overrun (CVE-2017-2885)
https://bugzilla.gnome.org/show_bug.cgi?id=785774'</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 __ip6_append_data(struct sock *sk,
struct flowi6 *fl6,
struct sk_buff_head *queue,
struct inet_cork *cork,
struct inet6_cork *v6_cork,
struct page_frag *pfrag,
int getfrag(void *from, char *to, int offset,
int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
unsigned int flags, struct ipcm6_cookie *ipc6,
const struct sockcm_cookie *sockc)
{
struct sk_buff *skb, *skb_prev = NULL;
unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu;
int exthdrlen = 0;
int dst_exthdrlen = 0;
int hh_len;
int copy;
int err;
int offset = 0;
__u8 tx_flags = 0;
u32 tskey = 0;
struct rt6_info *rt = (struct rt6_info *)cork->dst;
struct ipv6_txoptions *opt = v6_cork->opt;
int csummode = CHECKSUM_NONE;
unsigned int maxnonfragsize, headersize;
skb = skb_peek_tail(queue);
if (!skb) {
exthdrlen = opt ? opt->opt_flen : 0;
dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
}
mtu = cork->fragsize;
orig_mtu = mtu;
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen -
sizeof(struct frag_hdr);
headersize = sizeof(struct ipv6hdr) +
(opt ? opt->opt_flen + opt->opt_nflen : 0) +
(dst_allfrag(&rt->dst) ?
sizeof(struct frag_hdr) : 0) +
rt->rt6i_nfheader_len;
if (cork->length + length > mtu - headersize && ipc6->dontfrag &&
(sk->sk_protocol == IPPROTO_UDP ||
sk->sk_protocol == IPPROTO_RAW)) {
ipv6_local_rxpmtu(sk, fl6, mtu - headersize +
sizeof(struct ipv6hdr));
goto emsgsize;
}
if (ip6_sk_ignore_df(sk))
maxnonfragsize = sizeof(struct ipv6hdr) + IPV6_MAXPLEN;
else
maxnonfragsize = mtu;
if (cork->length + length > maxnonfragsize - headersize) {
emsgsize:
ipv6_local_error(sk, EMSGSIZE, fl6,
mtu - headersize +
sizeof(struct ipv6hdr));
return -EMSGSIZE;
}
/* CHECKSUM_PARTIAL only with no extension headers and when
* we are not going to fragment
*/
if (transhdrlen && sk->sk_protocol == IPPROTO_UDP &&
headersize == sizeof(struct ipv6hdr) &&
length <= mtu - headersize &&
!(flags & MSG_MORE) &&
rt->dst.dev->features & (NETIF_F_IPV6_CSUM | NETIF_F_HW_CSUM))
csummode = CHECKSUM_PARTIAL;
if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) {
sock_tx_timestamp(sk, sockc->tsflags, &tx_flags);
if (tx_flags & SKBTX_ANY_SW_TSTAMP &&
sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)
tskey = sk->sk_tskey++;
}
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
cork->length += length;
if ((((length + (skb ? skb->len : headersize)) > mtu) ||
(skb && skb_is_gso(skb))) &&
(sk->sk_protocol == IPPROTO_UDP) &&
(rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) &&
(sk->sk_type == SOCK_DGRAM) && !udp_get_no_check6_tx(sk)) {
err = ip6_ufo_append_data(sk, queue, getfrag, from, length,
hh_len, fragheaderlen, exthdrlen,
transhdrlen, mtu, flags, fl6);
if (err)
goto error;
return 0;
}
if (!skb)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
alloc_new_skb:
/* There's no room in the current skb */
if (skb)
fraggap = skb->len - maxfraglen;
else
fraggap = 0;
/* update mtu and maxfraglen if necessary */
if (!skb || !skb_prev)
ip6_append_data_mtu(&mtu, &maxfraglen,
fragheaderlen, skb, rt,
orig_mtu);
skb_prev = skb;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
alloclen += dst_exthdrlen;
if (datalen != length + fraggap) {
/*
* this is not the last fragment, the trailer
* space is regarded as data space.
*/
datalen += rt->dst.trailer_len;
}
alloclen += rt->dst.trailer_len;
fraglen = datalen + fragheaderlen;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
goto error;
}
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (refcount_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(!skb))
err = -ENOBUFS;
}
if (!skb)
goto error;
/*
* Fill in the control structures
*/
skb->protocol = htons(ETH_P_IPV6);
skb->ip_summed = csummode;
skb->csum = 0;
/* reserve for fragmentation and ipsec header */
skb_reserve(skb, hh_len + sizeof(struct frag_hdr) +
dst_exthdrlen);
/* Only the initial fragment is time stamped */
skb_shinfo(skb)->tx_flags = tx_flags;
tx_flags = 0;
skb_shinfo(skb)->tskey = tskey;
tskey = 0;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
if (copy > 0 &&
getfrag(from, data + transhdrlen, offset,
copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
if ((flags & MSG_CONFIRM) && !skb_prev)
skb_set_dst_pending_confirm(skb, 1);
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
err = -ENOMEM;
if (!sk_page_frag_refill(sk, pfrag))
goto error;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
err = -EMSGSIZE;
if (i == MAX_SKB_FRAGS)
goto error;
__skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, 0);
skb_shinfo(skb)->nr_frags = ++i;
get_page(pfrag->page);
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (getfrag(from,
page_address(pfrag->page) + pfrag->offset,
offset, copy, skb->len, skb) < 0)
goto error_efault;
pfrag->offset += copy;
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
refcount_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error_efault:
err = -EFAULT;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'udp: consistently apply ufo or fragmentation
When iteratively building a UDP datagram with MSG_MORE and that
datagram exceeds MTU, consistently choose UFO or fragmentation.
Once skb_is_gso, always apply ufo. Conversely, once a datagram is
split across multiple skbs, do not consider ufo.
Sendpage already maintains the first invariant, only add the second.
IPv6 does not have a sendpage implementation to modify.
A gso skb must have a partial checksum, do not follow sk_no_check_tx
in udp_send_skb.
Found by syzkaller.
Fixes: e89e9cf539a2 ("[IPv4/IPv6]: UFO Scatter-gather approach")
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: Willem de Bruijn <[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 __ip_append_data(struct sock *sk,
struct flowi4 *fl4,
struct sk_buff_head *queue,
struct inet_cork *cork,
struct page_frag *pfrag,
int getfrag(void *from, char *to, int offset,
int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
unsigned int flags)
{
struct inet_sock *inet = inet_sk(sk);
struct sk_buff *skb;
struct ip_options *opt = cork->opt;
int hh_len;
int exthdrlen;
int mtu;
int copy;
int err;
int offset = 0;
unsigned int maxfraglen, fragheaderlen, maxnonfragsize;
int csummode = CHECKSUM_NONE;
struct rtable *rt = (struct rtable *)cork->dst;
u32 tskey = 0;
skb = skb_peek_tail(queue);
exthdrlen = !skb ? rt->dst.header_len : 0;
mtu = cork->fragsize;
if (cork->tx_flags & SKBTX_ANY_SW_TSTAMP &&
sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)
tskey = sk->sk_tskey++;
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct iphdr) + (opt ? opt->optlen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen;
maxnonfragsize = ip_sk_ignore_df(sk) ? 0xFFFF : mtu;
if (cork->length + length > maxnonfragsize - fragheaderlen) {
ip_local_error(sk, EMSGSIZE, fl4->daddr, inet->inet_dport,
mtu - (opt ? opt->optlen : 0));
return -EMSGSIZE;
}
/*
* transhdrlen > 0 means that this is the first fragment and we wish
* it won't be fragmented in the future.
*/
if (transhdrlen &&
length + fragheaderlen <= mtu &&
rt->dst.dev->features & (NETIF_F_HW_CSUM | NETIF_F_IP_CSUM) &&
!(flags & MSG_MORE) &&
!exthdrlen)
csummode = CHECKSUM_PARTIAL;
cork->length += length;
if ((((length + (skb ? skb->len : fragheaderlen)) > mtu) ||
(skb && skb_is_gso(skb))) &&
(sk->sk_protocol == IPPROTO_UDP) &&
(rt->dst.dev->features & NETIF_F_UFO) && !dst_xfrm(&rt->dst) &&
(sk->sk_type == SOCK_DGRAM) && !sk->sk_no_check_tx) {
err = ip_ufo_append_data(sk, queue, getfrag, from, length,
hh_len, fragheaderlen, transhdrlen,
maxfraglen, flags);
if (err)
goto error;
return 0;
}
/* So, what's going on in the loop below?
*
* We use calculated fragment length to generate chained skb,
* each of segments is IP fragment ready for sending to network after
* adding appropriate IP header.
*/
if (!skb)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = mtu - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
struct sk_buff *skb_prev;
alloc_new_skb:
skb_prev = skb;
if (skb_prev)
fraggap = skb_prev->len - maxfraglen;
else
fraggap = 0;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > mtu - fragheaderlen)
datalen = maxfraglen - fragheaderlen;
fraglen = datalen + fragheaderlen;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = fraglen;
alloclen += exthdrlen;
/* The last fragment gets additional space at tail.
* Note, with MSG_MORE we overallocate on fragments,
* because we have no idea what fragment will be
* the last.
*/
if (datalen == length + fraggap)
alloclen += rt->dst.trailer_len;
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len + 15,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (refcount_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len + 15, 1,
sk->sk_allocation);
if (unlikely(!skb))
err = -ENOBUFS;
}
if (!skb)
goto error;
/*
* Fill in the control structures
*/
skb->ip_summed = csummode;
skb->csum = 0;
skb_reserve(skb, hh_len);
/* only the initial fragment is time stamped */
skb_shinfo(skb)->tx_flags = cork->tx_flags;
cork->tx_flags = 0;
skb_shinfo(skb)->tskey = tskey;
tskey = 0;
/*
* Find where to start putting bytes.
*/
data = skb_put(skb, fraglen + exthdrlen);
skb_set_network_header(skb, exthdrlen);
skb->transport_header = (skb->network_header +
fragheaderlen);
data += fragheaderlen + exthdrlen;
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
copy = datalen - transhdrlen - fraggap;
if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
csummode = CHECKSUM_NONE;
if ((flags & MSG_CONFIRM) && !skb_prev)
skb_set_dst_pending_confirm(skb, 1);
/*
* Put the packet on the pending queue.
*/
__skb_queue_tail(queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
err = -ENOMEM;
if (!sk_page_frag_refill(sk, pfrag))
goto error;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
err = -EMSGSIZE;
if (i == MAX_SKB_FRAGS)
goto error;
__skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, 0);
skb_shinfo(skb)->nr_frags = ++i;
get_page(pfrag->page);
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (getfrag(from,
page_address(pfrag->page) + pfrag->offset,
offset, copy, skb->len, skb) < 0)
goto error_efault;
pfrag->offset += copy;
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
refcount_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error_efault:
err = -EFAULT;
error:
cork->length -= length;
IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTDISCARDS);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'udp: consistently apply ufo or fragmentation
When iteratively building a UDP datagram with MSG_MORE and that
datagram exceeds MTU, consistently choose UFO or fragmentation.
Once skb_is_gso, always apply ufo. Conversely, once a datagram is
split across multiple skbs, do not consider ufo.
Sendpage already maintains the first invariant, only add the second.
IPv6 does not have a sendpage implementation to modify.
A gso skb must have a partial checksum, do not follow sk_no_check_tx
in udp_send_skb.
Found by syzkaller.
Fixes: e89e9cf539a2 ("[IPv4/IPv6]: UFO Scatter-gather approach")
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: Willem de Bruijn <[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 timerfd_remove_cancel(struct timerfd_ctx *ctx)
{
if (ctx->might_cancel) {
ctx->might_cancel = false;
spin_lock(&cancel_lock);
list_del_rcu(&ctx->clist);
spin_unlock(&cancel_lock);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'timerfd: Protect the might cancel mechanism proper
The handling of the might_cancel queueing is not properly protected, so
parallel operations on the file descriptor can race with each other and
lead to list corruptions or use after free.
Protect the context for these operations with a seperate lock.
The wait queue lock cannot be reused for this because that would create a
lock inversion scenario vs. the cancel lock. Replacing might_cancel with an
atomic (atomic_t or atomic bit) does not help either because it still can
race vs. the actual list operation.
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Cc: "[email protected]"
Cc: syzkaller <[email protected]>
Cc: Al Viro <[email protected]>
Cc: [email protected]
Link: http://lkml.kernel.org/r/alpine.DEB.2.20.1701311521430.3457@nanos
Signed-off-by: Thomas Gleixner <[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: SYSCALL_DEFINE2(timerfd_create, int, clockid, int, flags)
{
int ufd;
struct timerfd_ctx *ctx;
/* Check the TFD_* constants for consistency. */
BUILD_BUG_ON(TFD_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(TFD_NONBLOCK != O_NONBLOCK);
if ((flags & ~TFD_CREATE_FLAGS) ||
(clockid != CLOCK_MONOTONIC &&
clockid != CLOCK_REALTIME &&
clockid != CLOCK_REALTIME_ALARM &&
clockid != CLOCK_BOOTTIME &&
clockid != CLOCK_BOOTTIME_ALARM))
return -EINVAL;
if (!capable(CAP_WAKE_ALARM) &&
(clockid == CLOCK_REALTIME_ALARM ||
clockid == CLOCK_BOOTTIME_ALARM))
return -EPERM;
ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
init_waitqueue_head(&ctx->wqh);
ctx->clockid = clockid;
if (isalarm(ctx))
alarm_init(&ctx->t.alarm,
ctx->clockid == CLOCK_REALTIME_ALARM ?
ALARM_REALTIME : ALARM_BOOTTIME,
timerfd_alarmproc);
else
hrtimer_init(&ctx->t.tmr, clockid, HRTIMER_MODE_ABS);
ctx->moffs = ktime_mono_to_real(0);
ufd = anon_inode_getfd("[timerfd]", &timerfd_fops, ctx,
O_RDWR | (flags & TFD_SHARED_FCNTL_FLAGS));
if (ufd < 0)
kfree(ctx);
return ufd;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'timerfd: Protect the might cancel mechanism proper
The handling of the might_cancel queueing is not properly protected, so
parallel operations on the file descriptor can race with each other and
lead to list corruptions or use after free.
Protect the context for these operations with a seperate lock.
The wait queue lock cannot be reused for this because that would create a
lock inversion scenario vs. the cancel lock. Replacing might_cancel with an
atomic (atomic_t or atomic bit) does not help either because it still can
race vs. the actual list operation.
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Cc: "[email protected]"
Cc: syzkaller <[email protected]>
Cc: Al Viro <[email protected]>
Cc: [email protected]
Link: http://lkml.kernel.org/r/alpine.DEB.2.20.1701311521430.3457@nanos
Signed-off-by: Thomas Gleixner <[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 sanity_check_ckpt(struct f2fs_sb_info *sbi)
{
unsigned int total, fsmeta;
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
unsigned int ovp_segments, reserved_segments;
total = le32_to_cpu(raw_super->segment_count);
fsmeta = le32_to_cpu(raw_super->segment_count_ckpt);
fsmeta += le32_to_cpu(raw_super->segment_count_sit);
fsmeta += le32_to_cpu(raw_super->segment_count_nat);
fsmeta += le32_to_cpu(ckpt->rsvd_segment_count);
fsmeta += le32_to_cpu(raw_super->segment_count_ssa);
if (unlikely(fsmeta >= total))
return 1;
ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
if (unlikely(fsmeta < F2FS_MIN_SEGMENTS ||
ovp_segments == 0 || reserved_segments == 0)) {
f2fs_msg(sbi->sb, KERN_ERR,
"Wrong layout: check mkfs.f2fs version");
return 1;
}
if (unlikely(f2fs_cp_error(sbi))) {
f2fs_msg(sbi->sb, KERN_ERR, "A bug case: need to run fsck");
return 1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-129'], 'message': 'f2fs: sanity check checkpoint segno and blkoff
Make sure segno and blkoff read from raw image are valid.
Cc: [email protected]
Signed-off-by: Jin Qian <[email protected]>
[Jaegeuk Kim: adjust minor coding style]
Signed-off-by: Jaegeuk Kim <[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: isdn_net_newslave(char *parm)
{
char *p = strchr(parm, ',');
isdn_net_dev *n;
char newname[10];
if (p) {
/* Slave-Name MUST not be empty */
if (!strlen(p + 1))
return NULL;
strcpy(newname, p + 1);
*p = 0;
/* Master must already exist */
if (!(n = isdn_net_findif(parm)))
return NULL;
/* Master must be a real interface, not a slave */
if (n->local->master)
return NULL;
/* Master must not be started yet */
if (isdn_net_device_started(n))
return NULL;
return (isdn_net_new(newname, n->dev));
}
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'isdn/i4l: fix buffer overflow
This fixes a potential buffer overflow in isdn_net.c caused by an
unbounded strcpy.
[ ISDN seems to be effectively unmaintained, and the I4L driver in
particular is long deprecated, but in case somebody uses this..
- Linus ]
Signed-off-by: Jiten Thakkar <[email protected]>
Signed-off-by: Annie Cherkaev <[email protected]>
Cc: Karsten Keil <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: [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: static Image *ReadWMFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
double
bounding_height,
bounding_width,
image_height,
image_height_inch,
image_width,
image_width_inch,
resolution_y,
resolution_x,
units_per_inch;
float
wmf_width,
wmf_height;
Image
*image;
MagickBooleanType
status;
unsigned long
wmf_options_flags = 0;
wmf_error_t
wmf_error;
wmf_magick_t
*ddata = 0;
wmfAPI
*API = 0;
wmfAPI_Options
wmf_api_options;
wmfD_Rect
bbox;
image=AcquireImage(image_info,exception);
if (OpenBlob(image_info,image,ReadBinaryBlobMode,exception) == MagickFalse)
{
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" OpenBlob failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
* Create WMF API
*
*/
/* Register callbacks */
wmf_options_flags |= WMF_OPT_FUNCTION;
(void) ResetMagickMemory(&wmf_api_options, 0, sizeof(wmf_api_options));
wmf_api_options.function = ipa_functions;
/* Ignore non-fatal errors */
wmf_options_flags |= WMF_OPT_IGNORE_NONFATAL;
wmf_error = wmf_api_create(&API, wmf_options_flags, &wmf_api_options);
if (wmf_error != wmf_E_None)
{
if (API)
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_api_create failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"UnableToInitializeWMFLibrary");
}
/* Register progress monitor */
wmf_status_function(API,image,magick_progress_callback);
ddata=WMF_MAGICK_GetData(API);
ddata->image=image;
ddata->image_info=image_info;
ddata->draw_info=CloneDrawInfo(image_info,(const DrawInfo *) NULL);
ddata->exception=exception;
ddata->draw_info->font=(char *)
RelinquishMagickMemory(ddata->draw_info->font);
ddata->draw_info->text=(char *)
RelinquishMagickMemory(ddata->draw_info->text);
#if defined(MAGICKCORE_WMF_DELEGATE)
/* Must initialize font subystem for WMFlite interface */
lite_font_init (API,&wmf_api_options); /* similar to wmf_ipa_font_init in src/font.c */
/* wmf_arg_fontdirs (API,options); */ /* similar to wmf_arg_fontdirs in src/wmf.c */
#endif
/*
* Open BLOB input via libwmf API
*
*/
wmf_error = wmf_bbuf_input(API,ipa_blob_read,ipa_blob_seek,
ipa_blob_tell,(void*)image);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_bbuf_input failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
* Scan WMF file
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scanning WMF to obtain bounding box");
wmf_error=wmf_scan(API, 0, &bbox);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_scan failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToScanFile");
}
/*
* Compute dimensions and scale factors
*
*/
ddata->bbox=bbox;
/* User specified resolution */
resolution_y=DefaultResolution;
if (image->resolution.y != 0.0)
{
resolution_y = image->resolution.y;
if (image->units == PixelsPerCentimeterResolution)
resolution_y *= CENTIMETERS_PER_INCH;
}
resolution_x=DefaultResolution;
if (image->resolution.x != 0.0)
{
resolution_x = image->resolution.x;
if (image->units == PixelsPerCentimeterResolution)
resolution_x *= CENTIMETERS_PER_INCH;
}
/* Obtain output size expressed in metafile units */
wmf_error=wmf_size(API,&wmf_width,&wmf_height);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_size failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToComputeOutputSize");
}
/* Obtain (or guess) metafile units */
if ((API)->File->placeable)
units_per_inch=(API)->File->pmh->Inch;
else if ( (wmf_width*wmf_height) < 1024*1024)
units_per_inch=POINTS_PER_INCH; /* MM_TEXT */
else
units_per_inch=TWIPS_PER_INCH; /* MM_TWIPS */
/* Calculate image width and height based on specified DPI
resolution */
image_width_inch = (double) wmf_width / units_per_inch;
image_height_inch = (double) wmf_height / units_per_inch;
image_width = image_width_inch * resolution_x;
image_height = image_height_inch * resolution_y;
/* Compute bounding box scale factors and origin translations
*
* This all just a hack since libwmf does not currently seem to
* provide the mapping between LOGICAL coordinates and DEVICE
* coordinates. This mapping is necessary in order to know
* where to place the logical bounding box within the image.
*
*/
bounding_width = bbox.BR.x - bbox.TL.x;
bounding_height = bbox.BR.y - bbox.TL.y;
ddata->scale_x = image_width/bounding_width;
ddata->translate_x = 0-bbox.TL.x;
ddata->rotate = 0;
/* Heuristic: guess that if the vertical coordinates mostly span
negative values, then the image must be inverted. */
if ( fabs(bbox.BR.y) > fabs(bbox.TL.y) )
{
/* Normal (Origin at top left of image) */
ddata->scale_y = (image_height/bounding_height);
ddata->translate_y = 0-bbox.TL.y;
}
else
{
/* Inverted (Origin at bottom left of image) */
ddata->scale_y = (-image_height/bounding_height);
ddata->translate_y = 0-bbox.BR.y;
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Placeable metafile: %s",
(API)->File->placeable ? "Yes" : "No");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Size in metafile units: %gx%g",wmf_width,wmf_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Metafile units/inch: %g",units_per_inch);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Size in inches: %gx%g",
image_width_inch,image_height_inch);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding Box: %g,%g %g,%g",
bbox.TL.x, bbox.TL.y, bbox.BR.x, bbox.BR.y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding width x height: %gx%g",bounding_width,
bounding_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Output resolution: %gx%g",resolution_x,resolution_y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image size: %gx%g",image_width,image_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding box scale factor: %g,%g",ddata->scale_x,
ddata->scale_y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Translation: %g,%g",
ddata->translate_x, ddata->translate_y);
}
#if 0
#if 0
{
typedef struct _wmfPlayer_t wmfPlayer_t;
struct _wmfPlayer_t
{
wmfPen default_pen;
wmfBrush default_brush;
wmfFont default_font;
wmfDC* dc; /* current dc */
};
wmfDC
*dc;
#define WMF_ELICIT_DC(API) (((wmfPlayer_t*)((API)->player_data))->dc)
dc = WMF_ELICIT_DC(API);
printf("dc->Window.Ox = %d\n", dc->Window.Ox);
printf("dc->Window.Oy = %d\n", dc->Window.Oy);
printf("dc->Window.width = %d\n", dc->Window.width);
printf("dc->Window.height = %d\n", dc->Window.height);
printf("dc->pixel_width = %g\n", dc->pixel_width);
printf("dc->pixel_height = %g\n", dc->pixel_height);
#if defined(MAGICKCORE_WMF_DELEGATE) /* Only in libwmf 0.3 */
printf("dc->Ox = %.d\n", dc->Ox);
printf("dc->Oy = %.d\n", dc->Oy);
printf("dc->width = %.d\n", dc->width);
printf("dc->height = %.d\n", dc->height);
#endif
}
#endif
#endif
/*
* Create canvas image
*
*/
image->rows=(unsigned long) ceil(image_height);
image->columns=(unsigned long) ceil(image_width);
if (image_info->ping != MagickFalse)
{
wmf_api_destroy(API);
(void) CloseBlob(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating canvas image with size %lux%lu",(unsigned long) image->rows,
(unsigned long) image->columns);
/*
* Set solid background color
*/
{
image->background_color = image_info->background_color;
if (image->background_color.alpha != OpaqueAlpha)
image->alpha_trait=BlendPixelTrait;
(void) SetImageBackgroundColor(image,exception);
}
/*
* Play file to generate Vector drawing commands
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Playing WMF to prepare vectors");
wmf_error = wmf_play(API, 0, &bbox);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Playing WMF failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToRenderFile");
}
/*
* Scribble on canvas image
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Rendering WMF vectors");
DrawRender(ddata->draw_wand);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"leave ReadWMFImage()");
/* Cleanup allocated data */
wmf_api_destroy(API);
(void) CloseBlob(image);
/* Return image */
return image;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/544'</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 Image *ReadWMFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
double
bounding_height,
bounding_width,
image_height,
image_height_inch,
image_width,
image_width_inch,
resolution_y,
resolution_x,
units_per_inch;
float
wmf_width,
wmf_height;
Image
*image;
MagickBooleanType
status;
unsigned long
wmf_options_flags = 0;
wmf_error_t
wmf_error;
wmf_magick_t
*ddata = 0;
wmfAPI
*API = 0;
wmfAPI_Options
wmf_api_options;
wmfD_Rect
bbox;
image=AcquireImage(image_info,exception);
if (OpenBlob(image_info,image,ReadBinaryBlobMode,exception) == MagickFalse)
{
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" OpenBlob failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
* Create WMF API
*
*/
/* Register callbacks */
wmf_options_flags |= WMF_OPT_FUNCTION;
(void) ResetMagickMemory(&wmf_api_options, 0, sizeof(wmf_api_options));
wmf_api_options.function = ipa_functions;
/* Ignore non-fatal errors */
wmf_options_flags |= WMF_OPT_IGNORE_NONFATAL;
wmf_error = wmf_api_create(&API, wmf_options_flags, &wmf_api_options);
if (wmf_error != wmf_E_None)
{
if (API)
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_api_create failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"UnableToInitializeWMFLibrary");
}
/* Register progress monitor */
wmf_status_function(API,image,magick_progress_callback);
ddata=WMF_MAGICK_GetData(API);
ddata->image=image;
ddata->image_info=image_info;
ddata->draw_info=CloneDrawInfo(image_info,(const DrawInfo *) NULL);
ddata->exception=exception;
ddata->draw_info->font=(char *)
RelinquishMagickMemory(ddata->draw_info->font);
ddata->draw_info->text=(char *)
RelinquishMagickMemory(ddata->draw_info->text);
#if defined(MAGICKCORE_WMF_DELEGATE)
/* Must initialize font subystem for WMFlite interface */
lite_font_init (API,&wmf_api_options); /* similar to wmf_ipa_font_init in src/font.c */
/* wmf_arg_fontdirs (API,options); */ /* similar to wmf_arg_fontdirs in src/wmf.c */
#endif
/*
* Open BLOB input via libwmf API
*
*/
wmf_error = wmf_bbuf_input(API,ipa_blob_read,ipa_blob_seek,
ipa_blob_tell,(void*)image);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_bbuf_input failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
* Scan WMF file
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scanning WMF to obtain bounding box");
wmf_error=wmf_scan(API, 0, &bbox);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (ddata->draw_info != (DrawInfo *) NULL)
{
DestroyDrawInfo(ddata->draw_info);
ddata->draw_info=(DrawInfo *)NULL;
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_scan failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToScanFile");
}
/*
* Compute dimensions and scale factors
*
*/
ddata->bbox=bbox;
/* User specified resolution */
resolution_y=DefaultResolution;
if (image->resolution.y != 0.0)
{
resolution_y = image->resolution.y;
if (image->units == PixelsPerCentimeterResolution)
resolution_y *= CENTIMETERS_PER_INCH;
}
resolution_x=DefaultResolution;
if (image->resolution.x != 0.0)
{
resolution_x = image->resolution.x;
if (image->units == PixelsPerCentimeterResolution)
resolution_x *= CENTIMETERS_PER_INCH;
}
/* Obtain output size expressed in metafile units */
wmf_error=wmf_size(API,&wmf_width,&wmf_height);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_size failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToComputeOutputSize");
}
/* Obtain (or guess) metafile units */
if ((API)->File->placeable)
units_per_inch=(API)->File->pmh->Inch;
else if ( (wmf_width*wmf_height) < 1024*1024)
units_per_inch=POINTS_PER_INCH; /* MM_TEXT */
else
units_per_inch=TWIPS_PER_INCH; /* MM_TWIPS */
/* Calculate image width and height based on specified DPI
resolution */
image_width_inch = (double) wmf_width / units_per_inch;
image_height_inch = (double) wmf_height / units_per_inch;
image_width = image_width_inch * resolution_x;
image_height = image_height_inch * resolution_y;
/* Compute bounding box scale factors and origin translations
*
* This all just a hack since libwmf does not currently seem to
* provide the mapping between LOGICAL coordinates and DEVICE
* coordinates. This mapping is necessary in order to know
* where to place the logical bounding box within the image.
*
*/
bounding_width = bbox.BR.x - bbox.TL.x;
bounding_height = bbox.BR.y - bbox.TL.y;
ddata->scale_x = image_width/bounding_width;
ddata->translate_x = 0-bbox.TL.x;
ddata->rotate = 0;
/* Heuristic: guess that if the vertical coordinates mostly span
negative values, then the image must be inverted. */
if ( fabs(bbox.BR.y) > fabs(bbox.TL.y) )
{
/* Normal (Origin at top left of image) */
ddata->scale_y = (image_height/bounding_height);
ddata->translate_y = 0-bbox.TL.y;
}
else
{
/* Inverted (Origin at bottom left of image) */
ddata->scale_y = (-image_height/bounding_height);
ddata->translate_y = 0-bbox.BR.y;
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Placeable metafile: %s",
(API)->File->placeable ? "Yes" : "No");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Size in metafile units: %gx%g",wmf_width,wmf_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Metafile units/inch: %g",units_per_inch);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Size in inches: %gx%g",
image_width_inch,image_height_inch);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding Box: %g,%g %g,%g",
bbox.TL.x, bbox.TL.y, bbox.BR.x, bbox.BR.y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding width x height: %gx%g",bounding_width,
bounding_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Output resolution: %gx%g",resolution_x,resolution_y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image size: %gx%g",image_width,image_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding box scale factor: %g,%g",ddata->scale_x,
ddata->scale_y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Translation: %g,%g",
ddata->translate_x, ddata->translate_y);
}
#if 0
#if 0
{
typedef struct _wmfPlayer_t wmfPlayer_t;
struct _wmfPlayer_t
{
wmfPen default_pen;
wmfBrush default_brush;
wmfFont default_font;
wmfDC* dc; /* current dc */
};
wmfDC
*dc;
#define WMF_ELICIT_DC(API) (((wmfPlayer_t*)((API)->player_data))->dc)
dc = WMF_ELICIT_DC(API);
printf("dc->Window.Ox = %d\n", dc->Window.Ox);
printf("dc->Window.Oy = %d\n", dc->Window.Oy);
printf("dc->Window.width = %d\n", dc->Window.width);
printf("dc->Window.height = %d\n", dc->Window.height);
printf("dc->pixel_width = %g\n", dc->pixel_width);
printf("dc->pixel_height = %g\n", dc->pixel_height);
#if defined(MAGICKCORE_WMF_DELEGATE) /* Only in libwmf 0.3 */
printf("dc->Ox = %.d\n", dc->Ox);
printf("dc->Oy = %.d\n", dc->Oy);
printf("dc->width = %.d\n", dc->width);
printf("dc->height = %.d\n", dc->height);
#endif
}
#endif
#endif
/*
* Create canvas image
*
*/
image->rows=(unsigned long) ceil(image_height);
image->columns=(unsigned long) ceil(image_width);
if (image_info->ping != MagickFalse)
{
wmf_api_destroy(API);
(void) CloseBlob(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating canvas image with size %lux%lu",(unsigned long) image->rows,
(unsigned long) image->columns);
/*
* Set solid background color
*/
{
image->background_color = image_info->background_color;
if (image->background_color.alpha != OpaqueAlpha)
image->alpha_trait=BlendPixelTrait;
(void) SetImageBackgroundColor(image,exception);
}
/*
* Play file to generate Vector drawing commands
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Playing WMF to prepare vectors");
wmf_error = wmf_play(API, 0, &bbox);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Playing WMF failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToRenderFile");
}
/*
* Scribble on canvas image
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Rendering WMF vectors");
DrawRender(ddata->draw_wand);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"leave ReadWMFImage()");
/* Cleanup allocated data */
wmf_api_destroy(API);
(void) CloseBlob(image);
/* Return image */
return image;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/555'</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 Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
cache_filename[MagickPathExtent],
id[MagickPathExtent],
keyword[MagickPathExtent],
*options;
const unsigned char
*p;
GeometryInfo
geometry_info;
Image
*image;
int
c;
LinkedListInfo
*profiles;
MagickBooleanType
status;
MagickOffsetType
offset;
MagickStatusType
flags;
register ssize_t
i;
size_t
depth,
length;
ssize_t
count;
StringInfo
*profile;
unsigned int
signature;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) CopyMagickString(cache_filename,image->filename,MagickPathExtent);
AppendImageFormat("cache",cache_filename);
c=ReadBlobByte(image);
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
*id='\0';
(void) ResetMagickMemory(keyword,0,sizeof(keyword));
offset=0;
do
{
/*
Decode image header; header terminates one character beyond a ':'.
*/
profiles=(LinkedListInfo *) NULL;
length=MagickPathExtent;
options=AcquireString((char *) NULL);
signature=GetMagickSignature((const StringInfo *) NULL);
image->depth=8;
image->compression=NoCompression;
while ((isgraph(c) != MagickFalse) && (c != (int) ':'))
{
register char
*p;
if (c == (int) '{')
{
char
*comment;
/*
Read comment-- any text between { }.
*/
length=MagickPathExtent;
comment=AcquireString((char *) NULL);
for (p=comment; comment != (char *) NULL; p++)
{
c=ReadBlobByte(image);
if (c == (int) '\\')
c=ReadBlobByte(image);
else
if ((c == EOF) || (c == (int) '}'))
break;
if ((size_t) (p-comment+1) >= length)
{
*p='\0';
length<<=1;
comment=(char *) ResizeQuantumMemory(comment,length+
MagickPathExtent,sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=(char) c;
}
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
*p='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
c=ReadBlobByte(image);
}
else
if (isalnum(c) != MagickFalse)
{
/*
Get the keyword.
*/
length=MagickPathExtent;
p=keyword;
do
{
if (c == (int) '=')
break;
if ((size_t) (p-keyword) < (MagickPathExtent-1))
*p++=(char) c;
c=ReadBlobByte(image);
} while (c != EOF);
*p='\0';
p=options;
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
if (c == (int) '=')
{
/*
Get the keyword value.
*/
c=ReadBlobByte(image);
while ((c != (int) '}') && (c != EOF))
{
if ((size_t) (p-options+1) >= length)
{
*p='\0';
length<<=1;
options=(char *) ResizeQuantumMemory(options,length+
MagickPathExtent,sizeof(*options));
if (options == (char *) NULL)
break;
p=options+strlen(options);
}
*p++=(char) c;
c=ReadBlobByte(image);
if (c == '\\')
{
c=ReadBlobByte(image);
if (c == (int) '}')
{
*p++=(char) c;
c=ReadBlobByte(image);
}
}
if (*options != '{')
if (isspace((int) ((unsigned char) c)) != 0)
break;
}
if (options == (char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
*p='\0';
if (*options == '{')
(void) CopyMagickString(options,options+1,strlen(options));
/*
Assign a value to the specified keyword.
*/
switch (*keyword)
{
case 'a':
case 'A':
{
if (LocaleCompare(keyword,"alpha-trait") == 0)
{
ssize_t
alpha_trait;
alpha_trait=ParseCommandOption(MagickPixelTraitOptions,
MagickFalse,options);
if (alpha_trait < 0)
break;
image->alpha_trait=(PixelTrait) alpha_trait;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'b':
case 'B':
{
if (LocaleCompare(keyword,"background-color") == 0)
{
(void) QueryColorCompliance(options,AllCompliance,
&image->background_color,exception);
break;
}
if (LocaleCompare(keyword,"blue-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.blue_primary.x=geometry_info.rho;
image->chromaticity.blue_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.blue_primary.y=
image->chromaticity.blue_primary.x;
break;
}
if (LocaleCompare(keyword,"border-color") == 0)
{
(void) QueryColorCompliance(options,AllCompliance,
&image->border_color,exception);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'c':
case 'C':
{
if (LocaleCompare(keyword,"class") == 0)
{
ssize_t
storage_class;
storage_class=ParseCommandOption(MagickClassOptions,
MagickFalse,options);
if (storage_class < 0)
break;
image->storage_class=(ClassType) storage_class;
break;
}
if (LocaleCompare(keyword,"colors") == 0)
{
image->colors=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
ssize_t
colorspace;
colorspace=ParseCommandOption(MagickColorspaceOptions,
MagickFalse,options);
if (colorspace < 0)
break;
image->colorspace=(ColorspaceType) colorspace;
break;
}
if (LocaleCompare(keyword,"compression") == 0)
{
ssize_t
compression;
compression=ParseCommandOption(MagickCompressOptions,
MagickFalse,options);
if (compression < 0)
break;
image->compression=(CompressionType) compression;
break;
}
if (LocaleCompare(keyword,"columns") == 0)
{
image->columns=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'd':
case 'D':
{
if (LocaleCompare(keyword,"delay") == 0)
{
image->delay=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"depth") == 0)
{
image->depth=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"dispose") == 0)
{
ssize_t
dispose;
dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,
options);
if (dispose < 0)
break;
image->dispose=(DisposeType) dispose;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'e':
case 'E':
{
if (LocaleCompare(keyword,"endian") == 0)
{
ssize_t
endian;
endian=ParseCommandOption(MagickEndianOptions,MagickFalse,
options);
if (endian < 0)
break;
image->endian=(EndianType) endian;
break;
}
if (LocaleCompare(keyword,"error") == 0)
{
image->error.mean_error_per_pixel=StringToDouble(options,
(char **) NULL);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'g':
case 'G':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
image->gamma=StringToDouble(options,(char **) NULL);
break;
}
if (LocaleCompare(keyword,"green-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.green_primary.x=geometry_info.rho;
image->chromaticity.green_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.green_primary.y=
image->chromaticity.green_primary.x;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'i':
case 'I':
{
if (LocaleCompare(keyword,"id") == 0)
{
(void) CopyMagickString(id,options,MagickPathExtent);
break;
}
if (LocaleCompare(keyword,"iterations") == 0)
{
image->iterations=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'm':
case 'M':
{
if (LocaleCompare(keyword,"magick-signature") == 0)
{
signature=(unsigned int) StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"mattecolor") == 0)
{
(void) QueryColorCompliance(options,AllCompliance,
&image->matte_color,exception);
break;
}
if (LocaleCompare(keyword,"maximum-error") == 0)
{
image->error.normalized_maximum_error=StringToDouble(
options,(char **) NULL);
break;
}
if (LocaleCompare(keyword,"mean-error") == 0)
{
image->error.normalized_mean_error=StringToDouble(options,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"montage") == 0)
{
(void) CloneString(&image->montage,options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'n':
case 'N':
{
if (LocaleCompare(keyword,"number-channels") == 0)
{
image->number_channels=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"number-meta-channels") == 0)
{
image->number_meta_channels=StringToUnsignedLong(options);
if (image->number_meta_channels > MaxPixelChannels)
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
break;
}
break;
}
case 'o':
case 'O':
{
if (LocaleCompare(keyword,"orientation") == 0)
{
ssize_t
orientation;
orientation=ParseCommandOption(MagickOrientationOptions,
MagickFalse,options);
if (orientation < 0)
break;
image->orientation=(OrientationType) orientation;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'p':
case 'P':
{
if (LocaleCompare(keyword,"page") == 0)
{
char
*geometry;
geometry=GetPageGeometry(options);
(void) ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
break;
}
if (LocaleCompare(keyword,"pixel-intensity") == 0)
{
ssize_t
intensity;
intensity=ParseCommandOption(MagickPixelIntensityOptions,
MagickFalse,options);
if (intensity < 0)
break;
image->intensity=(PixelIntensityMethod) intensity;
break;
}
if ((LocaleNCompare(keyword,"profile:",8) == 0) ||
(LocaleNCompare(keyword,"profile-",8) == 0))
{
if (profiles == (LinkedListInfo *) NULL)
profiles=NewLinkedList(0);
(void) AppendValueToLinkedList(profiles,
AcquireString(keyword+8));
profile=BlobToStringInfo((const void *) NULL,(size_t)
StringToLong(options));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
(void) SetImageProfile(image,keyword+8,profile,exception);
profile=DestroyStringInfo(profile);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'q':
case 'Q':
{
if (LocaleCompare(keyword,"quality") == 0)
{
image->quality=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'r':
case 'R':
{
if (LocaleCompare(keyword,"red-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.red_primary.x=geometry_info.rho;
if ((flags & SigmaValue) != 0)
image->chromaticity.red_primary.y=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"rendering-intent") == 0)
{
ssize_t
rendering_intent;
rendering_intent=ParseCommandOption(MagickIntentOptions,
MagickFalse,options);
if (rendering_intent < 0)
break;
image->rendering_intent=(RenderingIntent) rendering_intent;
break;
}
if (LocaleCompare(keyword,"resolution") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
break;
}
if (LocaleCompare(keyword,"rows") == 0)
{
image->rows=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 's':
case 'S':
{
if (LocaleCompare(keyword,"scene") == 0)
{
image->scene=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 't':
case 'T':
{
if (LocaleCompare(keyword,"ticks-per-second") == 0)
{
image->ticks_per_second=(ssize_t) StringToLong(options);
break;
}
if (LocaleCompare(keyword,"tile-offset") == 0)
{
char
*geometry;
geometry=GetPageGeometry(options);
(void) ParseAbsoluteGeometry(geometry,&image->tile_offset);
geometry=DestroyString(geometry);
}
if (LocaleCompare(keyword,"type") == 0)
{
ssize_t
type;
type=ParseCommandOption(MagickTypeOptions,MagickFalse,
options);
if (type < 0)
break;
image->type=(ImageType) type;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'u':
case 'U':
{
if (LocaleCompare(keyword,"units") == 0)
{
ssize_t
units;
units=ParseCommandOption(MagickResolutionOptions,
MagickFalse,options);
if (units < 0)
break;
image->units=(ResolutionType) units;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'w':
case 'W':
{
if (LocaleCompare(keyword,"white-point") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.white_point.x=geometry_info.rho;
image->chromaticity.white_point.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.white_point.y=
image->chromaticity.white_point.x;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
default:
{
(void) SetImageProperty(image,keyword,options,exception);
break;
}
}
}
else
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
options=DestroyString(options);
(void) ReadBlobByte(image);
/*
Verify that required image information is defined.
*/
if ((LocaleCompare(id,"MagickCache") != 0) ||
(image->storage_class == UndefinedClass) ||
(image->compression == UndefinedCompression) || (image->columns == 0) ||
(image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (signature != GetMagickSignature((const StringInfo *) NULL))
ThrowReaderException(CacheError,"IncompatibleAPI");
if (image->montage != (char *) NULL)
{
register char
*p;
/*
Image directory.
*/
length=MagickPathExtent;
image->directory=AcquireString((char *) NULL);
p=image->directory;
do
{
*p='\0';
if ((strlen(image->directory)+MagickPathExtent) >= length)
{
/*
Allocate more memory for the image directory.
*/
length<<=1;
image->directory=(char *) ResizeQuantumMemory(image->directory,
length+MagickPathExtent,sizeof(*image->directory));
if (image->directory == (char *) NULL)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
p=image->directory+strlen(image->directory);
}
c=ReadBlobByte(image);
*p++=(char) c;
} while (c != (int) '\0');
}
if (profiles != (LinkedListInfo *) NULL)
{
const char
*name;
const StringInfo
*profile;
register unsigned char
*p;
/*
Read image profiles.
*/
ResetLinkedListIterator(profiles);
name=(const char *) GetNextValueInLinkedList(profiles);
while (name != (const char *) NULL)
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
p=GetStringInfoDatum(profile);
count=ReadBlob(image,GetStringInfoLength(profile),p);
}
name=(const char *) GetNextValueInLinkedList(profiles);
}
profiles=DestroyLinkedList(profiles,RelinquishMagickMemory);
}
depth=GetImageQuantumDepth(image,MagickFalse);
if (image->storage_class == PseudoClass)
{
/*
Create image colormap.
*/
image->colormap=(PixelInfo *) AcquireQuantumMemory(image->colors+1,
sizeof(*image->colormap));
if (image->colormap == (PixelInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->colors != 0)
{
size_t
packet_size;
unsigned char
*colormap;
/*
Read image colormap from file.
*/
packet_size=(size_t) (3UL*depth/8UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
packet_size*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,packet_size*image->colors,colormap);
if (count != (ssize_t) (packet_size*image->colors))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
p=colormap;
switch (depth)
{
default:
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
ThrowReaderException(CorruptImageError,
"ImageDepthNotSupported");
case 8:
{
unsigned char
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushCharPixel(p,&pixel);
image->colormap[i].red=ScaleCharToQuantum(pixel);
p=PushCharPixel(p,&pixel);
image->colormap[i].green=ScaleCharToQuantum(pixel);
p=PushCharPixel(p,&pixel);
image->colormap[i].blue=ScaleCharToQuantum(pixel);
}
break;
}
case 16:
{
unsigned short
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].red=ScaleShortToQuantum(pixel);
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].green=ScaleShortToQuantum(pixel);
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].blue=ScaleShortToQuantum(pixel);
}
break;
}
case 32:
{
unsigned int
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].red=ScaleLongToQuantum(pixel);
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].green=ScaleLongToQuantum(pixel);
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].blue=ScaleLongToQuantum(pixel);
}
break;
}
}
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) ||
(AcquireMagickResource(HeightResource,image->rows) == MagickFalse))
ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit");
/*
Attach persistent pixel cache.
*/
status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception);
if (status == MagickFalse)
ThrowReaderException(CacheError,"UnableToPersistPixelCache");
/*
Proceed to next image.
*/
do
{
c=ReadBlobByte(image);
} while ((isgraph(c) == MagickFalse) && (c != EOF));
if (c != EOF)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (c != EOF);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/546'</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 Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowPCXException(severity,tag) \
{ \
if (scanline != (unsigned char *) NULL) \
scanline=(unsigned char *) RelinquishMagickMemory(scanline); \
if (pixel_info != (MemoryInfo *) NULL) \
pixel_info=RelinquishVirtualMemory(pixel_info); \
if (page_table != (MagickOffsetType *) NULL) \
page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table); \
ThrowReaderException(severity,tag); \
}
Image
*image;
int
bits,
id,
mask;
MagickBooleanType
status;
MagickOffsetType
offset,
*page_table;
MemoryInfo
*pixel_info;
PCXInfo
pcx_info;
register ssize_t
x;
register Quantum
*q;
register ssize_t
i;
register unsigned char
*p,
*r;
size_t
one,
pcx_packets;
ssize_t
count,
y;
unsigned char
packet,
pcx_colormap[768],
*pixels,
*scanline;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Determine if this a PCX file.
*/
page_table=(MagickOffsetType *) NULL;
scanline=(unsigned char *) NULL;
pixel_info=(MemoryInfo *) NULL;
if (LocaleCompare(image_info->magick,"DCX") == 0)
{
size_t
magic;
/*
Read the DCX page table.
*/
magic=ReadBlobLSBLong(image);
if (magic != 987654321)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL,
sizeof(*page_table));
if (page_table == (MagickOffsetType *) NULL)
ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed");
for (id=0; id < 1024; id++)
{
page_table[id]=(MagickOffsetType) ReadBlobLSBLong(image);
if (page_table[id] == 0)
break;
}
}
if (page_table != (MagickOffsetType *) NULL)
{
offset=SeekBlob(image,(MagickOffsetType) page_table[0],SEEK_SET);
if (offset < 0)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,1,&pcx_info.identifier);
for (id=1; id < 1024; id++)
{
int
bits_per_pixel;
/*
Verify PCX identifier.
*/
pcx_info.version=(unsigned char) ReadBlobByte(image);
if ((count != 1) || (pcx_info.identifier != 0x0a))
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_info.encoding=(unsigned char) ReadBlobByte(image);
bits_per_pixel=ReadBlobByte(image);
if (bits_per_pixel == -1)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_info.bits_per_pixel=(unsigned char) bits_per_pixel;
pcx_info.left=ReadBlobLSBShort(image);
pcx_info.top=ReadBlobLSBShort(image);
pcx_info.right=ReadBlobLSBShort(image);
pcx_info.bottom=ReadBlobLSBShort(image);
pcx_info.horizontal_resolution=ReadBlobLSBShort(image);
pcx_info.vertical_resolution=ReadBlobLSBShort(image);
/*
Read PCX raster colormap.
*/
image->columns=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.right-
pcx_info.left)+1UL;
image->rows=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.bottom-
pcx_info.top)+1UL;
if ((image->columns == 0) || (image->rows == 0) ||
((pcx_info.bits_per_pixel != 1) && (pcx_info.bits_per_pixel != 2) &&
(pcx_info.bits_per_pixel != 4) && (pcx_info.bits_per_pixel != 8)))
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
image->depth=pcx_info.bits_per_pixel;
image->units=PixelsPerInchResolution;
image->resolution.x=(double) pcx_info.horizontal_resolution;
image->resolution.y=(double) pcx_info.vertical_resolution;
image->colors=16;
count=ReadBlob(image,3*image->colors,pcx_colormap);
if (count != (ssize_t) (3*image->colors))
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_info.reserved=(unsigned char) ReadBlobByte(image);
pcx_info.planes=(unsigned char) ReadBlobByte(image);
if (pcx_info.planes == 0)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
if ((pcx_info.bits_per_pixel*pcx_info.planes) >= 64)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
one=1;
if ((pcx_info.bits_per_pixel != 8) || (pcx_info.planes == 1))
if ((pcx_info.version == 3) || (pcx_info.version == 5) ||
((pcx_info.bits_per_pixel*pcx_info.planes) == 1))
image->colors=(size_t) MagickMin(one << (1UL*
(pcx_info.bits_per_pixel*pcx_info.planes)),256UL);
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed");
if ((pcx_info.bits_per_pixel >= 8) && (pcx_info.planes != 1))
image->storage_class=DirectClass;
p=pcx_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
}
pcx_info.bytes_per_line=ReadBlobLSBShort(image);
pcx_info.palette_info=ReadBlobLSBShort(image);
pcx_info.horizontal_screensize=ReadBlobLSBShort(image);
pcx_info.vertical_screensize=ReadBlobLSBShort(image);
for (i=0; i < 54; i++)
(void) ReadBlobByte(image);
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Read image data.
*/
if (HeapOverflowSanityCheck(image->rows, (size_t) pcx_info.bytes_per_line) != MagickFalse)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_packets=(size_t) image->rows*pcx_info.bytes_per_line;
if (HeapOverflowSanityCheck(pcx_packets, (size_t) pcx_info.planes) != MagickFalse)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
pcx_packets=(size_t) pcx_packets*pcx_info.planes;
if ((size_t) (pcx_info.bits_per_pixel*pcx_info.planes*image->columns) >
(pcx_packets*8U))
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
scanline=(unsigned char *) AcquireQuantumMemory(MagickMax(image->columns,
pcx_info.bytes_per_line),MagickMax(8,pcx_info.planes)*sizeof(*scanline));
pixel_info=AcquireVirtualMemory(pcx_packets,2*sizeof(*pixels));
if ((scanline == (unsigned char *) NULL) ||
(pixel_info == (MemoryInfo *) NULL))
{
if (scanline != (unsigned char *) NULL)
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowPCXException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Uncompress image data.
*/
p=pixels;
if (pcx_info.encoding == 0)
while (pcx_packets != 0)
{
packet=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
*p++=packet;
pcx_packets--;
}
else
while (pcx_packets != 0)
{
packet=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
if ((packet & 0xc0) != 0xc0)
{
*p++=packet;
pcx_packets--;
continue;
}
count=(ssize_t) (packet & 0x3f);
packet=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
for ( ; count != 0; count--)
{
*p++=packet;
pcx_packets--;
if (pcx_packets == 0)
break;
}
}
if (image->storage_class == DirectClass)
image->alpha_trait=pcx_info.planes > 3 ? BlendPixelTrait :
UndefinedPixelTrait;
else
if ((pcx_info.version == 5) ||
((pcx_info.bits_per_pixel*pcx_info.planes) == 1))
{
/*
Initialize image colormap.
*/
if (image->colors > 256)
ThrowPCXException(CorruptImageError,"ColormapExceeds256Colors");
if ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)
{
/*
Monochrome colormap.
*/
image->colormap[0].red=(Quantum) 0;
image->colormap[0].green=(Quantum) 0;
image->colormap[0].blue=(Quantum) 0;
image->colormap[1].red=QuantumRange;
image->colormap[1].green=QuantumRange;
image->colormap[1].blue=QuantumRange;
}
else
if (image->colors > 16)
{
/*
256 color images have their color map at the end of the file.
*/
pcx_info.colormap_signature=(unsigned char) ReadBlobByte(image);
count=ReadBlob(image,3*image->colors,pcx_colormap);
p=pcx_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p++);
image->colormap[i].green=ScaleCharToQuantum(*p++);
image->colormap[i].blue=ScaleCharToQuantum(*p++);
}
}
}
/*
Convert PCX raster image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(y*pcx_info.bytes_per_line*pcx_info.planes);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
r=scanline;
if (image->storage_class == DirectClass)
for (i=0; i < pcx_info.planes; i++)
{
r=scanline+i;
for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
{
switch (i)
{
case 0:
{
*r=(*p++);
break;
}
case 1:
{
*r=(*p++);
break;
}
case 2:
{
*r=(*p++);
break;
}
case 3:
default:
{
*r=(*p++);
break;
}
}
r+=pcx_info.planes;
}
}
else
if (pcx_info.planes > 1)
{
for (x=0; x < (ssize_t) image->columns; x++)
*r++=0;
for (i=0; i < pcx_info.planes; i++)
{
r=scanline;
for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
{
bits=(*p++);
for (mask=0x80; mask != 0; mask>>=1)
{
if (bits & mask)
*r|=1 << i;
r++;
}
}
}
}
else
switch (pcx_info.bits_per_pixel)
{
case 1:
{
register ssize_t
bit;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=7; bit >= 0; bit--)
*r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00);
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=7; bit >= (ssize_t) (8-(image->columns % 8)); bit--)
*r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00);
p++;
}
break;
}
case 2:
{
for (x=0; x < ((ssize_t) image->columns-3); x+=4)
{
*r++=(*p >> 6) & 0x3;
*r++=(*p >> 4) & 0x3;
*r++=(*p >> 2) & 0x3;
*r++=(*p) & 0x3;
p++;
}
if ((image->columns % 4) != 0)
{
for (i=3; i >= (ssize_t) (4-(image->columns % 4)); i--)
*r++=(unsigned char) ((*p >> (i*2)) & 0x03);
p++;
}
break;
}
case 4:
{
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
*r++=(*p >> 4) & 0xf;
*r++=(*p) & 0xf;
p++;
}
if ((image->columns % 2) != 0)
*r++=(*p++ >> 4) & 0xf;
break;
}
case 8:
{
(void) CopyMagickMemory(r,p,image->columns);
break;
}
default:
break;
}
/*
Transfer image scanline.
*/
r=scanline;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->storage_class == PseudoClass)
SetPixelIndex(image,*r++,q);
else
{
SetPixelRed(image,ScaleCharToQuantum(*r++),q);
SetPixelGreen(image,ScaleCharToQuantum(*r++),q);
SetPixelBlue(image,ScaleCharToQuantum(*r++),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*r++),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (page_table == (MagickOffsetType *) NULL)
break;
if (page_table[id] == 0)
break;
offset=SeekBlob(image,(MagickOffsetType) page_table[id],SEEK_SET);
if (offset < 0)
ThrowPCXException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,1,&pcx_info.identifier);
if ((count != 0) && (pcx_info.identifier == 0x0a))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
if (page_table != (MagickOffsetType *) NULL)
page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/536'</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 Image *ReadMIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define BZipMaxExtent(x) ((x)+((x)/100)+600)
#define LZMAMaxExtent(x) ((x)+((x)/3)+128)
#define ZipMaxExtent(x) ((x)+(((x)+7) >> 3)+(((x)+63) >> 6)+11)
#if defined(MAGICKCORE_BZLIB_DELEGATE)
bz_stream
bzip_info;
#endif
char
id[MagickPathExtent],
keyword[MagickPathExtent],
*options;
const unsigned char
*p;
double
version;
GeometryInfo
geometry_info;
Image
*image;
int
c;
LinkedListInfo
*profiles;
#if defined(MAGICKCORE_LZMA_DELEGATE)
lzma_stream
initialize_lzma = LZMA_STREAM_INIT,
lzma_info;
lzma_allocator
allocator;
#endif
MagickBooleanType
status;
PixelInfo
pixel;
MagickStatusType
flags;
QuantumFormatType
quantum_format;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
compress_extent,
length,
packet_size;
ssize_t
count;
unsigned char
*compress_pixels,
*pixels;
size_t
colors;
ssize_t
y;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
z_stream
zip_info;
#endif
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Decode image header; header terminates one character beyond a ':'.
*/
c=ReadBlobByte(image);
if (c == EOF)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
*id='\0';
(void) ResetMagickMemory(keyword,0,sizeof(keyword));
version=0.0;
(void) version;
do
{
/*
Decode image header; header terminates one character beyond a ':'.
*/
length=MagickPathExtent;
options=AcquireString((char *) NULL);
quantum_format=UndefinedQuantumFormat;
profiles=(LinkedListInfo *) NULL;
colors=0;
image->depth=8UL;
image->compression=NoCompression;
while ((isgraph(c) != MagickFalse) && (c != (int) ':'))
{
register char
*p;
if (c == (int) '{')
{
char
*comment;
/*
Read comment-- any text between { }.
*/
length=MagickPathExtent;
comment=AcquireString((char *) NULL);
for (p=comment; comment != (char *) NULL; p++)
{
c=ReadBlobByte(image);
if (c == (int) '\\')
c=ReadBlobByte(image);
else
if ((c == EOF) || (c == (int) '}'))
break;
if ((size_t) (p-comment+1) >= length)
{
*p='\0';
length<<=1;
comment=(char *) ResizeQuantumMemory(comment,length+
MagickPathExtent,sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=(char) c;
}
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
*p='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
c=ReadBlobByte(image);
}
else
if (isalnum(c) != MagickFalse)
{
/*
Get the keyword.
*/
length=MagickPathExtent;
p=keyword;
do
{
if (c == (int) '=')
break;
if ((size_t) (p-keyword) < (MagickPathExtent-1))
*p++=(char) c;
c=ReadBlobByte(image);
} while (c != EOF);
*p='\0';
p=options;
while ((isspace((int) ((unsigned char) c)) != 0) && (c != EOF))
c=ReadBlobByte(image);
if (c == (int) '=')
{
/*
Get the keyword value.
*/
c=ReadBlobByte(image);
while ((c != (int) '}') && (c != EOF))
{
if ((size_t) (p-options+1) >= length)
{
*p='\0';
length<<=1;
options=(char *) ResizeQuantumMemory(options,length+
MagickPathExtent,sizeof(*options));
if (options == (char *) NULL)
break;
p=options+strlen(options);
}
*p++=(char) c;
c=ReadBlobByte(image);
if (c == '\\')
{
c=ReadBlobByte(image);
if (c == (int) '}')
{
*p++=(char) c;
c=ReadBlobByte(image);
}
}
if (*options != '{')
if (isspace((int) ((unsigned char) c)) != 0)
break;
}
if (options == (char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
*p='\0';
if (*options == '{')
(void) CopyMagickString(options,options+1,strlen(options));
/*
Assign a value to the specified keyword.
*/
switch (*keyword)
{
case 'a':
case 'A':
{
if (LocaleCompare(keyword,"alpha-trait") == 0)
{
ssize_t
alpha_trait;
alpha_trait=ParseCommandOption(MagickPixelTraitOptions,
MagickFalse,options);
if (alpha_trait < 0)
break;
image->alpha_trait=(PixelTrait) alpha_trait;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'b':
case 'B':
{
if (LocaleCompare(keyword,"background-color") == 0)
{
(void) QueryColorCompliance(options,AllCompliance,
&image->background_color,exception);
break;
}
if (LocaleCompare(keyword,"blue-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.blue_primary.x=geometry_info.rho;
image->chromaticity.blue_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.blue_primary.y=
image->chromaticity.blue_primary.x;
break;
}
if (LocaleCompare(keyword,"border-color") == 0)
{
(void) QueryColorCompliance(options,AllCompliance,
&image->border_color,exception);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'c':
case 'C':
{
if (LocaleCompare(keyword,"class") == 0)
{
ssize_t
storage_class;
storage_class=ParseCommandOption(MagickClassOptions,
MagickFalse,options);
if (storage_class < 0)
break;
image->storage_class=(ClassType) storage_class;
break;
}
if (LocaleCompare(keyword,"colors") == 0)
{
colors=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
ssize_t
colorspace;
colorspace=ParseCommandOption(MagickColorspaceOptions,
MagickFalse,options);
if (colorspace < 0)
break;
image->colorspace=(ColorspaceType) colorspace;
break;
}
if (LocaleCompare(keyword,"compression") == 0)
{
ssize_t
compression;
compression=ParseCommandOption(MagickCompressOptions,
MagickFalse,options);
if (compression < 0)
break;
image->compression=(CompressionType) compression;
break;
}
if (LocaleCompare(keyword,"columns") == 0)
{
image->columns=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'd':
case 'D':
{
if (LocaleCompare(keyword,"delay") == 0)
{
image->delay=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"depth") == 0)
{
image->depth=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"dispose") == 0)
{
ssize_t
dispose;
dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,
options);
if (dispose < 0)
break;
image->dispose=(DisposeType) dispose;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'e':
case 'E':
{
if (LocaleCompare(keyword,"endian") == 0)
{
ssize_t
endian;
endian=ParseCommandOption(MagickEndianOptions,MagickFalse,
options);
if (endian < 0)
break;
image->endian=(EndianType) endian;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'g':
case 'G':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
image->gamma=StringToDouble(options,(char **) NULL);
break;
}
if (LocaleCompare(keyword,"gravity") == 0)
{
ssize_t
gravity;
gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,
options);
if (gravity < 0)
break;
image->gravity=(GravityType) gravity;
break;
}
if (LocaleCompare(keyword,"green-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.green_primary.x=geometry_info.rho;
image->chromaticity.green_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.green_primary.y=
image->chromaticity.green_primary.x;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'i':
case 'I':
{
if (LocaleCompare(keyword,"id") == 0)
{
(void) CopyMagickString(id,options,MagickPathExtent);
break;
}
if (LocaleCompare(keyword,"iterations") == 0)
{
image->iterations=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'm':
case 'M':
{
if (LocaleCompare(keyword,"matte") == 0)
{
ssize_t
matte;
matte=ParseCommandOption(MagickBooleanOptions,MagickFalse,
options);
if (matte < 0)
break;
image->alpha_trait=matte == 0 ? UndefinedPixelTrait :
BlendPixelTrait;
break;
}
if (LocaleCompare(keyword,"mattecolor") == 0)
{
(void) QueryColorCompliance(options,AllCompliance,
&image->matte_color,exception);
break;
}
if (LocaleCompare(keyword,"montage") == 0)
{
(void) CloneString(&image->montage,options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'o':
case 'O':
{
if (LocaleCompare(keyword,"orientation") == 0)
{
ssize_t
orientation;
orientation=ParseCommandOption(MagickOrientationOptions,
MagickFalse,options);
if (orientation < 0)
break;
image->orientation=(OrientationType) orientation;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'p':
case 'P':
{
if (LocaleCompare(keyword,"page") == 0)
{
char
*geometry;
geometry=GetPageGeometry(options);
(void) ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
break;
}
if (LocaleCompare(keyword,"pixel-intensity") == 0)
{
ssize_t
intensity;
intensity=ParseCommandOption(MagickPixelIntensityOptions,
MagickFalse,options);
if (intensity < 0)
break;
image->intensity=(PixelIntensityMethod) intensity;
break;
}
if ((LocaleNCompare(keyword,"profile:",8) == 0) ||
(LocaleNCompare(keyword,"profile-",8) == 0))
{
StringInfo
*profile;
if (profiles == (LinkedListInfo *) NULL)
profiles=NewLinkedList(0);
(void) AppendValueToLinkedList(profiles,
AcquireString(keyword+8));
profile=BlobToStringInfo((const void *) NULL,(size_t)
StringToLong(options));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
(void) SetImageProfile(image,keyword+8,profile,exception);
profile=DestroyStringInfo(profile);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'q':
case 'Q':
{
if (LocaleCompare(keyword,"quality") == 0)
{
image->quality=StringToUnsignedLong(options);
break;
}
if ((LocaleCompare(keyword,"quantum-format") == 0) ||
(LocaleCompare(keyword,"quantum:format") == 0))
{
ssize_t
format;
format=ParseCommandOption(MagickQuantumFormatOptions,
MagickFalse,options);
if (format < 0)
break;
quantum_format=(QuantumFormatType) format;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'r':
case 'R':
{
if (LocaleCompare(keyword,"red-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.red_primary.x=geometry_info.rho;
image->chromaticity.red_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.red_primary.y=
image->chromaticity.red_primary.x;
break;
}
if (LocaleCompare(keyword,"rendering-intent") == 0)
{
ssize_t
rendering_intent;
rendering_intent=ParseCommandOption(MagickIntentOptions,
MagickFalse,options);
if (rendering_intent < 0)
break;
image->rendering_intent=(RenderingIntent) rendering_intent;
break;
}
if (LocaleCompare(keyword,"resolution") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
break;
}
if (LocaleCompare(keyword,"rows") == 0)
{
image->rows=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 's':
case 'S':
{
if (LocaleCompare(keyword,"scene") == 0)
{
image->scene=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 't':
case 'T':
{
if (LocaleCompare(keyword,"ticks-per-second") == 0)
{
image->ticks_per_second=(ssize_t) StringToLong(options);
break;
}
if (LocaleCompare(keyword,"tile-offset") == 0)
{
char
*geometry;
geometry=GetPageGeometry(options);
(void) ParseAbsoluteGeometry(geometry,&image->tile_offset);
geometry=DestroyString(geometry);
break;
}
if (LocaleCompare(keyword,"type") == 0)
{
ssize_t
type;
type=ParseCommandOption(MagickTypeOptions,MagickFalse,
options);
if (type < 0)
break;
image->type=(ImageType) type;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'u':
case 'U':
{
if (LocaleCompare(keyword,"units") == 0)
{
ssize_t
units;
units=ParseCommandOption(MagickResolutionOptions,
MagickFalse,options);
if (units < 0)
break;
image->units=(ResolutionType) units;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'v':
case 'V':
{
if (LocaleCompare(keyword,"version") == 0)
{
version=StringToDouble(options,(char **) NULL);
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
case 'w':
case 'W':
{
if (LocaleCompare(keyword,"white-point") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.white_point.x=geometry_info.rho;
image->chromaticity.white_point.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.white_point.y=
image->chromaticity.white_point.x;
break;
}
(void) SetImageProperty(image,keyword,options,exception);
break;
}
default:
{
(void) SetImageProperty(image,keyword,options,exception);
break;
}
}
}
else
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
options=DestroyString(options);
(void) ReadBlobByte(image);
/*
Verify that required image information is defined.
*/
if ((LocaleCompare(id,"ImageMagick") != 0) ||
(image->storage_class == UndefinedClass) ||
(image->compression == UndefinedCompression) ||
(image->colorspace == UndefinedColorspace) ||
(image->columns == 0) || (image->rows == 0))
{
if (image->previous == (Image *) NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
DeleteImageFromList(&image);
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"ImproperImageHeader","`%s'",image->filename);
break;
}
if (image->montage != (char *) NULL)
{
register char
*p;
/*
Image directory.
*/
length=MagickPathExtent;
image->directory=AcquireString((char *) NULL);
p=image->directory;
do
{
*p='\0';
if ((strlen(image->directory)+MagickPathExtent) >= length)
{
/*
Allocate more memory for the image directory.
*/
length<<=1;
image->directory=(char *) ResizeQuantumMemory(image->directory,
length+MagickPathExtent,sizeof(*image->directory));
if (image->directory == (char *) NULL)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
p=image->directory+strlen(image->directory);
}
c=ReadBlobByte(image);
*p++=(char) c;
} while (c != (int) '\0');
}
if (profiles != (LinkedListInfo *) NULL)
{
const char
*name;
const StringInfo
*profile;
/*
Read image profiles.
*/
ResetLinkedListIterator(profiles);
name=(const char *) GetNextValueInLinkedList(profiles);
while (name != (const char *) NULL)
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
register unsigned char
*p;
p=GetStringInfoDatum(profile);
count=ReadBlob(image,GetStringInfoLength(profile),p);
(void) count;
}
name=(const char *) GetNextValueInLinkedList(profiles);
}
profiles=DestroyLinkedList(profiles,RelinquishMagickMemory);
}
image->depth=GetImageQuantumDepth(image,MagickFalse);
if (image->storage_class == PseudoClass)
{
/*
Create image colormap.
*/
status=AcquireImageColormap(image,colors != 0 ? colors : 256,exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (colors != 0)
{
size_t
packet_size;
unsigned char
*colormap;
/*
Read image colormap from file.
*/
packet_size=(size_t) (3UL*image->depth/8UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
packet_size*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,packet_size*image->colors,colormap);
p=colormap;
switch (image->depth)
{
default:
ThrowReaderException(CorruptImageError,
"ImageDepthNotSupported");
case 8:
{
unsigned char
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushCharPixel(p,&pixel);
image->colormap[i].red=ScaleCharToQuantum(pixel);
p=PushCharPixel(p,&pixel);
image->colormap[i].green=ScaleCharToQuantum(pixel);
p=PushCharPixel(p,&pixel);
image->colormap[i].blue=ScaleCharToQuantum(pixel);
}
break;
}
case 16:
{
unsigned short
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].red=ScaleShortToQuantum(pixel);
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].green=ScaleShortToQuantum(pixel);
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].blue=ScaleShortToQuantum(pixel);
}
break;
}
case 32:
{
unsigned int
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].red=ScaleLongToQuantum(pixel);
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].green=ScaleLongToQuantum(pixel);
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].blue=ScaleLongToQuantum(pixel);
}
break;
}
}
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
}
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate image pixels.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (quantum_format != UndefinedQuantumFormat)
{
status=SetQuantumFormat(image,quantum_info,quantum_format);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
packet_size=(size_t) (quantum_info->depth/8);
if (image->storage_class == DirectClass)
packet_size=(size_t) (3*quantum_info->depth/8);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
packet_size=quantum_info->depth/8;
if (image->alpha_trait != UndefinedPixelTrait)
packet_size+=quantum_info->depth/8;
if (image->colorspace == CMYKColorspace)
packet_size+=quantum_info->depth/8;
if (image->compression == RLECompression)
packet_size++;
compress_extent=MagickMax(MagickMax(BZipMaxExtent(packet_size*
image->columns),LZMAMaxExtent(packet_size*image->columns)),
ZipMaxExtent(packet_size*image->columns));
compress_pixels=(unsigned char *) AcquireQuantumMemory(compress_extent,
sizeof(*compress_pixels));
if (compress_pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Read image pixels.
*/
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=RGBAQuantum;
if (image->colorspace == CMYKColorspace)
{
quantum_type=CMYKQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=CMYKAQuantum;
}
if (IsGrayColorspace(image->colorspace) != MagickFalse)
{
quantum_type=GrayQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=GrayAlphaQuantum;
}
if (image->storage_class == PseudoClass)
{
quantum_type=IndexQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=IndexAlphaQuantum;
}
status=MagickTrue;
GetPixelInfo(image,&pixel);
#if defined(MAGICKCORE_BZLIB_DELEGATE)
(void) ResetMagickMemory(&bzip_info,0,sizeof(bzip_info));
#endif
#if defined(MAGICKCORE_LZMA_DELEGATE)
(void) ResetMagickMemory(&allocator,0,sizeof(allocator));
#endif
#if defined(MAGICKCORE_ZLIB_DELEGATE)
(void) ResetMagickMemory(&zip_info,0,sizeof(zip_info));
#endif
switch (image->compression)
{
#if defined(MAGICKCORE_BZLIB_DELEGATE)
case BZipCompression:
{
int
code;
bzip_info.bzalloc=AcquireBZIPMemory;
bzip_info.bzfree=RelinquishBZIPMemory;
bzip_info.opaque=(void *) NULL;
code=BZ2_bzDecompressInit(&bzip_info,(int) image_info->verbose,
MagickFalse);
if (code != BZ_OK)
status=MagickFalse;
break;
}
#endif
#if defined(MAGICKCORE_LZMA_DELEGATE)
case LZMACompression:
{
int
code;
allocator.alloc=AcquireLZMAMemory;
allocator.free=RelinquishLZMAMemory;
lzma_info=initialize_lzma;
lzma_info.allocator=(&allocator);
code=lzma_auto_decoder(&lzma_info,-1,0);
if (code != LZMA_OK)
status=MagickFalse;
break;
}
#endif
#if defined(MAGICKCORE_ZLIB_DELEGATE)
case LZWCompression:
case ZipCompression:
{
int
code;
zip_info.zalloc=AcquireZIPMemory;
zip_info.zfree=RelinquishZIPMemory;
zip_info.opaque=(voidpf) NULL;
code=inflateInit(&zip_info);
if (code != Z_OK)
status=MagickFalse;
break;
}
#endif
case RLECompression:
break;
default:
break;
}
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
switch (image->compression)
{
#if defined(MAGICKCORE_BZLIB_DELEGATE)
case BZipCompression:
{
bzip_info.next_out=(char *) pixels;
bzip_info.avail_out=(unsigned int) (packet_size*image->columns);
do
{
int
code;
if (bzip_info.avail_in == 0)
{
bzip_info.next_in=(char *) compress_pixels;
length=(size_t) BZipMaxExtent(packet_size*image->columns);
if (version != 0.0)
length=(size_t) ReadBlobMSBLong(image);
if (length > compress_extent)
{
(void) BZ2_bzDecompressEnd(&bzip_info);
ThrowReaderException(CorruptImageError,
"UnableToReadImageData");
}
bzip_info.avail_in=(unsigned int) ReadBlob(image,length,
(unsigned char *) bzip_info.next_in);
}
code=BZ2_bzDecompress(&bzip_info);
if (code < 0)
{
status=MagickFalse;
break;
}
if (code == BZ_STREAM_END)
break;
} while (bzip_info.avail_out != 0);
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
#endif
#if defined(MAGICKCORE_LZMA_DELEGATE)
case LZMACompression:
{
lzma_info.next_out=pixels;
lzma_info.avail_out=packet_size*image->columns;
do
{
int
code;
if (lzma_info.avail_in == 0)
{
lzma_info.next_in=compress_pixels;
length=(size_t) ReadBlobMSBLong(image);
if (length > compress_extent)
{
lzma_end(&lzma_info);
ThrowReaderException(CorruptImageError,
"UnableToReadImageData");
}
lzma_info.avail_in=(unsigned int) ReadBlob(image,length,
(unsigned char *) lzma_info.next_in);
}
code=lzma_code(&lzma_info,LZMA_RUN);
if (code < 0)
{
status=MagickFalse;
break;
}
if (code == LZMA_STREAM_END)
break;
} while (lzma_info.avail_out != 0);
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
#endif
#if defined(MAGICKCORE_ZLIB_DELEGATE)
case LZWCompression:
case ZipCompression:
{
zip_info.next_out=pixels;
zip_info.avail_out=(uInt) (packet_size*image->columns);
do
{
int
code;
if (zip_info.avail_in == 0)
{
zip_info.next_in=compress_pixels;
length=(size_t) ZipMaxExtent(packet_size*image->columns);
if (version != 0.0)
length=(size_t) ReadBlobMSBLong(image);
if (length > compress_extent)
{
(void) inflateEnd(&zip_info);
ThrowReaderException(CorruptImageError,
"UnableToReadImageData");
}
zip_info.avail_in=(unsigned int) ReadBlob(image,length,
zip_info.next_in);
}
code=inflate(&zip_info,Z_SYNC_FLUSH);
if (code < 0)
{
status=MagickFalse;
break;
}
if (code == Z_STREAM_END)
break;
} while (zip_info.avail_out != 0);
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
#endif
case RLECompression:
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (length == 0)
{
count=ReadBlob(image,packet_size,pixels);
PushRunlengthPacket(image,pixels,&length,&pixel,exception);
}
length--;
if (image->storage_class == PseudoClass)
SetPixelIndex(image,ClampToQuantum(pixel.index),q);
else
{
SetPixelRed(image,ClampToQuantum(pixel.red),q);
SetPixelGreen(image,ClampToQuantum(pixel.green),q);
SetPixelBlue(image,ClampToQuantum(pixel.blue),q);
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,ClampToQuantum(pixel.black),q);
}
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
break;
}
default:
{
count=ReadBlob(image,packet_size*image->columns,pixels);
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
switch (image->compression)
{
#if defined(MAGICKCORE_BZLIB_DELEGATE)
case BZipCompression:
{
int
code;
if (version == 0.0)
{
MagickOffsetType
offset;
offset=SeekBlob(image,-((MagickOffsetType)
bzip_info.avail_in),SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
code=BZ2_bzDecompressEnd(&bzip_info);
if (code != BZ_OK)
status=MagickFalse;
break;
}
#endif
#if defined(MAGICKCORE_LZMA_DELEGATE)
case LZMACompression:
{
int
code;
code=lzma_code(&lzma_info,LZMA_FINISH);
if ((code != LZMA_STREAM_END) && (code != LZMA_OK))
status=MagickFalse;
lzma_end(&lzma_info);
break;
}
#endif
#if defined(MAGICKCORE_ZLIB_DELEGATE)
case LZWCompression:
case ZipCompression:
{
int
code;
if (version == 0.0)
{
MagickOffsetType
offset;
offset=SeekBlob(image,-((MagickOffsetType) zip_info.avail_in),
SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
code=inflateEnd(&zip_info);
if (code != LZMA_OK)
status=MagickFalse;
break;
}
#endif
default:
break;
}
quantum_info=DestroyQuantumInfo(quantum_info);
compress_pixels=(unsigned char *) RelinquishMagickMemory(compress_pixels);
if (((y != (ssize_t) image->rows)) || (status == MagickFalse))
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
do
{
c=ReadBlobByte(image);
} while ((isgraph(c) == MagickFalse) && (c != EOF));
if (c != EOF)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (c != EOF);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/545'</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: psf_binheader_writef (SF_PRIVATE *psf, const char *format, ...)
{ va_list argptr ;
sf_count_t countdata ;
unsigned long longdata ;
unsigned int data ;
float floatdata ;
double doubledata ;
void *bindata ;
size_t size ;
char c, *strptr ;
int count = 0, trunc_8to4 ;
trunc_8to4 = SF_FALSE ;
va_start (argptr, format) ;
while ((c = *format++))
{
if (psf->header.indx + 16 >= psf->header.len && psf_bump_header_allocation (psf, 16))
return count ;
switch (c)
{ case ' ' : /* Do nothing. Just used to space out format string. */
break ;
case 'e' : /* All conversions are now from LE to host. */
psf->rwf_endian = SF_ENDIAN_LITTLE ;
break ;
case 'E' : /* All conversions are now from BE to host. */
psf->rwf_endian = SF_ENDIAN_BIG ;
break ;
case 't' : /* All 8 byte values now get written as 4 bytes. */
trunc_8to4 = SF_TRUE ;
break ;
case 'T' : /* All 8 byte values now get written as 8 bytes. */
trunc_8to4 = SF_FALSE ;
break ;
case 'm' :
data = va_arg (argptr, unsigned int) ;
header_put_marker (psf, data) ;
count += 4 ;
break ;
case '1' :
data = va_arg (argptr, unsigned int) ;
header_put_byte (psf, data) ;
count += 1 ;
break ;
case '2' :
data = va_arg (argptr, unsigned int) ;
if (psf->rwf_endian == SF_ENDIAN_BIG)
{ header_put_be_short (psf, data) ;
}
else
{ header_put_le_short (psf, data) ;
} ;
count += 2 ;
break ;
case '3' : /* tribyte */
data = va_arg (argptr, unsigned int) ;
if (psf->rwf_endian == SF_ENDIAN_BIG)
{ header_put_be_3byte (psf, data) ;
}
else
{ header_put_le_3byte (psf, data) ;
} ;
count += 3 ;
break ;
case '4' :
data = va_arg (argptr, unsigned int) ;
if (psf->rwf_endian == SF_ENDIAN_BIG)
{ header_put_be_int (psf, data) ;
}
else
{ header_put_le_int (psf, data) ;
} ;
count += 4 ;
break ;
case '8' :
countdata = va_arg (argptr, sf_count_t) ;
if (psf->rwf_endian == SF_ENDIAN_BIG && trunc_8to4 == SF_FALSE)
{ header_put_be_8byte (psf, countdata) ;
count += 8 ;
}
else if (psf->rwf_endian == SF_ENDIAN_LITTLE && trunc_8to4 == SF_FALSE)
{ header_put_le_8byte (psf, countdata) ;
count += 8 ;
}
else if (psf->rwf_endian == SF_ENDIAN_BIG && trunc_8to4 == SF_TRUE)
{ longdata = countdata & 0xFFFFFFFF ;
header_put_be_int (psf, longdata) ;
count += 4 ;
}
else if (psf->rwf_endian == SF_ENDIAN_LITTLE && trunc_8to4 == SF_TRUE)
{ longdata = countdata & 0xFFFFFFFF ;
header_put_le_int (psf, longdata) ;
count += 4 ;
}
break ;
case 'f' :
/* Floats are passed as doubles. Is this always true? */
floatdata = (float) va_arg (argptr, double) ;
if (psf->rwf_endian == SF_ENDIAN_BIG)
float32_be_write (floatdata, psf->header.ptr + psf->header.indx) ;
else
float32_le_write (floatdata, psf->header.ptr + psf->header.indx) ;
psf->header.indx += 4 ;
count += 4 ;
break ;
case 'd' :
doubledata = va_arg (argptr, double) ;
if (psf->rwf_endian == SF_ENDIAN_BIG)
double64_be_write (doubledata, psf->header.ptr + psf->header.indx) ;
else
double64_le_write (doubledata, psf->header.ptr + psf->header.indx) ;
psf->header.indx += 8 ;
count += 8 ;
break ;
case 's' :
/* Write a C string (guaranteed to have a zero terminator). */
strptr = va_arg (argptr, char *) ;
size = strlen (strptr) + 1 ;
size += (size & 1) ;
if (psf->header.indx + (sf_count_t) size >= psf->header.len && psf_bump_header_allocation (psf, 16))
return count ;
if (psf->rwf_endian == SF_ENDIAN_BIG)
header_put_be_int (psf, size) ;
else
header_put_le_int (psf, size) ;
memcpy (&(psf->header.ptr [psf->header.indx]), strptr, size) ;
psf->header.indx += size ;
psf->header.ptr [psf->header.indx - 1] = 0 ;
count += 4 + size ;
break ;
case 'S' :
/*
** Write an AIFF style string (no zero terminator but possibly
** an extra pad byte if the string length is odd).
*/
strptr = va_arg (argptr, char *) ;
size = strlen (strptr) ;
if (psf->header.indx + (sf_count_t) size > psf->header.len && psf_bump_header_allocation (psf, size))
return count ;
if (psf->rwf_endian == SF_ENDIAN_BIG)
header_put_be_int (psf, size) ;
else
header_put_le_int (psf, size) ;
memcpy (&(psf->header.ptr [psf->header.indx]), strptr, size + 1) ;
size += (size & 1) ;
psf->header.indx += size ;
psf->header.ptr [psf->header.indx] = 0 ;
count += 4 + size ;
break ;
case 'p' :
/* Write a PASCAL string (as used by AIFF files).
*/
strptr = va_arg (argptr, char *) ;
size = strlen (strptr) ;
size = (size & 1) ? size : size + 1 ;
size = (size > 254) ? 254 : size ;
if (psf->header.indx + (sf_count_t) size > psf->header.len && psf_bump_header_allocation (psf, size))
return count ;
header_put_byte (psf, size) ;
memcpy (&(psf->header.ptr [psf->header.indx]), strptr, size) ;
psf->header.indx += size ;
count += 1 + size ;
break ;
case 'b' :
bindata = va_arg (argptr, void *) ;
size = va_arg (argptr, size_t) ;
if (psf->header.indx + (sf_count_t) size > psf->header.len && psf_bump_header_allocation (psf, size))
return count ;
memcpy (&(psf->header.ptr [psf->header.indx]), bindata, size) ;
psf->header.indx += size ;
count += size ;
break ;
case 'z' :
size = va_arg (argptr, size_t) ;
if (psf->header.indx + (sf_count_t) size > psf->header.len && psf_bump_header_allocation (psf, size))
return count ;
count += size ;
while (size)
{ psf->header.ptr [psf->header.indx] = 0 ;
psf->header.indx ++ ;
size -- ;
} ;
break ;
case 'h' :
bindata = va_arg (argptr, void *) ;
memcpy (&(psf->header.ptr [psf->header.indx]), bindata, 16) ;
psf->header.indx += 16 ;
count += 16 ;
break ;
case 'j' : /* Jump forwards/backwards by specified amount. */
size = va_arg (argptr, size_t) ;
if (psf->header.indx + (sf_count_t) size > psf->header.len && psf_bump_header_allocation (psf, size))
return count ;
psf->header.indx += size ;
count += size ;
break ;
case 'o' : /* Jump to specified offset. */
size = va_arg (argptr, size_t) ;
if ((sf_count_t) size >= psf->header.len && psf_bump_header_allocation (psf, size))
return count ;
psf->header.indx = size ;
break ;
default :
psf_log_printf (psf, "*** Invalid format specifier `%c'\n", c) ;
psf->error = SFE_INTERNAL ;
break ;
} ;
} ;
va_end (argptr) ;
return count ;
} /* psf_binheader_writef */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'src/common.c: Fix heap buffer overflows when writing strings in binheader
Fixes the following problems:
1. Case 's' only enlarges the buffer by 16 bytes instead of size bytes.
2. psf_binheader_writef() enlarges the header buffer (if needed) prior to the
big switch statement by an amount (16 bytes) which is enough for all cases
where only a single value gets added. Cases 's', 'S', 'p' however
additionally write an arbitrary length block of data and again enlarge the
buffer to the required amount. However, the required space calculation does
not take into account the size of the length field which gets output before
the data.
3. Buffer size requirement calculation in case 'S' does not account for the
padding byte ("size += (size & 1) ;" happens after the calculation which
uses "size").
4. Case 'S' can overrun the header buffer by 1 byte when no padding is
involved
("memcpy (&(psf->header.ptr [psf->header.indx]), strptr, size + 1) ;" while
the buffer is only guaranteed to have "size" space available).
5. "psf->header.ptr [psf->header.indx] = 0 ;" in case 'S' always writes 1 byte
beyond the space which is guaranteed to be allocated in the header buffer.
6. Case 's' can overrun the provided source string by 1 byte if padding is
involved ("memcpy (&(psf->header.ptr [psf->header.indx]), strptr, size) ;"
where "size" is "strlen (strptr) + 1" (which includes the 0 terminator,
plus optionally another 1 which is padding and not guaranteed to be
readable via the source string pointer).
Closes: https://github.com/erikd/libsndfile/issues/292'</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 get_name(int counter,
unsigned char *pkt, unsigned char *start, unsigned char *max,
unsigned char *output, int output_max, int *output_len,
unsigned char **end, char *name, int *name_len)
{
unsigned char *p;
/* Limit recursion to 10 (this means up to 10 labels in domain name) */
if (counter > 10)
return -EINVAL;
p = start;
while (*p) {
if ((*p & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
uint16_t offset = (*p & 0x3F) * 256 + *(p + 1);
if (offset >= max - pkt)
return -ENOBUFS;
if (!*end)
*end = p + 2;
return get_name(counter + 1, pkt, pkt + offset, max,
output, output_max, output_len, end,
name, name_len);
} else {
unsigned label_len = *p;
if (pkt + label_len > max)
return -ENOBUFS;
if (*output_len > output_max)
return -ENOBUFS;
/*
* We need the original name in order to check
* if this answer is the correct one.
*/
name[(*name_len)++] = label_len;
memcpy(name + *name_len, p + 1, label_len + 1);
*name_len += label_len;
/* We compress the result */
output[0] = NS_CMPRSFLGS;
output[1] = 0x0C;
*output_len = 2;
p += label_len + 1;
if (!*end)
*end = p;
if (p >= max)
return -ENOBUFS;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'dnsproxy: Fix crash on malformed DNS response
If the response query string is malformed, we might access memory
pass the end of "name" variable in parse_response().'</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: setup_arch (char **cmdline_p)
{
unw_init();
ia64_patch_vtop((u64) __start___vtop_patchlist, (u64) __end___vtop_patchlist);
*cmdline_p = __va(ia64_boot_param->command_line);
strlcpy(boot_command_line, *cmdline_p, COMMAND_LINE_SIZE);
efi_init();
io_port_init();
#ifdef CONFIG_IA64_GENERIC
/* machvec needs to be parsed from the command line
* before parse_early_param() is called to ensure
* that ia64_mv is initialised before any command line
* settings may cause console setup to occur
*/
machvec_init_from_cmdline(*cmdline_p);
#endif
parse_early_param();
if (early_console_setup(*cmdline_p) == 0)
mark_bsp_online();
#ifdef CONFIG_ACPI
/* Initialize the ACPI boot-time table parser */
acpi_table_init();
# ifdef CONFIG_ACPI_NUMA
acpi_numa_init();
per_cpu_scan_finalize((cpus_weight(early_cpu_possible_map) == 0 ?
32 : cpus_weight(early_cpu_possible_map)), additional_cpus);
# endif
#else
# ifdef CONFIG_SMP
smp_build_cpu_map(); /* happens, e.g., with the Ski simulator */
# endif
#endif /* CONFIG_APCI_BOOT */
find_memory();
/* process SAL system table: */
ia64_sal_init(__va(efi.sal_systab));
#ifdef CONFIG_SMP
cpu_physical_id(0) = hard_smp_processor_id();
#endif
cpu_init(); /* initialize the bootstrap CPU */
mmu_context_init(); /* initialize context_id bitmap */
check_sal_cache_flush();
#ifdef CONFIG_ACPI
acpi_boot_init();
#endif
#ifdef CONFIG_VT
if (!conswitchp) {
# if defined(CONFIG_DUMMY_CONSOLE)
conswitchp = &dummy_con;
# endif
# if defined(CONFIG_VGA_CONSOLE)
/*
* Non-legacy systems may route legacy VGA MMIO range to system
* memory. vga_con probes the MMIO hole, so memory looks like
* a VGA device to it. The EFI memory map can tell us if it's
* memory so we can avoid this problem.
*/
if (efi_mem_type(0xA0000) != EFI_CONVENTIONAL_MEMORY)
conswitchp = &vga_con;
# endif
}
#endif
/* enable IA-64 Machine Check Abort Handling unless disabled */
if (!nomca)
ia64_mca_init();
platform_setup(cmdline_p);
paging_init();
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '[IA64] Workaround for RSE issue
Problem: An application violating the architectural rules regarding
operation dependencies and having specific Register Stack Engine (RSE)
state at the time of the violation, may result in an illegal operation
fault and invalid RSE state. Such faults may initiate a cascade of
repeated illegal operation faults within OS interruption handlers.
The specific behavior is OS dependent.
Implication: An application causing an illegal operation fault with
specific RSE state may result in a series of illegal operation faults
and an eventual OS stack overflow condition.
Workaround: OS interruption handlers that switch to kernel backing
store implement a check for invalid RSE state to avoid the series
of illegal operation faults.
The core of the workaround is the RSE_WORKAROUND code sequence
inserted into each invocation of the SAVE_MIN_WITH_COVER and
SAVE_MIN_WITH_COVER_R19 macros. This sequence includes hard-coded
constants that depend on the number of stacked physical registers
being 96. The rest of this patch consists of code to disable this
workaround should this not be the case (with the presumption that
if a future Itanium processor increases the number of registers, it
would also remove the need for this patch).
Move the start of the RBS up to a mod32 boundary to avoid some
corner cases.
The dispatch_illegal_op_fault code outgrew the spot it was
squatting in when built with this patch and CONFIG_VIRT_CPU_ACCOUNTING=y
Move it out to the end of the ivt.
Signed-off-by: Tony Luck <[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: messageFindArgument(const message *m, const char *variable)
{
int i;
size_t len;
assert(m != NULL);
assert(variable != NULL);
len = strlen(variable);
for(i = 0; i < m->numberOfArguments; i++) {
const char *ptr;
ptr = messageGetArgument(m, i);
if((ptr == NULL) || (*ptr == '\0'))
continue;
#ifdef CL_DEBUG
cli_dbgmsg("messageFindArgument: compare %lu bytes of %s with %s\n",
(unsigned long)len, variable, ptr);
#endif
if(strncasecmp(ptr, variable, len) == 0) {
ptr = &ptr[len];
while(isspace(*ptr))
ptr++;
if(*ptr != '=') {
cli_dbgmsg("messageFindArgument: no '=' sign found in MIME header '%s' (%s)\n", variable, messageGetArgument(m, i));
return NULL;
}
if((*++ptr == '"') && (strchr(&ptr[1], '"') != NULL)) {
/* Remove any quote characters */
char *ret = cli_strdup(++ptr);
char *p;
if(ret == NULL)
return NULL;
/*
* fix un-quoting of boundary strings from
* header, occurs if boundary was given as
* 'boundary="_Test_";'
*
* At least two quotes in string, assume
* quoted argument
* end string at next quote
*/
if((p = strchr(ret, '"')) != NULL) {
ret[strlen(ret) - 1] = '\0';
*p = '\0';
}
return ret;
}
return cli_strdup(ptr);
}
}
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'bb11797 - fix invalid read in fuzzed mail file.'</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 mspack_fmap_free(void *mem)
{
free(mem);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'fixing potential OOB window write when unpacking chm files'</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 wwunpack(uint8_t *exe, uint32_t exesz, uint8_t *wwsect, struct cli_exe_section *sects, uint16_t scount, uint32_t pe, int desc) {
uint8_t *structs = wwsect + 0x2a1, *compd, *ccur, *unpd, *ucur, bc;
uint32_t src, srcend, szd, bt, bits;
int error=0, i;
cli_dbgmsg("in wwunpack\n");
while (1) {
if (!CLI_ISCONTAINED(wwsect, sects[scount].rsz, structs, 17)) {
cli_dbgmsg("WWPack: Array of structs out of section\n");
break;
}
src = sects[scount].rva - cli_readint32(structs); /* src delta / dst delta - not used / dwords / end of src */
structs+=8;
szd = cli_readint32(structs) * 4;
structs+=4;
srcend = cli_readint32(structs);
structs+=4;
unpd = ucur = exe+src+srcend+4-szd;
if (!szd || !CLI_ISCONTAINED(exe, exesz, unpd, szd)) {
cli_dbgmsg("WWPack: Compressed data out of file\n");
break;
}
cli_dbgmsg("WWP: src: %x, szd: %x, srcend: %x - %x\n", src, szd, srcend, srcend+4-szd);
if (!(compd = cli_malloc(szd))) {
cli_dbgmsg("WWPack: Unable to allocate memory for compd\n");
break;
}
memcpy(compd, unpd, szd);
memset(unpd, -1, szd); /*FIXME*/
ccur=compd;
RESEED;
while(!error) {
uint32_t backbytes, backsize;
uint8_t saved;
BIT;
if (!bits) { /* BYTE copy */
if(ccur-compd>=szd || !CLI_ISCONTAINED(exe, exesz, ucur, 1))
error=1;
else
*ucur++=*ccur++;
continue;
}
BITS(2);
if(bits==3) { /* WORD backcopy */
uint8_t shifted, subbed = 31;
BITS(2);
shifted = bits + 5;
if(bits>=2) {
shifted++;
subbed += 0x80;
}
backbytes = (1<<shifted)-subbed; /* 1h, 21h, 61h, 161h */
BITS(shifted); /* 5, 6, 8, 9 */
if(error || bits == 0x1ff) break;
backbytes+=bits;
if(!CLI_ISCONTAINED(exe, exesz, ucur, 2) || !CLI_ISCONTAINED(exe, exesz, ucur-backbytes, 2)) {
error=1;
} else {
ucur[0]=*(ucur-backbytes);
ucur[1]=*(ucur-backbytes+1);
ucur+=2;
}
continue;
}
/* BLOCK backcopy */
saved = bits; /* cmp al, 1 / pushf */
BITS(3);
if (bits<6) {
backbytes = bits;
switch(bits) {
case 4: /* 10,11 */
backbytes++;
case 3: /* 8,9 */
BIT;
backbytes+=bits;
case 0: case 1: case 2: /* 5,6,7 */
backbytes+=5;
break;
case 5: /* 12 */
backbytes=12;
break;
}
BITS(backbytes);
bits+=(1<<backbytes)-31;
} else if(bits==6) {
BITS(0x0e);
bits+=0x1fe1;
} else {
BITS(0x0f);
bits+=0x5fe1;
}
backbytes = bits;
/* popf / jb */
if (!saved) {
BIT;
if(!bits) {
BIT;
bits+=5;
} else {
BITS(3);
if(bits) {
bits+=6;
} else {
BITS(4);
if(bits) {
bits+=13;
} else {
uint8_t cnt = 4;
uint16_t shifted = 0x0d;
do {
if(cnt==7) { cnt = 0x0e; shifted = 0; break; }
shifted=((shifted+2)<<1)-1;
BIT;
cnt++;
} while(!bits);
BITS(cnt);
bits+=shifted;
}
}
}
backsize = bits;
} else {
backsize = saved+2;
}
if(!CLI_ISCONTAINED(exe, exesz, ucur, backsize) || !CLI_ISCONTAINED(exe, exesz, ucur-backbytes, backsize)) error=1;
else while(backsize--) {
*ucur=*(ucur-backbytes);
ucur++;
}
}
free(compd);
if(error) {
cli_dbgmsg("WWPack: decompression error\n");
break;
}
if (error || !*structs++) break;
}
if(!error) {
if (pe+6 > exesz || pe+7 > exesz || pe+0x28 > exesz ||
pe+0x50 > exesz || pe+0x14 > exesz)
return CL_EFORMAT;
exe[pe+6]=(uint8_t)scount;
exe[pe+7]=(uint8_t)(scount>>8);
cli_writeint32(&exe[pe+0x28], cli_readint32(wwsect+0x295)+sects[scount].rva+0x299);
cli_writeint32(&exe[pe+0x50], cli_readint32(&exe[pe+0x50])-sects[scount].vsz);
structs = &exe[(0xffff&cli_readint32(&exe[pe+0x14]))+pe+0x18];
for(i=0 ; i<scount ; i++) {
if (!CLI_ISCONTAINED(exe, exesz, structs, 0x28)) {
cli_dbgmsg("WWPack: structs pointer out of bounds\n");
return CL_EFORMAT;
}
cli_writeint32(structs+8, sects[i].vsz);
cli_writeint32(structs+12, sects[i].rva);
cli_writeint32(structs+16, sects[i].vsz);
cli_writeint32(structs+20, sects[i].rva);
structs+=0x28;
}
if (!CLI_ISCONTAINED(exe, exesz, structs, 0x28)) {
cli_dbgmsg("WWPack: structs pointer out of bounds\n");
return CL_EFORMAT;
}
memset(structs, 0, 0x28);
error = (uint32_t)cli_writen(desc, exe, exesz)!=exesz;
}
return error;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'bb19798 - fix out of bound memory access for crafted wwunpack file.'</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: _zip_dirent_read(zip_dirent_t *zde, zip_source_t *src, zip_buffer_t *buffer, bool local, zip_error_t *error)
{
zip_uint8_t buf[CDENTRYSIZE];
zip_uint16_t dostime, dosdate;
zip_uint32_t size, variable_size;
zip_uint16_t filename_len, comment_len, ef_len;
bool from_buffer = (buffer != NULL);
size = local ? LENTRYSIZE : CDENTRYSIZE;
if (buffer) {
if (_zip_buffer_left(buffer) < size) {
zip_error_set(error, ZIP_ER_NOZIP, 0);
return -1;
}
}
else {
if ((buffer = _zip_buffer_new_from_source(src, size, buf, error)) == NULL) {
return -1;
}
}
if (memcmp(_zip_buffer_get(buffer, 4), (local ? LOCAL_MAGIC : CENTRAL_MAGIC), 4) != 0) {
zip_error_set(error, ZIP_ER_NOZIP, 0);
if (!from_buffer) {
_zip_buffer_free(buffer);
}
return -1;
}
/* convert buffercontents to zip_dirent */
_zip_dirent_init(zde);
if (!local)
zde->version_madeby = _zip_buffer_get_16(buffer);
else
zde->version_madeby = 0;
zde->version_needed = _zip_buffer_get_16(buffer);
zde->bitflags = _zip_buffer_get_16(buffer);
zde->comp_method = _zip_buffer_get_16(buffer);
/* convert to time_t */
dostime = _zip_buffer_get_16(buffer);
dosdate = _zip_buffer_get_16(buffer);
zde->last_mod = _zip_d2u_time(dostime, dosdate);
zde->crc = _zip_buffer_get_32(buffer);
zde->comp_size = _zip_buffer_get_32(buffer);
zde->uncomp_size = _zip_buffer_get_32(buffer);
filename_len = _zip_buffer_get_16(buffer);
ef_len = _zip_buffer_get_16(buffer);
if (local) {
comment_len = 0;
zde->disk_number = 0;
zde->int_attrib = 0;
zde->ext_attrib = 0;
zde->offset = 0;
} else {
comment_len = _zip_buffer_get_16(buffer);
zde->disk_number = _zip_buffer_get_16(buffer);
zde->int_attrib = _zip_buffer_get_16(buffer);
zde->ext_attrib = _zip_buffer_get_32(buffer);
zde->offset = _zip_buffer_get_32(buffer);
}
if (!_zip_buffer_ok(buffer)) {
zip_error_set(error, ZIP_ER_INTERNAL, 0);
if (!from_buffer) {
_zip_buffer_free(buffer);
}
return -1;
}
if (zde->bitflags & ZIP_GPBF_ENCRYPTED) {
if (zde->bitflags & ZIP_GPBF_STRONG_ENCRYPTION) {
/* TODO */
zde->encryption_method = ZIP_EM_UNKNOWN;
}
else {
zde->encryption_method = ZIP_EM_TRAD_PKWARE;
}
}
else {
zde->encryption_method = ZIP_EM_NONE;
}
zde->filename = NULL;
zde->extra_fields = NULL;
zde->comment = NULL;
variable_size = (zip_uint32_t)filename_len+(zip_uint32_t)ef_len+(zip_uint32_t)comment_len;
if (from_buffer) {
if (_zip_buffer_left(buffer) < variable_size) {
zip_error_set(error, ZIP_ER_INCONS, 0);
return -1;
}
}
else {
_zip_buffer_free(buffer);
if ((buffer = _zip_buffer_new_from_source(src, variable_size, NULL, error)) == NULL) {
return -1;
}
}
if (filename_len) {
zde->filename = _zip_read_string(buffer, src, filename_len, 1, error);
if (!zde->filename) {
if (zip_error_code_zip(error) == ZIP_ER_EOF) {
zip_error_set(error, ZIP_ER_INCONS, 0);
}
if (!from_buffer) {
_zip_buffer_free(buffer);
}
return -1;
}
if (zde->bitflags & ZIP_GPBF_ENCODING_UTF_8) {
if (_zip_guess_encoding(zde->filename, ZIP_ENCODING_UTF8_KNOWN) == ZIP_ENCODING_ERROR) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (!from_buffer) {
_zip_buffer_free(buffer);
}
return -1;
}
}
}
if (ef_len) {
zip_uint8_t *ef = _zip_read_data(buffer, src, ef_len, 0, error);
if (ef == NULL) {
if (!from_buffer) {
_zip_buffer_free(buffer);
}
return -1;
}
if (!_zip_ef_parse(ef, ef_len, local ? ZIP_EF_LOCAL : ZIP_EF_CENTRAL, &zde->extra_fields, error)) {
free(ef);
if (!from_buffer) {
_zip_buffer_free(buffer);
}
return -1;
}
free(ef);
if (local)
zde->local_extra_fields_read = 1;
}
if (comment_len) {
zde->comment = _zip_read_string(buffer, src, comment_len, 0, error);
if (!zde->comment) {
if (!from_buffer) {
_zip_buffer_free(buffer);
}
return -1;
}
if (zde->bitflags & ZIP_GPBF_ENCODING_UTF_8) {
if (_zip_guess_encoding(zde->comment, ZIP_ENCODING_UTF8_KNOWN) == ZIP_ENCODING_ERROR) {
zip_error_set(error, ZIP_ER_INCONS, 0);
if (!from_buffer) {
_zip_buffer_free(buffer);
}
return -1;
}
}
}
zde->filename = _zip_dirent_process_ef_utf_8(zde, ZIP_EF_UTF_8_NAME, zde->filename);
zde->comment = _zip_dirent_process_ef_utf_8(zde, ZIP_EF_UTF_8_COMMENT, zde->comment);
/* Zip64 */
if (zde->uncomp_size == ZIP_UINT32_MAX || zde->comp_size == ZIP_UINT32_MAX || zde->offset == ZIP_UINT32_MAX) {
zip_uint16_t got_len;
zip_buffer_t *ef_buffer;
const zip_uint8_t *ef = _zip_ef_get_by_id(zde->extra_fields, &got_len, ZIP_EF_ZIP64, 0, local ? ZIP_EF_LOCAL : ZIP_EF_CENTRAL, error);
/* TODO: if got_len == 0 && !ZIP64_EOCD: no error, 0xffffffff is valid value */
if (ef == NULL) {
if (!from_buffer) {
_zip_buffer_free(buffer);
}
return -1;
}
if ((ef_buffer = _zip_buffer_new((zip_uint8_t *)ef, got_len)) == NULL) {
zip_error_set(error, ZIP_ER_MEMORY, 0);
if (!from_buffer) {
_zip_buffer_free(buffer);
}
return -1;
}
if (zde->uncomp_size == ZIP_UINT32_MAX)
zde->uncomp_size = _zip_buffer_get_64(ef_buffer);
else if (local) {
/* From appnote.txt: This entry in the Local header MUST
include BOTH original and compressed file size fields. */
(void)_zip_buffer_skip(ef_buffer, 8); /* error is caught by _zip_buffer_eof() call */
}
if (zde->comp_size == ZIP_UINT32_MAX)
zde->comp_size = _zip_buffer_get_64(ef_buffer);
if (!local) {
if (zde->offset == ZIP_UINT32_MAX)
zde->offset = _zip_buffer_get_64(ef_buffer);
if (zde->disk_number == ZIP_UINT16_MAX)
zde->disk_number = _zip_buffer_get_32(buffer);
}
if (!_zip_buffer_eof(ef_buffer)) {
zip_error_set(error, ZIP_ER_INCONS, 0);
_zip_buffer_free(ef_buffer);
if (!from_buffer) {
_zip_buffer_free(buffer);
}
return -1;
}
_zip_buffer_free(ef_buffer);
}
if (!_zip_buffer_ok(buffer)) {
zip_error_set(error, ZIP_ER_INTERNAL, 0);
if (!from_buffer) {
_zip_buffer_free(buffer);
}
return -1;
}
if (!from_buffer) {
_zip_buffer_free(buffer);
}
/* zip_source_seek / zip_source_tell don't support values > ZIP_INT64_MAX */
if (zde->offset > ZIP_INT64_MAX) {
zip_error_set(error, ZIP_ER_SEEK, EFBIG);
return -1;
}
if (!_zip_dirent_process_winzip_aes(zde, error)) {
if (!from_buffer) {
_zip_buffer_free(buffer);
}
return -1;
}
zde->extra_fields = _zip_ef_remove_internal(zde->extra_fields);
return (zip_int64_t)(size + variable_size);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-415'], 'message': 'Fix double free().
Found by Brian 'geeknik' Carpenter using AFL.'</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 zend_always_inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, zend_long elements, int objprops)
{
while (elements-- > 0) {
zval key, *data, d, *old_data;
zend_ulong idx;
ZVAL_UNDEF(&key);
if (!php_var_unserialize_internal(&key, p, max, NULL, classes)) {
zval_dtor(&key);
return 0;
}
data = NULL;
ZVAL_UNDEF(&d);
if (!objprops) {
if (Z_TYPE(key) == IS_LONG) {
idx = Z_LVAL(key);
numeric_key:
if (UNEXPECTED((old_data = zend_hash_index_find(ht, idx)) != NULL)) {
//??? update hash
var_push_dtor(var_hash, old_data);
data = zend_hash_index_update(ht, idx, &d);
} else {
data = zend_hash_index_add_new(ht, idx, &d);
}
} else if (Z_TYPE(key) == IS_STRING) {
if (UNEXPECTED(ZEND_HANDLE_NUMERIC(Z_STR(key), idx))) {
goto numeric_key;
}
if (UNEXPECTED((old_data = zend_hash_find(ht, Z_STR(key))) != NULL)) {
//??? update hash
var_push_dtor(var_hash, old_data);
data = zend_hash_update(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else {
zval_dtor(&key);
return 0;
}
} else {
if (EXPECTED(Z_TYPE(key) == IS_STRING)) {
string_key:
if ((old_data = zend_hash_find(ht, Z_STR(key))) != NULL) {
if (Z_TYPE_P(old_data) == IS_INDIRECT) {
old_data = Z_INDIRECT_P(old_data);
}
var_push_dtor(var_hash, old_data);
data = zend_hash_update_ind(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else if (Z_TYPE(key) == IS_LONG) {
/* object properties should include no integers */
convert_to_string(&key);
goto string_key;
} else {
zval_dtor(&key);
return 0;
}
}
if (!php_var_unserialize_internal(data, p, max, var_hash, classes)) {
zval_dtor(&key);
return 0;
}
if (UNEXPECTED(Z_ISUNDEF_P(data))) {
if (Z_TYPE(key) == IS_LONG) {
zend_hash_index_del(ht, Z_LVAL(key));
} else {
zend_hash_del_ind(ht, Z_STR(key));
}
} else {
var_push_dtor(var_hash, data);
}
zval_dtor(&key);
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #74103 and bug #75054
Directly fail unserialization when trying to acquire an r/R
reference to an UNDEF HT slot. Previously this left an UNDEF and
later deleted the index/key from the HT.
What actually caused the issue here is a combination of two
factors: First, the key deletion was performed using the hash API,
rather than the symtable API, such that the element was not actually
removed if it used an integral string key. Second, a subsequent
deletion operation, while collecting trailing UNDEF ranges, would
mark the element as available for reuse (leaving a corrupted HT
state with nNumOfElemnts > nNumUsed).
Fix this by failing early and dropping the deletion 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: bool __skb_flow_dissect(const struct sk_buff *skb,
struct flow_dissector *flow_dissector,
void *target_container,
void *data, __be16 proto, int nhoff, int hlen)
{
struct flow_dissector_key_control *key_control;
struct flow_dissector_key_basic *key_basic;
struct flow_dissector_key_addrs *key_addrs;
struct flow_dissector_key_ports *key_ports;
struct flow_dissector_key_tags *key_tags;
struct flow_dissector_key_keyid *key_keyid;
u8 ip_proto = 0;
if (!data) {
data = skb->data;
proto = skb->protocol;
nhoff = skb_network_offset(skb);
hlen = skb_headlen(skb);
}
/* It is ensured by skb_flow_dissector_init() that control key will
* be always present.
*/
key_control = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_CONTROL,
target_container);
/* It is ensured by skb_flow_dissector_init() that basic key will
* be always present.
*/
key_basic = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_BASIC,
target_container);
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
struct ethhdr *eth = eth_hdr(skb);
struct flow_dissector_key_eth_addrs *key_eth_addrs;
key_eth_addrs = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_ETH_ADDRS,
target_container);
memcpy(key_eth_addrs, ð->h_dest, sizeof(*key_eth_addrs));
}
again:
switch (proto) {
case htons(ETH_P_IP): {
const struct iphdr *iph;
struct iphdr _iph;
ip:
iph = __skb_header_pointer(skb, nhoff, sizeof(_iph), data, hlen, &_iph);
if (!iph || iph->ihl < 5)
return false;
nhoff += iph->ihl * 4;
ip_proto = iph->protocol;
if (ip_is_fragment(iph))
ip_proto = 0;
if (!skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_IPV4_ADDRS))
break;
key_addrs = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_IPV4_ADDRS, target_container);
memcpy(&key_addrs->v4addrs, &iph->saddr,
sizeof(key_addrs->v4addrs));
key_control->addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
break;
}
case htons(ETH_P_IPV6): {
const struct ipv6hdr *iph;
struct ipv6hdr _iph;
__be32 flow_label;
ipv6:
iph = __skb_header_pointer(skb, nhoff, sizeof(_iph), data, hlen, &_iph);
if (!iph)
return false;
ip_proto = iph->nexthdr;
nhoff += sizeof(struct ipv6hdr);
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_IPV6_ADDRS)) {
struct flow_dissector_key_ipv6_addrs *key_ipv6_addrs;
key_ipv6_addrs = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_IPV6_ADDRS,
target_container);
memcpy(key_ipv6_addrs, &iph->saddr, sizeof(*key_ipv6_addrs));
key_control->addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
}
flow_label = ip6_flowlabel(iph);
if (flow_label) {
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_FLOW_LABEL)) {
key_tags = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_FLOW_LABEL,
target_container);
key_tags->flow_label = ntohl(flow_label);
}
}
break;
}
case htons(ETH_P_8021AD):
case htons(ETH_P_8021Q): {
const struct vlan_hdr *vlan;
struct vlan_hdr _vlan;
vlan = __skb_header_pointer(skb, nhoff, sizeof(_vlan), data, hlen, &_vlan);
if (!vlan)
return false;
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_VLANID)) {
key_tags = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_VLANID,
target_container);
key_tags->vlan_id = skb_vlan_tag_get_id(skb);
}
proto = vlan->h_vlan_encapsulated_proto;
nhoff += sizeof(*vlan);
goto again;
}
case htons(ETH_P_PPP_SES): {
struct {
struct pppoe_hdr hdr;
__be16 proto;
} *hdr, _hdr;
hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data, hlen, &_hdr);
if (!hdr)
return false;
proto = hdr->proto;
nhoff += PPPOE_SES_HLEN;
switch (proto) {
case htons(PPP_IP):
goto ip;
case htons(PPP_IPV6):
goto ipv6;
default:
return false;
}
}
case htons(ETH_P_TIPC): {
struct {
__be32 pre[3];
__be32 srcnode;
} *hdr, _hdr;
hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data, hlen, &_hdr);
if (!hdr)
return false;
key_basic->n_proto = proto;
key_control->thoff = (u16)nhoff;
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_TIPC_ADDRS)) {
key_addrs = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_TIPC_ADDRS,
target_container);
key_addrs->tipcaddrs.srcnode = hdr->srcnode;
key_control->addr_type = FLOW_DISSECTOR_KEY_TIPC_ADDRS;
}
return true;
}
case htons(ETH_P_MPLS_UC):
case htons(ETH_P_MPLS_MC): {
struct mpls_label *hdr, _hdr[2];
mpls:
hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data,
hlen, &_hdr);
if (!hdr)
return false;
if ((ntohl(hdr[0].entry) & MPLS_LS_LABEL_MASK) >>
MPLS_LS_LABEL_SHIFT == MPLS_LABEL_ENTROPY) {
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_MPLS_ENTROPY)) {
key_keyid = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_MPLS_ENTROPY,
target_container);
key_keyid->keyid = hdr[1].entry &
htonl(MPLS_LS_LABEL_MASK);
}
key_basic->n_proto = proto;
key_basic->ip_proto = ip_proto;
key_control->thoff = (u16)nhoff;
return true;
}
return true;
}
case htons(ETH_P_FCOE):
key_control->thoff = (u16)(nhoff + FCOE_HEADER_LEN);
/* fall through */
default:
return false;
}
ip_proto_again:
switch (ip_proto) {
case IPPROTO_GRE: {
struct gre_hdr {
__be16 flags;
__be16 proto;
} *hdr, _hdr;
hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data, hlen, &_hdr);
if (!hdr)
return false;
/*
* Only look inside GRE if version zero and no
* routing
*/
if (hdr->flags & (GRE_VERSION | GRE_ROUTING))
break;
proto = hdr->proto;
nhoff += 4;
if (hdr->flags & GRE_CSUM)
nhoff += 4;
if (hdr->flags & GRE_KEY) {
const __be32 *keyid;
__be32 _keyid;
keyid = __skb_header_pointer(skb, nhoff, sizeof(_keyid),
data, hlen, &_keyid);
if (!keyid)
return false;
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_GRE_KEYID)) {
key_keyid = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_GRE_KEYID,
target_container);
key_keyid->keyid = *keyid;
}
nhoff += 4;
}
if (hdr->flags & GRE_SEQ)
nhoff += 4;
if (proto == htons(ETH_P_TEB)) {
const struct ethhdr *eth;
struct ethhdr _eth;
eth = __skb_header_pointer(skb, nhoff,
sizeof(_eth),
data, hlen, &_eth);
if (!eth)
return false;
proto = eth->h_proto;
nhoff += sizeof(*eth);
}
goto again;
}
case NEXTHDR_HOP:
case NEXTHDR_ROUTING:
case NEXTHDR_DEST: {
u8 _opthdr[2], *opthdr;
if (proto != htons(ETH_P_IPV6))
break;
opthdr = __skb_header_pointer(skb, nhoff, sizeof(_opthdr),
data, hlen, &_opthdr);
if (!opthdr)
return false;
ip_proto = opthdr[0];
nhoff += (opthdr[1] + 1) << 3;
goto ip_proto_again;
}
case IPPROTO_IPIP:
proto = htons(ETH_P_IP);
goto ip;
case IPPROTO_IPV6:
proto = htons(ETH_P_IPV6);
goto ipv6;
case IPPROTO_MPLS:
proto = htons(ETH_P_MPLS_UC);
goto mpls;
default:
break;
}
key_basic->n_proto = proto;
key_basic->ip_proto = ip_proto;
key_control->thoff = (u16)nhoff;
if (skb_flow_dissector_uses_key(flow_dissector,
FLOW_DISSECTOR_KEY_PORTS)) {
key_ports = skb_flow_dissector_target(flow_dissector,
FLOW_DISSECTOR_KEY_PORTS,
target_container);
key_ports->ports = __skb_flow_get_ports(skb, nhoff, ip_proto,
data, hlen);
}
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20', 'CWE-665', 'CWE-703'], 'message': 'flow_dissector: Jump to exit code in __skb_flow_dissect
Instead of returning immediately (on a parsing failure for instance) we
jump to cleanup code. This always sets protocol values in key_control
(even on a failure there is still valid information in the key_tags that
was set before the problem was hit).
Signed-off-by: Tom Herbert <[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 inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(in_skb->sk);
struct rtmsg *rtm;
struct nlattr *tb[RTA_MAX+1];
struct fib_result res = {};
struct rtable *rt = NULL;
struct flowi4 fl4;
__be32 dst = 0;
__be32 src = 0;
u32 iif;
int err;
int mark;
struct sk_buff *skb;
u32 table_id = RT_TABLE_MAIN;
kuid_t uid;
err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy,
extack);
if (err < 0)
goto errout;
rtm = nlmsg_data(nlh);
skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb) {
err = -ENOBUFS;
goto errout;
}
/* Reserve room for dummy headers, this skb can pass
through good chunk of routing engine.
*/
skb_reset_mac_header(skb);
skb_reset_network_header(skb);
src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0;
dst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0;
iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0;
mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0;
if (tb[RTA_UID])
uid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID]));
else
uid = (iif ? INVALID_UID : current_uid());
/* Bugfix: need to give ip_route_input enough of an IP header to
* not gag.
*/
ip_hdr(skb)->protocol = IPPROTO_UDP;
ip_hdr(skb)->saddr = src;
ip_hdr(skb)->daddr = dst;
skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr));
memset(&fl4, 0, sizeof(fl4));
fl4.daddr = dst;
fl4.saddr = src;
fl4.flowi4_tos = rtm->rtm_tos;
fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0;
fl4.flowi4_mark = mark;
fl4.flowi4_uid = uid;
rcu_read_lock();
if (iif) {
struct net_device *dev;
dev = dev_get_by_index_rcu(net, iif);
if (!dev) {
err = -ENODEV;
goto errout_free;
}
skb->protocol = htons(ETH_P_IP);
skb->dev = dev;
skb->mark = mark;
err = ip_route_input_rcu(skb, dst, src, rtm->rtm_tos,
dev, &res);
rt = skb_rtable(skb);
if (err == 0 && rt->dst.error)
err = -rt->dst.error;
} else {
rt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb);
err = 0;
if (IS_ERR(rt))
err = PTR_ERR(rt);
else
skb_dst_set(skb, &rt->dst);
}
if (err)
goto errout_free;
if (rtm->rtm_flags & RTM_F_NOTIFY)
rt->rt_flags |= RTCF_NOTIFY;
if (rtm->rtm_flags & RTM_F_LOOKUP_TABLE)
table_id = rt->rt_table_id;
if (rtm->rtm_flags & RTM_F_FIB_MATCH)
err = fib_dump_info(skb, NETLINK_CB(in_skb).portid,
nlh->nlmsg_seq, RTM_NEWROUTE, table_id,
rt->rt_type, res.prefix, res.prefixlen,
fl4.flowi4_tos, res.fi, 0);
else
err = rt_fill_info(net, dst, src, table_id, &fl4, skb,
NETLINK_CB(in_skb).portid, nlh->nlmsg_seq);
if (err < 0)
goto errout_free;
rcu_read_unlock();
err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
errout:
return err;
errout_free:
rcu_read_unlock();
kfree_skb(skb);
goto errout;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'net: check and errout if res->fi is NULL when RTM_F_FIB_MATCH is set
Syzkaller hit 'general protection fault in fib_dump_info' bug on
commit 4.13-rc5..
Guilty file: net/ipv4/fib_semantics.c
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN
Modules linked in:
CPU: 0 PID: 2808 Comm: syz-executor0 Not tainted 4.13.0-rc5 #1
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS
Ubuntu-1.8.2-1ubuntu1 04/01/2014
task: ffff880078562700 task.stack: ffff880078110000
RIP: 0010:fib_dump_info+0x388/0x1170 net/ipv4/fib_semantics.c:1314
RSP: 0018:ffff880078117010 EFLAGS: 00010206
RAX: dffffc0000000000 RBX: 00000000000000fe RCX: 0000000000000002
RDX: 0000000000000006 RSI: ffff880078117084 RDI: 0000000000000030
RBP: ffff880078117268 R08: 000000000000000c R09: ffff8800780d80c8
R10: 0000000058d629b4 R11: 0000000067fce681 R12: 0000000000000000
R13: ffff8800784bd540 R14: ffff8800780d80b5 R15: ffff8800780d80a4
FS: 00000000022fa940(0000) GS:ffff88007fc00000(0000)
knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00000000004387d0 CR3: 0000000079135000 CR4: 00000000000006f0
Call Trace:
inet_rtm_getroute+0xc89/0x1f50 net/ipv4/route.c:2766
rtnetlink_rcv_msg+0x288/0x680 net/core/rtnetlink.c:4217
netlink_rcv_skb+0x340/0x470 net/netlink/af_netlink.c:2397
rtnetlink_rcv+0x28/0x30 net/core/rtnetlink.c:4223
netlink_unicast_kernel net/netlink/af_netlink.c:1265 [inline]
netlink_unicast+0x4c4/0x6e0 net/netlink/af_netlink.c:1291
netlink_sendmsg+0x8c4/0xca0 net/netlink/af_netlink.c:1854
sock_sendmsg_nosec net/socket.c:633 [inline]
sock_sendmsg+0xca/0x110 net/socket.c:643
___sys_sendmsg+0x779/0x8d0 net/socket.c:2035
__sys_sendmsg+0xd1/0x170 net/socket.c:2069
SYSC_sendmsg net/socket.c:2080 [inline]
SyS_sendmsg+0x2d/0x50 net/socket.c:2076
entry_SYSCALL_64_fastpath+0x1a/0xa5
RIP: 0033:0x4512e9
RSP: 002b:00007ffc75584cc8 EFLAGS: 00000216 ORIG_RAX:
000000000000002e
RAX: ffffffffffffffda RBX: 0000000000000002 RCX: 00000000004512e9
RDX: 0000000000000000 RSI: 0000000020f2cfc8 RDI: 0000000000000003
RBP: 000000000000000e R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000216 R12: fffffffffffffffe
R13: 0000000000718000 R14: 0000000020c44ff0 R15: 0000000000000000
Code: 00 0f b6 8d ec fd ff ff 48 8b 85 f0 fd ff ff 88 48 17 48 8b 45
28 48 8d 78 30 48 b8 00 00 00 00 00 fc ff df 48 89 fa 48 c1 ea 03
<0f>
b6 04 02 84 c0 74 08 3c 03 0f 8e cb 0c 00 00 48 8b 45 28 44
RIP: fib_dump_info+0x388/0x1170 net/ipv4/fib_semantics.c:1314 RSP:
ffff880078117010
---[ end trace 254a7af28348f88b ]---
This patch adds a res->fi NULL check.
example run:
$ip route get 0.0.0.0 iif virt1-0
broadcast 0.0.0.0 dev lo
cache <local,brd> iif virt1-0
$ip route get 0.0.0.0 iif virt1-0 fibmatch
RTNETLINK answers: No route to host
Reported-by: idaifish <[email protected]>
Reported-by: Dmitry Vyukov <[email protected]>
Fixes: b61798130f1b ("net: ipv4: RTM_GETROUTE: return matched fib result when requested")
Signed-off-by: Roopa Prabhu <[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: QPDFObjectHandle::parse(PointerHolder<InputSource> input,
std::string const& object_description,
QPDFTokenizer& tokenizer, bool& empty,
StringDecrypter* decrypter, QPDF* context)
{
return parseInternal(input, object_description, tokenizer, empty,
decrypter, context, false, false, false);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'Parse iteratively to avoid stack overflow (fixes #146)'</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: ecc_decrypt_raw (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t keyparms)
{
unsigned int nbits;
gpg_err_code_t rc;
struct pk_encoding_ctx ctx;
gcry_sexp_t l1 = NULL;
gcry_mpi_t data_e = NULL;
ECC_secret_key sk;
gcry_mpi_t mpi_g = NULL;
char *curvename = NULL;
mpi_ec_t ec = NULL;
mpi_point_struct kG;
mpi_point_struct R;
gcry_mpi_t r = NULL;
int flags = 0;
memset (&sk, 0, sizeof sk);
point_init (&kG);
point_init (&R);
_gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT,
(nbits = ecc_get_nbits (keyparms)));
/* Look for flags. */
l1 = sexp_find_token (keyparms, "flags", 0);
if (l1)
{
rc = _gcry_pk_util_parse_flaglist (l1, &flags, NULL);
if (rc)
goto leave;
}
sexp_release (l1);
l1 = NULL;
/*
* Extract the data.
*/
rc = _gcry_pk_util_preparse_encval (s_data, ecc_names, &l1, &ctx);
if (rc)
goto leave;
rc = sexp_extract_param (l1, NULL, "e", &data_e, NULL);
if (rc)
goto leave;
if (DBG_CIPHER)
log_printmpi ("ecc_decrypt d_e", data_e);
if (mpi_is_opaque (data_e))
{
rc = GPG_ERR_INV_DATA;
goto leave;
}
/*
* Extract the key.
*/
rc = sexp_extract_param (keyparms, NULL, "-p?a?b?g?n?h?+d",
&sk.E.p, &sk.E.a, &sk.E.b, &mpi_g, &sk.E.n,
&sk.E.h, &sk.d, NULL);
if (rc)
goto leave;
if (mpi_g)
{
point_init (&sk.E.G);
rc = _gcry_ecc_os2ec (&sk.E.G, mpi_g);
if (rc)
goto leave;
}
/* Add missing parameters using the optional curve parameter. */
sexp_release (l1);
l1 = sexp_find_token (keyparms, "curve", 5);
if (l1)
{
curvename = sexp_nth_string (l1, 1);
if (curvename)
{
rc = _gcry_ecc_fill_in_curve (0, curvename, &sk.E, NULL);
if (rc)
goto leave;
}
}
/* Guess required fields if a curve parameter has not been given. */
if (!curvename)
{
sk.E.model = MPI_EC_WEIERSTRASS;
sk.E.dialect = ECC_DIALECT_STANDARD;
if (!sk.E.h)
sk.E.h = mpi_const (MPI_C_ONE);
}
if (DBG_CIPHER)
{
log_debug ("ecc_decrypt info: %s/%s\n",
_gcry_ecc_model2str (sk.E.model),
_gcry_ecc_dialect2str (sk.E.dialect));
if (sk.E.name)
log_debug ("ecc_decrypt name: %s\n", sk.E.name);
log_printmpi ("ecc_decrypt p", sk.E.p);
log_printmpi ("ecc_decrypt a", sk.E.a);
log_printmpi ("ecc_decrypt b", sk.E.b);
log_printpnt ("ecc_decrypt g", &sk.E.G, NULL);
log_printmpi ("ecc_decrypt n", sk.E.n);
log_printmpi ("ecc_decrypt h", sk.E.h);
if (!fips_mode ())
log_printmpi ("ecc_decrypt d", sk.d);
}
if (!sk.E.p || !sk.E.a || !sk.E.b || !sk.E.G.x || !sk.E.n || !sk.E.h || !sk.d)
{
rc = GPG_ERR_NO_OBJ;
goto leave;
}
ec = _gcry_mpi_ec_p_internal_new (sk.E.model, sk.E.dialect, flags,
sk.E.p, sk.E.a, sk.E.b);
/*
* Compute the plaintext.
*/
if (ec->model == MPI_EC_MONTGOMERY)
rc = _gcry_ecc_mont_decodepoint (data_e, ec, &kG);
else
rc = _gcry_ecc_os2ec (&kG, data_e);
if (rc)
goto leave;
if (DBG_CIPHER)
log_printpnt ("ecc_decrypt kG", &kG, NULL);
if (!(flags & PUBKEY_FLAG_DJB_TWEAK)
/* For X25519, by its definition, validation should not be done. */
&& !_gcry_mpi_ec_curve_point (&kG, ec))
{
rc = GPG_ERR_INV_DATA;
goto leave;
}
/* R = dkG */
_gcry_mpi_ec_mul_point (&R, sk.d, &kG, ec);
/* The following is false: assert( mpi_cmp_ui( R.x, 1 )==0 );, so: */
{
gcry_mpi_t x, y;
x = mpi_new (0);
if (ec->model == MPI_EC_MONTGOMERY)
y = NULL;
else
y = mpi_new (0);
if (_gcry_mpi_ec_get_affine (x, y, &R, ec))
{
rc = GPG_ERR_INV_DATA;
goto leave;
/*
* Note for X25519.
*
* By the definition of X25519, this is the case where X25519
* returns 0, mapping infinity to zero. However, we
* deliberately let it return an error.
*
* For X25519 ECDH, comming here means that it might be
* decrypted by anyone with the shared secret of 0 (the result
* of this function could be always 0 by other scalar values,
* other than the private key of SK.D).
*
* So, it looks like an encrypted message but it can be
* decrypted by anyone, or at least something wrong
* happens. Recipient should not proceed as if it were
* properly encrypted message.
*
* This handling is needed for our major usage of GnuPG,
* where it does the One-Pass Diffie-Hellman method,
* C(1, 1, ECC CDH), with an ephemeral key.
*/
}
if (y)
r = _gcry_ecc_ec2os (x, y, sk.E.p);
else
{
unsigned char *rawmpi;
unsigned int rawmpilen;
rawmpi = _gcry_mpi_get_buffer_extra (x, nbits/8, -1,
&rawmpilen, NULL);
if (!rawmpi)
{
rc = gpg_err_code_from_syserror ();
goto leave;
}
else
{
rawmpi[0] = 0x40;
rawmpilen++;
r = mpi_new (0);
mpi_set_opaque (r, rawmpi, rawmpilen*8);
}
}
if (!r)
rc = gpg_err_code_from_syserror ();
else
rc = 0;
mpi_free (x);
mpi_free (y);
}
if (DBG_CIPHER)
log_printmpi ("ecc_decrypt res", r);
if (!rc)
rc = sexp_build (r_plain, NULL, "(value %m)", r);
leave:
point_free (&R);
point_free (&kG);
_gcry_mpi_release (r);
_gcry_mpi_release (sk.E.p);
_gcry_mpi_release (sk.E.a);
_gcry_mpi_release (sk.E.b);
_gcry_mpi_release (mpi_g);
point_free (&sk.E.G);
_gcry_mpi_release (sk.E.n);
_gcry_mpi_release (sk.E.h);
_gcry_mpi_release (sk.d);
_gcry_mpi_release (data_e);
xfree (curvename);
sexp_release (l1);
_gcry_mpi_ec_free (ec);
_gcry_pk_util_free_encoding_ctx (&ctx);
if (DBG_CIPHER)
log_debug ("ecc_decrypt => %s\n", gpg_strerror (rc));
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'ecc: Add input validation for X25519.
* cipher/ecc.c (ecc_decrypt_raw): Add input validation.
* mpi/ec.c (ec_p_init): Use scratch buffer for bad points.
(_gcry_mpi_ec_bad_point): New.
--
Following is the paper describing the attack:
May the Fourth Be With You: A Microarchitectural Side Channel Attack
on Real-World Applications of Curve25519
by Daniel Genkin, Luke Valenta, and Yuval Yarom
In the current implementation, we do output checking and it results an
error for those bad points. However, when attacked, the computation
will done with leak of private key, even it will results errors. To
mitigate leak, we added input validation.
Note that we only list bad points with MSB=0. By X25519, MSB is
always cleared.
In future, we should implement constant-time field computation. Then,
this input validation could be removed, if performance is important
and we are sure for no leak.
CVE-id: CVE-2017-0379
Signed-off-by: NIIBE Yutaka <[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 MagickBooleanType load_level(Image *image,XCFDocInfo *inDocInfo,
XCFLayerInfo *inLayerInfo,ExceptionInfo *exception)
{
int
destLeft = 0,
destTop = 0;
Image*
tile_image;
MagickBooleanType
status;
MagickOffsetType
saved_pos,
offset,
offset2;
register ssize_t
i;
size_t
width,
height,
ntiles,
ntile_rows,
ntile_cols,
tile_image_width,
tile_image_height;
/* start reading the data */
width=ReadBlobMSBLong(image);
height=ReadBlobMSBLong(image);
/* read in the first tile offset.
* if it is '0', then this tile level is empty
* and we can simply return.
*/
offset=(MagickOffsetType) ReadBlobMSBLong(image);
if (offset == 0)
return(MagickTrue);
/* Initialise the reference for the in-memory tile-compression
*/
ntile_rows=(height+TILE_HEIGHT-1)/TILE_HEIGHT;
ntile_cols=(width+TILE_WIDTH-1)/TILE_WIDTH;
ntiles=ntile_rows*ntile_cols;
for (i = 0; i < (ssize_t) ntiles; i++)
{
status=MagickFalse;
if (offset == 0)
ThrowBinaryException(CorruptImageError,"NotEnoughTiles",image->filename);
/* save the current position as it is where the
* next tile offset is stored.
*/
saved_pos=TellBlob(image);
/* read in the offset of the next tile so we can calculate the amount
of data needed for this tile*/
offset2=(MagickOffsetType)ReadBlobMSBLong(image);
/* if the offset is 0 then we need to read in the maximum possible
allowing for negative compression */
if (offset2 == 0)
offset2=(MagickOffsetType) (offset + TILE_WIDTH * TILE_WIDTH * 4* 1.5);
/* seek to the tile offset */
if (SeekBlob(image, offset, SEEK_SET) != offset)
ThrowBinaryException(CorruptImageError,"InsufficientImageDataInFile",
image->filename);
/*
Allocate the image for the tile. NOTE: the last tile in a row or
column may not be a full tile!
*/
tile_image_width=(size_t) (destLeft == (int) ntile_cols-1 ?
(int) width % TILE_WIDTH : TILE_WIDTH);
if (tile_image_width == 0)
tile_image_width=TILE_WIDTH;
tile_image_height = (size_t) (destTop == (int) ntile_rows-1 ?
(int) height % TILE_HEIGHT : TILE_HEIGHT);
if (tile_image_height == 0)
tile_image_height=TILE_HEIGHT;
tile_image=CloneImage(inLayerInfo->image,tile_image_width,
tile_image_height,MagickTrue,exception);
/* read in the tile */
switch (inDocInfo->compression)
{
case COMPRESS_NONE:
if (load_tile(image,tile_image,inDocInfo,inLayerInfo,(size_t) (offset2-offset),exception) == 0)
status=MagickTrue;
break;
case COMPRESS_RLE:
if (load_tile_rle (image,tile_image,inDocInfo,inLayerInfo,
(int) (offset2-offset),exception) == 0)
status=MagickTrue;
break;
case COMPRESS_ZLIB:
ThrowBinaryException(CoderError,"ZipCompressNotSupported",
image->filename)
case COMPRESS_FRACTAL:
ThrowBinaryException(CoderError,"FractalCompressNotSupported",
image->filename)
}
/* composite the tile onto the layer's image, and then destroy it */
(void) CompositeImage(inLayerInfo->image,tile_image,CopyCompositeOp,
MagickTrue,destLeft * TILE_WIDTH,destTop*TILE_HEIGHT,exception);
tile_image=DestroyImage(tile_image);
/* adjust tile position */
destLeft++;
if (destLeft >= (int) ntile_cols)
{
destLeft = 0;
destTop++;
}
if (status != MagickFalse)
return(MagickFalse);
/* restore the saved position so we'll be ready to
* read the next offset.
*/
offset=SeekBlob(image, saved_pos, SEEK_SET);
/* read in the offset of the next tile */
offset=(MagickOffsetType) ReadBlobMSBLong(image);
}
if (offset != 0)
ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename)
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-770'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/679'</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: MagickExport MagickBooleanType ContrastStretchImage(Image *image,
const double black_point,const double white_point,ExceptionInfo *exception)
{
#define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color)))
#define ContrastStretchImageTag "ContrastStretch/Image"
CacheView
*image_view;
double
*black,
*histogram,
*stretch_map,
*white;
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate histogram and stretch map.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace,exception);
black=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*black));
white=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*white));
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)*
sizeof(*histogram));
stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL,
GetPixelChannels(image)*sizeof(*stretch_map));
if ((black == (double *) NULL) || (white == (double *) NULL) ||
(histogram == (double *) NULL) || (stretch_map == (double *) NULL))
{
if (stretch_map != (double *) NULL)
stretch_map=(double *) RelinquishMagickMemory(stretch_map);
if (histogram != (double *) NULL)
histogram=(double *) RelinquishMagickMemory(histogram);
if (white != (double *) NULL)
white=(double *) RelinquishMagickMemory(white);
if (black != (double *) NULL)
black=(double *) RelinquishMagickMemory(black);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
/*
Form histogram.
*/
status=MagickTrue;
(void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
pixel=GetPixelIntensity(image,p);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
if (image->channel_mask != DefaultChannels)
pixel=(double) p[i];
histogram[GetPixelChannels(image)*ScaleQuantumToMap(
ClampToQuantum(pixel))+i]++;
}
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Find the histogram boundaries by locating the black/white levels.
*/
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
register ssize_t
j;
black[i]=0.0;
white[i]=MaxRange(QuantumRange);
intensity=0.0;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
if (intensity > black_point)
break;
}
black[i]=(double) j;
intensity=0.0;
for (j=(ssize_t) MaxMap; j != 0; j--)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
if (intensity > ((double) image->columns*image->rows-white_point))
break;
}
white[i]=(double) j;
}
histogram=(double *) RelinquishMagickMemory(histogram);
/*
Stretch the histogram to create the stretched image mapping.
*/
(void) ResetMagickMemory(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*stretch_map));
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
register ssize_t
j;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
double
gamma;
gamma=PerceptibleReciprocal(white[i]-black[i]);
if (j < (ssize_t) black[i])
stretch_map[GetPixelChannels(image)*j+i]=0.0;
else
if (j > (ssize_t) white[i])
stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange;
else
if (black[i] != white[i])
stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum(
(double) (MaxMap*gamma*(j-black[i])));
}
}
if (image->storage_class == PseudoClass)
{
register ssize_t
j;
/*
Stretch-contrast colormap.
*/
for (j=0; j < (ssize_t) image->colors; j++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,RedPixelChannel);
image->colormap[j].red=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i];
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,GreenPixelChannel);
image->colormap[j].green=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i];
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,BluePixelChannel);
image->colormap[j].blue=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i];
}
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
{
i=GetPixelChannelOffset(image,AlphaPixelChannel);
image->colormap[j].alpha=stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i];
}
}
}
/*
Stretch-contrast image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
{
PixelChannel channel=GetPixelChannelChannel(image,j);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (black[j] == white[j])
continue;
q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)*
ScaleQuantumToMap(q[j])+j]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ContrastStretchImage)
#endif
proceed=SetImageProgress(image,ContrastStretchImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
stretch_map=(double *) RelinquishMagickMemory(stretch_map);
white=(double *) RelinquishMagickMemory(white);
black=(double *) RelinquishMagickMemory(black);
return(status);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-401', 'CWE-119', 'CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/663
https://github.com/ImageMagick/ImageMagick/issues/655'</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 OPJ_BOOL bmp_read_info_header(FILE* IN, OPJ_BITMAPINFOHEADER* header)
{
memset(header, 0, sizeof(*header));
/* INFO HEADER */
/* ------------- */
header->biSize = (OPJ_UINT32)getc(IN);
header->biSize |= (OPJ_UINT32)getc(IN) << 8;
header->biSize |= (OPJ_UINT32)getc(IN) << 16;
header->biSize |= (OPJ_UINT32)getc(IN) << 24;
switch (header->biSize) {
case 12U: /* BITMAPCOREHEADER */
case 40U: /* BITMAPINFOHEADER */
case 52U: /* BITMAPV2INFOHEADER */
case 56U: /* BITMAPV3INFOHEADER */
case 108U: /* BITMAPV4HEADER */
case 124U: /* BITMAPV5HEADER */
break;
default:
fprintf(stderr, "Error, unknown BMP header size %d\n", header->biSize);
return OPJ_FALSE;
}
header->biWidth = (OPJ_UINT32)getc(IN);
header->biWidth |= (OPJ_UINT32)getc(IN) << 8;
header->biWidth |= (OPJ_UINT32)getc(IN) << 16;
header->biWidth |= (OPJ_UINT32)getc(IN) << 24;
header->biHeight = (OPJ_UINT32)getc(IN);
header->biHeight |= (OPJ_UINT32)getc(IN) << 8;
header->biHeight |= (OPJ_UINT32)getc(IN) << 16;
header->biHeight |= (OPJ_UINT32)getc(IN) << 24;
header->biPlanes = (OPJ_UINT16)getc(IN);
header->biPlanes |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8);
header->biBitCount = (OPJ_UINT16)getc(IN);
header->biBitCount |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8);
if (header->biSize >= 40U) {
header->biCompression = (OPJ_UINT32)getc(IN);
header->biCompression |= (OPJ_UINT32)getc(IN) << 8;
header->biCompression |= (OPJ_UINT32)getc(IN) << 16;
header->biCompression |= (OPJ_UINT32)getc(IN) << 24;
header->biSizeImage = (OPJ_UINT32)getc(IN);
header->biSizeImage |= (OPJ_UINT32)getc(IN) << 8;
header->biSizeImage |= (OPJ_UINT32)getc(IN) << 16;
header->biSizeImage |= (OPJ_UINT32)getc(IN) << 24;
header->biXpelsPerMeter = (OPJ_UINT32)getc(IN);
header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8;
header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16;
header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24;
header->biYpelsPerMeter = (OPJ_UINT32)getc(IN);
header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8;
header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16;
header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24;
header->biClrUsed = (OPJ_UINT32)getc(IN);
header->biClrUsed |= (OPJ_UINT32)getc(IN) << 8;
header->biClrUsed |= (OPJ_UINT32)getc(IN) << 16;
header->biClrUsed |= (OPJ_UINT32)getc(IN) << 24;
header->biClrImportant = (OPJ_UINT32)getc(IN);
header->biClrImportant |= (OPJ_UINT32)getc(IN) << 8;
header->biClrImportant |= (OPJ_UINT32)getc(IN) << 16;
header->biClrImportant |= (OPJ_UINT32)getc(IN) << 24;
}
if (header->biSize >= 56U) {
header->biRedMask = (OPJ_UINT32)getc(IN);
header->biRedMask |= (OPJ_UINT32)getc(IN) << 8;
header->biRedMask |= (OPJ_UINT32)getc(IN) << 16;
header->biRedMask |= (OPJ_UINT32)getc(IN) << 24;
header->biGreenMask = (OPJ_UINT32)getc(IN);
header->biGreenMask |= (OPJ_UINT32)getc(IN) << 8;
header->biGreenMask |= (OPJ_UINT32)getc(IN) << 16;
header->biGreenMask |= (OPJ_UINT32)getc(IN) << 24;
header->biBlueMask = (OPJ_UINT32)getc(IN);
header->biBlueMask |= (OPJ_UINT32)getc(IN) << 8;
header->biBlueMask |= (OPJ_UINT32)getc(IN) << 16;
header->biBlueMask |= (OPJ_UINT32)getc(IN) << 24;
header->biAlphaMask = (OPJ_UINT32)getc(IN);
header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 8;
header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 16;
header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 24;
}
if (header->biSize >= 108U) {
header->biColorSpaceType = (OPJ_UINT32)getc(IN);
header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 8;
header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 16;
header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 24;
if (fread(&(header->biColorSpaceEP), 1U, sizeof(header->biColorSpaceEP),
IN) != sizeof(header->biColorSpaceEP)) {
fprintf(stderr, "Error, can't read BMP header\n");
return OPJ_FALSE;
}
header->biRedGamma = (OPJ_UINT32)getc(IN);
header->biRedGamma |= (OPJ_UINT32)getc(IN) << 8;
header->biRedGamma |= (OPJ_UINT32)getc(IN) << 16;
header->biRedGamma |= (OPJ_UINT32)getc(IN) << 24;
header->biGreenGamma = (OPJ_UINT32)getc(IN);
header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 8;
header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 16;
header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 24;
header->biBlueGamma = (OPJ_UINT32)getc(IN);
header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 8;
header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 16;
header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 24;
}
if (header->biSize >= 124U) {
header->biIntent = (OPJ_UINT32)getc(IN);
header->biIntent |= (OPJ_UINT32)getc(IN) << 8;
header->biIntent |= (OPJ_UINT32)getc(IN) << 16;
header->biIntent |= (OPJ_UINT32)getc(IN) << 24;
header->biIccProfileData = (OPJ_UINT32)getc(IN);
header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 8;
header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 16;
header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 24;
header->biIccProfileSize = (OPJ_UINT32)getc(IN);
header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 8;
header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 16;
header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 24;
header->biReserved = (OPJ_UINT32)getc(IN);
header->biReserved |= (OPJ_UINT32)getc(IN) << 8;
header->biReserved |= (OPJ_UINT32)getc(IN) << 16;
header->biReserved |= (OPJ_UINT32)getc(IN) << 24;
}
return OPJ_TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'bmp_read_info_header(): reject bmp files with biBitCount == 0 (#983)'</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 Image *ReadSFWImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
static unsigned char
HuffmanTable[] =
{
0xFF, 0xC4, 0x01, 0xA2, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04,
0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x10, 0x00, 0x02, 0x01,
0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00,
0x01, 0x7D, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21,
0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32,
0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1,
0xF0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18,
0x19, 0x1A, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36,
0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64,
0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A,
0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3,
0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5,
0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,
0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9,
0xDA, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA,
0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0x11,
0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04,
0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04,
0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13,
0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09,
0x23, 0x33, 0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24,
0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26, 0x27, 0x28,
0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45,
0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73,
0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85,
0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9,
0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2,
0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4,
0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6,
0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
0xF9, 0xFA
};
FILE
*file;
Image
*flipped_image,
*jpeg_image,
*image;
ImageInfo
*read_info;
int
unique_file;
MagickBooleanType
status;
register unsigned char
*header,
*data;
size_t
extent;
ssize_t
count;
unsigned char
*buffer,
*offset;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read image into a buffer.
*/
if (GetBlobSize(image) != (size_t) GetBlobSize(image))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
buffer=(unsigned char *) AcquireQuantumMemory((size_t) GetBlobSize(image),
sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) GetBlobSize(image),buffer);
if ((count != (ssize_t) GetBlobSize(image)) ||
(LocaleNCompare((char *) buffer,"SFW",3) != 0))
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
(void) CloseBlob(image);
/*
Find the start of the JFIF data
*/
header=SFWScan(buffer,buffer+count-1,(const unsigned char *)
"\377\310\377\320",4);
if (header == (unsigned char *) NULL)
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
TranslateSFWMarker(header); /* translate soi and app tags */
TranslateSFWMarker(header+2);
(void) CopyMagickMemory(header+6,"JFIF\0\001\0",7); /* JFIF magic */
/*
Translate remaining markers.
*/
offset=header+2;
offset+=(((unsigned int) offset[2]) << 8)+offset[3]+2;
for ( ; ; )
{
if ((offset+4) > (buffer+count-1))
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
TranslateSFWMarker(offset);
if (offset[1] == 0xda)
break;
offset+=(((unsigned int) offset[2]) << 8)+offset[3]+2;
}
offset--;
data=SFWScan(offset,buffer+count-1,(const unsigned char *) "\377\311",2);
if (data == (unsigned char *) NULL)
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
TranslateSFWMarker(data++); /* translate eoi marker */
/*
Write JFIF file.
*/
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(read_info->filename);
if (unique_file != -1)
file=fopen_utf8(read_info->filename,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
read_info=DestroyImageInfo(read_info);
(void) CopyMagickString(image->filename,read_info->filename,
MagickPathExtent);
ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
extent=fwrite(header,(size_t) (offset-header+1),1,file);
(void) extent;
extent=fwrite(HuffmanTable,1,sizeof(HuffmanTable)/sizeof(*HuffmanTable),file);
extent=fwrite(offset+1,(size_t) (data-offset),1,file);
status=ferror(file) != 0 ? MagickFalse : MagickTrue;
(void) fclose(file);
(void) close(unique_file);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
if (status == MagickFalse)
{
char
*message;
(void) remove_utf8(read_info->filename);
read_info=DestroyImageInfo(read_info);
message=GetExceptionMessage(errno);
(void) ThrowMagickException(exception,GetMagickModule(),FileOpenError,
"UnableToWriteFile","`%s': %s",image->filename,message);
message=DestroyString(message);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read JPEG image.
*/
jpeg_image=ReadImage(read_info,exception);
(void) RelinquishUniqueFileResource(read_info->filename);
read_info=DestroyImageInfo(read_info);
if (jpeg_image == (Image *) NULL)
{
image=DestroyImageList(image);
return(jpeg_image);
}
(void) CopyMagickString(jpeg_image->filename,image->filename,MagickPathExtent);
(void) CopyMagickString(jpeg_image->magick,image->magick,MagickPathExtent);
image=DestroyImageList(image);
image=jpeg_image;
/*
Correct image orientation.
*/
flipped_image=FlipImage(image,exception);
if (flipped_image != (Image *) NULL)
{
DuplicateBlob(flipped_image,image);
image=DestroyImage(image);
image=flipped_image;
}
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/682'</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: on_unregister_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gpointer user_data)
{
struct tcmur_handler *handler = find_handler_by_subtype(subtype);
struct dbus_info *info = handler->opaque;
if (!handler) {
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE,
"unknown subtype"));
return TRUE;
}
dbus_unexport_handler(handler);
tcmur_unregister_handler(handler);
g_bus_unwatch_name(info->watcher_id);
g_free(info);
g_free(handler);
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'fixed local DoS when UnregisterHandler was called for a not existing handler
Any user with DBUS access could cause a SEGFAULT in tcmu-runner by
running something like this:
dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:123'</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: on_handler_vanished(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
struct tcmur_handler *handler = user_data;
struct dbus_info *info = handler->opaque;
if (info->register_invocation) {
char *reason;
reason = g_strdup_printf("Cannot find handler bus name: "
"org.kernel.TCMUService1.HandlerManager1.%s",
handler->subtype);
g_dbus_method_invocation_return_value(info->register_invocation,
g_variant_new("(bs)", FALSE, reason));
g_free(reason);
}
tcmur_unregister_handler(handler);
dbus_unexport_handler(handler);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS
Trying to unregister an internal handler ended up in a SEGFAULT, because
the tcmur_handler->opaque was NULL. Way to reproduce:
dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow
we use a newly introduced boolean in struct tcmur_handler for keeping
track of external handlers. As suggested by mikechristie adjusting the
public data structure is acceptable.'</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: on_unregister_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gpointer user_data)
{
struct tcmur_handler *handler = find_handler_by_subtype(subtype);
struct dbus_info *info = handler ? handler->opaque : NULL;
if (!handler) {
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE,
"unknown subtype"));
return TRUE;
}
dbus_unexport_handler(handler);
tcmur_unregister_handler(handler);
g_bus_unwatch_name(info->watcher_id);
g_free(info);
g_free(handler);
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-476'], 'message': 'only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS
Trying to unregister an internal handler ended up in a SEGFAULT, because
the tcmur_handler->opaque was NULL. Way to reproduce:
dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow
we use a newly introduced boolean in struct tcmur_handler for keeping
track of external handlers. As suggested by mikechristie adjusting the
public data structure is acceptable.'</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 foo_check_config(const char *cfgstring, char **reason)
{
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'removed all check_config callback implementations to avoid security issues
see github issue #194
qcow.c contained an information leak, could test for existance of any
file in the system
file_example.c and file_optical.c allow also to test for existance of
any file, plus to temporarily create empty new files anywhere in the
file system. This also involves a race condition, if a file didn't exist
in the first place, but would be created in-between by some other
process, then the file would be deleted by the check_config
implementation.'</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 syn_check_config(const char *cfgstring, char **reason)
{
tcmu_dbg("syn check config\n");
if (strcmp(cfgstring, "syn/null")) {
asprintf(reason, "invalid option");
return false;
}
return true;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'removed all check_config callback implementations to avoid security issues
see github issue #194
qcow.c contained an information leak, could test for existance of any
file in the system
file_example.c and file_optical.c allow also to test for existance of
any file, plus to temporarily create empty new files anywhere in the
file system. This also involves a race condition, if a file didn't exist
in the first place, but would be created in-between by some other
process, then the file would be deleted by the check_config
implementation.'</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 tcp_disconnect(struct sock *sk, int flags)
{
struct inet_sock *inet = inet_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
int err = 0;
int old_state = sk->sk_state;
if (old_state != TCP_CLOSE)
tcp_set_state(sk, TCP_CLOSE);
/* ABORT function of RFC793 */
if (old_state == TCP_LISTEN) {
inet_csk_listen_stop(sk);
} else if (unlikely(tp->repair)) {
sk->sk_err = ECONNABORTED;
} else if (tcp_need_reset(old_state) ||
(tp->snd_nxt != tp->write_seq &&
(1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
/* The last check adjusts for discrepancy of Linux wrt. RFC
* states
*/
tcp_send_active_reset(sk, gfp_any());
sk->sk_err = ECONNRESET;
} else if (old_state == TCP_SYN_SENT)
sk->sk_err = ECONNRESET;
tcp_clear_xmit_timers(sk);
__skb_queue_purge(&sk->sk_receive_queue);
tcp_write_queue_purge(sk);
tcp_fastopen_active_disable_ofo_check(sk);
skb_rbtree_purge(&tp->out_of_order_queue);
inet->inet_dport = 0;
if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
inet_reset_saddr(sk);
sk->sk_shutdown = 0;
sock_reset_flag(sk, SOCK_DONE);
tp->srtt_us = 0;
tp->write_seq += tp->max_window + 2;
if (tp->write_seq == 0)
tp->write_seq = 1;
icsk->icsk_backoff = 0;
tp->snd_cwnd = 2;
icsk->icsk_probes_out = 0;
tp->packets_out = 0;
tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
tp->snd_cwnd_cnt = 0;
tp->window_clamp = 0;
tcp_set_ca_state(sk, TCP_CA_Open);
tcp_clear_retrans(tp);
inet_csk_delack_init(sk);
tcp_init_send_head(sk);
memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
__sk_dst_reset(sk);
tcp_saved_syn_free(tp);
/* Clean up fastopen related fields */
tcp_free_fastopen_req(tp);
inet->defer_connect = 0;
WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
sk->sk_error_report(sk);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-369'], 'message': 'tcp: initialize rcv_mss to TCP_MIN_MSS instead of 0
When tcp_disconnect() is called, inet_csk_delack_init() sets
icsk->icsk_ack.rcv_mss to 0.
This could potentially cause tcp_recvmsg() => tcp_cleanup_rbuf() =>
__tcp_select_window() call path to have division by 0 issue.
So this patch initializes rcv_mss to TCP_MIN_MSS instead of 0.
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: Wei Wang <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: Neal Cardwell <[email protected]>
Signed-off-by: Yuchung Cheng <[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 tga_readheader(FILE *fp, unsigned int *bits_per_pixel,
unsigned int *width, unsigned int *height, int *flip_image)
{
int palette_size;
unsigned char tga[TGA_HEADER_SIZE];
unsigned char id_len, /*cmap_type,*/ image_type;
unsigned char pixel_depth, image_desc;
unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size;
unsigned short /*x_origin, y_origin,*/ image_w, image_h;
if (!bits_per_pixel || !width || !height || !flip_image) {
return 0;
}
if (fread(tga, TGA_HEADER_SIZE, 1, fp) != 1) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
return 0 ;
}
id_len = tga[0];
/*cmap_type = tga[1];*/
image_type = tga[2];
/*cmap_index = get_ushort(&tga[3]);*/
cmap_len = get_ushort(&tga[5]);
cmap_entry_size = tga[7];
#if 0
x_origin = get_ushort(&tga[8]);
y_origin = get_ushort(&tga[10]);
#endif
image_w = get_ushort(&tga[12]);
image_h = get_ushort(&tga[14]);
pixel_depth = tga[16];
image_desc = tga[17];
*bits_per_pixel = (unsigned int)pixel_depth;
*width = (unsigned int)image_w;
*height = (unsigned int)image_h;
/* Ignore tga identifier, if present ... */
if (id_len) {
unsigned char *id = (unsigned char *) malloc(id_len);
if (id == 0) {
fprintf(stderr, "tga_readheader: memory out\n");
return 0;
}
if (!fread(id, id_len, 1, fp)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
free(id);
return 0 ;
}
free(id);
}
/* Test for compressed formats ... not yet supported ...
// Note :- 9 - RLE encoded palettized.
// 10 - RLE encoded RGB. */
if (image_type > 8) {
fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n");
return 0 ;
}
*flip_image = !(image_desc & 32);
/* Palettized formats are not yet supported, skip over the palette, if present ... */
palette_size = cmap_len * (cmap_entry_size / 8);
if (palette_size > 0) {
fprintf(stderr, "File contains a palette - not yet supported.");
fseek(fp, palette_size, SEEK_CUR);
}
return 1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'tgatoimage(): avoid excessive memory allocation attempt, and fixes unaligned load (#995)'</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: opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters)
{
FILE *f;
opj_image_t *image;
unsigned int image_width, image_height, pixel_bit_depth;
unsigned int x, y;
int flip_image = 0;
opj_image_cmptparm_t cmptparm[4]; /* maximum 4 components */
int numcomps;
OPJ_COLOR_SPACE color_space;
OPJ_BOOL mono ;
OPJ_BOOL save_alpha;
int subsampling_dx, subsampling_dy;
int i;
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !!\n", filename);
return 0;
}
if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height,
&flip_image)) {
fclose(f);
return NULL;
}
/* We currently only support 24 & 32 bit tga's ... */
if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) {
fclose(f);
return NULL;
}
/* initialize image components */
memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
mono = (pixel_bit_depth == 8) ||
(pixel_bit_depth == 16); /* Mono with & without alpha. */
save_alpha = (pixel_bit_depth == 16) ||
(pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */
if (mono) {
color_space = OPJ_CLRSPC_GRAY;
numcomps = save_alpha ? 2 : 1;
} else {
numcomps = save_alpha ? 4 : 3;
color_space = OPJ_CLRSPC_SRGB;
}
subsampling_dx = parameters->subsampling_dx;
subsampling_dy = parameters->subsampling_dy;
for (i = 0; i < numcomps; i++) {
cmptparm[i].prec = 8;
cmptparm[i].bpp = 8;
cmptparm[i].sgnd = 0;
cmptparm[i].dx = (OPJ_UINT32)subsampling_dx;
cmptparm[i].dy = (OPJ_UINT32)subsampling_dy;
cmptparm[i].w = image_width;
cmptparm[i].h = image_height;
}
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = (OPJ_UINT32)parameters->image_offset_x0;
image->y0 = (OPJ_UINT32)parameters->image_offset_y0;
image->x1 = !image->x0 ? (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1) *
(OPJ_UINT32)subsampling_dx + 1;
image->y1 = !image->y0 ? (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) *
(OPJ_UINT32)subsampling_dy + 1;
/* set image data */
for (y = 0; y < image_height; y++) {
int index;
if (flip_image) {
index = (int)((image_height - y - 1) * image_width);
} else {
index = (int)(y * image_width);
}
if (numcomps == 3) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
index++;
}
} else if (numcomps == 4) {
for (x = 0; x < image_width; x++) {
unsigned char r, g, b, a;
if (!fread(&b, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&g, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&r, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
if (!fread(&a, 1, 1, f)) {
fprintf(stderr,
"\nError: fread return a number of element different from the expected.\n");
opj_image_destroy(image);
fclose(f);
return NULL;
}
image->comps[0].data[index] = r;
image->comps[1].data[index] = g;
image->comps[2].data[index] = b;
image->comps[3].data[index] = a;
index++;
}
} else {
fprintf(stderr, "Currently unsupported bit depth : %s\n", filename);
}
}
fclose(f);
return image;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'tgatoimage(): avoid excessive memory allocation attempt, and fixes unaligned load (#995)'</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 OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
OPJ_UINT32 index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
OPJ_UINT32 resno;
comp = &pi->comps[pi->compno];
pi->dx = 0;
pi->dy = 0;
for (resno = 0; resno < comp->numresolutions; resno++) {
OPJ_UINT32 dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy);
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) {
for (pi->resno = pi->poc.resno0;
pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
OPJ_UINT32 levelno;
OPJ_INT32 trx0, try0;
OPJ_INT32 trx1, try1;
OPJ_UINT32 rpx, rpy;
OPJ_INT32 prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno));
try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno));
trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno));
try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno));
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x,
(OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx)
- opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx);
prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y,
(OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy)
- opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy);
pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw);
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-369'], 'message': 'Avoid division by zero in opj_pi_next_rpcl, opj_pi_next_pcrl and opj_pi_next_cprl (#938)
Fixes issues with id:000026,sig:08,src:002419,op:int32,pos:60,val:+32 and
id:000019,sig:08,src:001098,op:flip1,pos:49'</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 OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
OPJ_UINT32 index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
OPJ_UINT32 compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
OPJ_UINT32 dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
for (pi->resno = pi->poc.resno0;
pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
OPJ_UINT32 levelno;
OPJ_INT32 trx0, try0;
OPJ_INT32 trx1, try1;
OPJ_UINT32 rpx, rpy;
OPJ_INT32 prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno));
try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno));
trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno));
try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno));
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x,
(OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx)
- opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx);
prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y,
(OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy)
- opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy);
pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw);
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-369'], 'message': 'Avoid division by zero in opj_pi_next_rpcl, opj_pi_next_pcrl and opj_pi_next_cprl (#938)
Fixes issues with id:000026,sig:08,src:002419,op:int32,pos:60,val:+32 and
id:000019,sig:08,src:001098,op:flip1,pos:49'</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 OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *
p_code_block)
{
OPJ_UINT32 l_data_size;
/* The +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */
l_data_size = 1 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *
(p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));
if (l_data_size > p_code_block->data_size) {
if (p_code_block->data) {
/* We refer to data - 1 since below we incremented it */
opj_free(p_code_block->data - 1);
}
p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);
if (! p_code_block->data) {
p_code_block->data_size = 0U;
return OPJ_FALSE;
}
p_code_block->data_size = l_data_size;
/* We reserve the initial byte as a fake byte to a non-FF value */
/* and increment the data pointer, so that opj_mqc_init_enc() */
/* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */
/* it. */
p_code_block->data[0] = 0;
p_code_block->data += 1; /*why +1 ?*/
}
return OPJ_TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Encoder: grow buffer size in opj_tcd_code_block_enc_allocate_data() to avoid write heap buffer overflow in opj_mqc_flush (#982)'</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 *fstrndup(const char *ptr, unsigned long len) {
char *result;
if (len <= 0) return NULL;
result = ALLOC_N(char, len);
memccpy(result, ptr, 0, len);
return result;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix arbitrary heap exposure problem'</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 VALUE cState_indent_set(VALUE self, VALUE indent)
{
unsigned long len;
GET_STATE(self);
Check_Type(indent, T_STRING);
len = RSTRING_LEN(indent);
if (len == 0) {
if (state->indent) {
ruby_xfree(state->indent);
state->indent = NULL;
state->indent_len = 0;
}
} else {
if (state->indent) ruby_xfree(state->indent);
state->indent = strdup(RSTRING_PTR(indent));
state->indent_len = len;
}
return Qnil;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix arbitrary heap exposure problem'</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 VALUE cState_array_nl_set(VALUE self, VALUE array_nl)
{
unsigned long len;
GET_STATE(self);
Check_Type(array_nl, T_STRING);
len = RSTRING_LEN(array_nl);
if (len == 0) {
if (state->array_nl) {
ruby_xfree(state->array_nl);
state->array_nl = NULL;
}
} else {
if (state->array_nl) ruby_xfree(state->array_nl);
state->array_nl = strdup(RSTRING_PTR(array_nl));
state->array_nl_len = len;
}
return Qnil;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix arbitrary heap exposure problem'</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 OPJ_BOOL opj_t2_encode_packet(OPJ_UINT32 tileno,
opj_tcd_tile_t * tile,
opj_tcp_t * tcp,
opj_pi_iterator_t *pi,
OPJ_BYTE *dest,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 length,
opj_codestream_info_t *cstr_info,
J2K_T2_MODE p_t2_mode,
opj_event_mgr_t *p_manager)
{
OPJ_UINT32 bandno, cblkno;
OPJ_BYTE* c = dest;
OPJ_UINT32 l_nb_bytes;
OPJ_UINT32 compno = pi->compno; /* component value */
OPJ_UINT32 resno = pi->resno; /* resolution level value */
OPJ_UINT32 precno = pi->precno; /* precinct value */
OPJ_UINT32 layno = pi->layno; /* quality layer value */
OPJ_UINT32 l_nb_blocks;
opj_tcd_band_t *band = 00;
opj_tcd_cblk_enc_t* cblk = 00;
opj_tcd_pass_t *pass = 00;
opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
opj_bio_t *bio = 00; /* BIO component */
OPJ_BOOL packet_empty = OPJ_TRUE;
/* <SOP 0xff91> */
if (tcp->csty & J2K_CP_CSTY_SOP) {
c[0] = 255;
c[1] = 145;
c[2] = 0;
c[3] = 4;
#if 0
c[4] = (tile->packno % 65536) / 256;
c[5] = (tile->packno % 65536) % 256;
#else
c[4] = (tile->packno >> 8) & 0xff; /* packno is uint32_t */
c[5] = tile->packno & 0xff;
#endif
c += 6;
length -= 6;
}
/* </SOP> */
if (!layno) {
band = res->bands;
for (bandno = 0; bandno < res->numbands; ++bandno, ++band) {
opj_tcd_precinct_t *prc;
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
prc = &band->precincts[precno];
opj_tgt_reset(prc->incltree);
opj_tgt_reset(prc->imsbtree);
l_nb_blocks = prc->cw * prc->ch;
for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
cblk = &prc->cblks.enc[cblkno];
cblk->numpasses = 0;
opj_tgt_setvalue(prc->imsbtree, cblkno, band->numbps - (OPJ_INT32)cblk->numbps);
}
}
}
bio = opj_bio_create();
if (!bio) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
opj_bio_init_enc(bio, c, length);
/* Check if the packet is empty */
/* Note: we could also skip that step and always write a packet header */
band = res->bands;
for (bandno = 0; bandno < res->numbands; ++bandno, ++band) {
opj_tcd_precinct_t *prc;
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
prc = &band->precincts[precno];
l_nb_blocks = prc->cw * prc->ch;
cblk = prc->cblks.enc;
for (cblkno = 0; cblkno < l_nb_blocks; cblkno++, ++cblk) {
opj_tcd_layer_t *layer = &cblk->layers[layno];
/* if cblk not included, go to the next cblk */
if (!layer->numpasses) {
continue;
}
packet_empty = OPJ_FALSE;
break;
}
if (!packet_empty) {
break;
}
}
opj_bio_write(bio, packet_empty ? 0 : 1, 1); /* Empty header bit */
/* Writing Packet header */
band = res->bands;
for (bandno = 0; !packet_empty &&
bandno < res->numbands; ++bandno, ++band) {
opj_tcd_precinct_t *prc;
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
prc = &band->precincts[precno];
l_nb_blocks = prc->cw * prc->ch;
cblk = prc->cblks.enc;
for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
opj_tcd_layer_t *layer = &cblk->layers[layno];
if (!cblk->numpasses && layer->numpasses) {
opj_tgt_setvalue(prc->incltree, cblkno, (OPJ_INT32)layno);
}
++cblk;
}
cblk = prc->cblks.enc;
for (cblkno = 0; cblkno < l_nb_blocks; cblkno++) {
opj_tcd_layer_t *layer = &cblk->layers[layno];
OPJ_UINT32 increment = 0;
OPJ_UINT32 nump = 0;
OPJ_UINT32 len = 0, passno;
OPJ_UINT32 l_nb_passes;
/* cblk inclusion bits */
if (!cblk->numpasses) {
opj_tgt_encode(bio, prc->incltree, cblkno, (OPJ_INT32)(layno + 1));
} else {
opj_bio_write(bio, layer->numpasses != 0, 1);
}
/* if cblk not included, go to the next cblk */
if (!layer->numpasses) {
++cblk;
continue;
}
/* if first instance of cblk --> zero bit-planes information */
if (!cblk->numpasses) {
cblk->numlenbits = 3;
opj_tgt_encode(bio, prc->imsbtree, cblkno, 999);
}
/* number of coding passes included */
opj_t2_putnumpasses(bio, layer->numpasses);
l_nb_passes = cblk->numpasses + layer->numpasses;
pass = cblk->passes + cblk->numpasses;
/* computation of the increase of the length indicator and insertion in the header */
for (passno = cblk->numpasses; passno < l_nb_passes; ++passno) {
++nump;
len += pass->len;
if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
increment = (OPJ_UINT32)opj_int_max((OPJ_INT32)increment,
opj_int_floorlog2((OPJ_INT32)len) + 1
- ((OPJ_INT32)cblk->numlenbits + opj_int_floorlog2((OPJ_INT32)nump)));
len = 0;
nump = 0;
}
++pass;
}
opj_t2_putcommacode(bio, (OPJ_INT32)increment);
/* computation of the new Length indicator */
cblk->numlenbits += increment;
pass = cblk->passes + cblk->numpasses;
/* insertion of the codeword segment length */
for (passno = cblk->numpasses; passno < l_nb_passes; ++passno) {
nump++;
len += pass->len;
if (pass->term || passno == (cblk->numpasses + layer->numpasses) - 1) {
opj_bio_write(bio, (OPJ_UINT32)len,
cblk->numlenbits + (OPJ_UINT32)opj_int_floorlog2((OPJ_INT32)nump));
len = 0;
nump = 0;
}
++pass;
}
++cblk;
}
}
if (!opj_bio_flush(bio)) {
opj_bio_destroy(bio);
return OPJ_FALSE; /* modified to eliminate longjmp !! */
}
l_nb_bytes = (OPJ_UINT32)opj_bio_numbytes(bio);
c += l_nb_bytes;
length -= l_nb_bytes;
opj_bio_destroy(bio);
/* <EPH 0xff92> */
if (tcp->csty & J2K_CP_CSTY_EPH) {
c[0] = 255;
c[1] = 146;
c += 2;
length -= 2;
}
/* </EPH> */
/* << INDEX */
/* End of packet header position. Currently only represents the distance to start of packet
Will be updated later by incrementing with packet start value*/
if (cstr_info && cstr_info->index_write) {
opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno];
info_PK->end_ph_pos = (OPJ_INT32)(c - dest);
}
/* INDEX >> */
/* Writing the packet body */
band = res->bands;
for (bandno = 0; !packet_empty && bandno < res->numbands; bandno++, ++band) {
opj_tcd_precinct_t *prc;
/* Skip empty bands */
if (opj_tcd_is_band_empty(band)) {
continue;
}
prc = &band->precincts[precno];
l_nb_blocks = prc->cw * prc->ch;
cblk = prc->cblks.enc;
for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
opj_tcd_layer_t *layer = &cblk->layers[layno];
if (!layer->numpasses) {
++cblk;
continue;
}
if (layer->len > length) {
if (p_t2_mode == FINAL_PASS) {
opj_event_msg(p_manager, EVT_ERROR,
"opj_t2_encode_packet(): only %u bytes remaining in "
"output buffer. %u needed.\n",
length, layer->len);
}
return OPJ_FALSE;
}
memcpy(c, layer->data, layer->len);
cblk->numpasses += layer->numpasses;
c += layer->len;
length -= layer->len;
/* << INDEX */
if (cstr_info && cstr_info->index_write) {
opj_packet_info_t *info_PK = &cstr_info->tile[tileno].packet[cstr_info->packno];
info_PK->disto += layer->disto;
if (cstr_info->D_max < info_PK->disto) {
cstr_info->D_max = info_PK->disto;
}
}
++cblk;
/* INDEX >> */
}
}
assert(c >= dest);
* p_data_written += (OPJ_UINT32)(c - dest);
return OPJ_TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-787'], 'message': 'opj_t2_encode_packet(): fix potential write heap buffer overflow (#992)'</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_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_BUILD_ID && (descsz >= 4 || descsz <= 20)) {
uint8_t desc[20];
const char *btype;
uint32_t i;
*flags |= FLAGS_DID_BUILD_ID;
switch (descsz) {
case 8:
btype = "xxHash";
break;
case 16:
btype = "md5/uuid";
break;
case 20:
btype = "sha1";
break;
default:
btype = "unknown";
break;
}
if (file_printf(ms, ", BuildID[%s]=", btype) == -1)
return 1;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return 1;
return 1;
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Fix always true condition (Thomas Jarosch)'</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: ModuleExport size_t RegisterWEBPImage(void)
{
char
version[MagickPathExtent];
MagickInfo
*entry;
*version='\0';
entry=AcquireMagickInfo("WEBP","WEBP","WebP Image Format");
#if defined(MAGICKCORE_WEBP_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadWEBPImage;
entry->encoder=(EncodeImageHandler *) WriteWEBPImage;
(void) FormatLocaleString(version,MagickPathExtent,"libwebp %d.%d.%d [%04X]",
(WebPGetDecoderVersion() >> 16) & 0xff,
(WebPGetDecoderVersion() >> 8) & 0xff,
(WebPGetDecoderVersion() >> 0) & 0xff,WEBP_DECODER_ABI_VERSION);
#endif
entry->mime_type=ConstantString("image/webp");
entry->flags^=CoderAdjoinFlag;
entry->magick=(IsImageFormatHandler *) IsWEBP;
if (*version != '\0')
entry->version=ConstantString(version);
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-400'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/641'</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: gdk_pixbuf__jpeg_image_load_increment (gpointer data,
const guchar *buf, guint size,
GError **error)
{
JpegProgContext *context = (JpegProgContext *)data;
struct jpeg_decompress_struct *cinfo;
my_src_ptr src;
guint num_left, num_copy;
guint last_num_left, last_bytes_left;
guint spinguard;
gboolean first;
const guchar *bufhd;
gint width, height;
char otag_str[5];
gchar *icc_profile_base64;
char *density_str;
JpegExifContext exif_context = { 0, };
gboolean retval;
g_return_val_if_fail (context != NULL, FALSE);
g_return_val_if_fail (buf != NULL, FALSE);
src = (my_src_ptr) context->cinfo.src;
cinfo = &context->cinfo;
context->jerr.error = error;
/* check for fatal error */
if (sigsetjmp (context->jerr.setjmp_buffer, 1)) {
retval = FALSE;
goto out;
}
/* skip over data if requested, handle unsigned int sizes cleanly */
/* only can happen if we've already called jpeg_get_header once */
if (context->src_initialized && src->skip_next) {
if (src->skip_next > size) {
src->skip_next -= size;
retval = TRUE;
goto out;
} else {
num_left = size - src->skip_next;
bufhd = buf + src->skip_next;
src->skip_next = 0;
}
} else {
num_left = size;
bufhd = buf;
}
if (num_left == 0) {
retval = TRUE;
goto out;
}
last_num_left = num_left;
last_bytes_left = 0;
spinguard = 0;
first = TRUE;
while (TRUE) {
/* handle any data from caller we haven't processed yet */
if (num_left > 0) {
if(src->pub.bytes_in_buffer &&
src->pub.next_input_byte != src->buffer)
memmove(src->buffer, src->pub.next_input_byte,
src->pub.bytes_in_buffer);
num_copy = MIN (JPEG_PROG_BUF_SIZE - src->pub.bytes_in_buffer,
num_left);
memcpy(src->buffer + src->pub.bytes_in_buffer, bufhd,num_copy);
src->pub.next_input_byte = src->buffer;
src->pub.bytes_in_buffer += num_copy;
bufhd += num_copy;
num_left -= num_copy;
}
/* did anything change from last pass, if not return */
if (first) {
last_bytes_left = src->pub.bytes_in_buffer;
first = FALSE;
} else if (src->pub.bytes_in_buffer == last_bytes_left
&& num_left == last_num_left) {
spinguard++;
} else {
last_bytes_left = src->pub.bytes_in_buffer;
last_num_left = num_left;
}
/* should not go through twice and not pull bytes out of buf */
if (spinguard > 2) {
retval = TRUE;
goto out;
}
/* try to load jpeg header */
if (!context->got_header) {
int rc;
gchar* comment;
jpeg_save_markers (cinfo, JPEG_APP0+1, 0xffff);
jpeg_save_markers (cinfo, JPEG_APP0+2, 0xffff);
jpeg_save_markers (cinfo, JPEG_COM, 0xffff);
rc = jpeg_read_header (cinfo, TRUE);
context->src_initialized = TRUE;
if (rc == JPEG_SUSPENDED)
continue;
context->got_header = TRUE;
/* parse exif data */
jpeg_parse_exif (&exif_context, cinfo);
width = cinfo->image_width;
height = cinfo->image_height;
if (context->size_func) {
(* context->size_func) (&width, &height, context->user_data);
if (width == 0 || height == 0) {
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_CORRUPT_IMAGE,
_("Transformed JPEG has zero width or height."));
retval = FALSE;
goto out;
}
}
cinfo->scale_num = 1;
for (cinfo->scale_denom = 2; cinfo->scale_denom <= 8; cinfo->scale_denom *= 2) {
jpeg_calc_output_dimensions (cinfo);
if (cinfo->output_width < width || cinfo->output_height < height) {
cinfo->scale_denom /= 2;
break;
}
}
jpeg_calc_output_dimensions (cinfo);
context->pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
cinfo->output_components == 4 ? TRUE : FALSE,
8,
cinfo->output_width,
cinfo->output_height);
if (context->pixbuf == NULL) {
g_set_error_literal (error,
GDK_PIXBUF_ERROR,
GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY,
_("Couldn't allocate memory for loading JPEG file"));
retval = FALSE;
goto out;
}
comment = jpeg_get_comment (cinfo);
if (comment != NULL) {
gdk_pixbuf_set_option (context->pixbuf, "comment", comment);
g_free (comment);
}
switch (cinfo->density_unit) {
case 1:
/* Dots per inch (no conversion required) */
density_str = g_strdup_printf ("%d", cinfo->X_density);
gdk_pixbuf_set_option (context->pixbuf, "x-dpi", density_str);
g_free (density_str);
density_str = g_strdup_printf ("%d", cinfo->Y_density);
gdk_pixbuf_set_option (context->pixbuf, "y-dpi", density_str);
g_free (density_str);
break;
case 2:
/* Dots per cm - convert into dpi */
density_str = g_strdup_printf ("%d", DPCM_TO_DPI (cinfo->X_density));
gdk_pixbuf_set_option (context->pixbuf, "x-dpi", density_str);
g_free (density_str);
density_str = g_strdup_printf ("%d", DPCM_TO_DPI (cinfo->Y_density));
gdk_pixbuf_set_option (context->pixbuf, "y-dpi", density_str);
g_free (density_str);
break;
}
/* if orientation tag was found set an option to remember its value */
if (exif_context.orientation != 0) {
g_snprintf (otag_str, sizeof (otag_str), "%d", exif_context.orientation);
gdk_pixbuf_set_option (context->pixbuf, "orientation", otag_str);
}
/* if icc profile was found */
if (exif_context.icc_profile != NULL) {
icc_profile_base64 = g_base64_encode ((const guchar *) exif_context.icc_profile, exif_context.icc_profile_size);
gdk_pixbuf_set_option (context->pixbuf, "icc-profile", icc_profile_base64);
g_free (icc_profile_base64);
}
/* Use pixbuf buffer to store decompressed data */
context->dptr = context->pixbuf->pixels;
/* Notify the client that we are ready to go */
if (context->prepared_func)
(* context->prepared_func) (context->pixbuf,
NULL,
context->user_data);
} else if (!context->did_prescan) {
int rc;
/* start decompression */
cinfo->buffered_image = cinfo->progressive_mode;
rc = jpeg_start_decompress (cinfo);
cinfo->do_fancy_upsampling = FALSE;
cinfo->do_block_smoothing = FALSE;
if (rc == JPEG_SUSPENDED)
continue;
context->did_prescan = TRUE;
} else if (!cinfo->buffered_image) {
/* we're decompressing unbuffered so
* simply get scanline by scanline from jpeg lib
*/
if (! gdk_pixbuf__jpeg_image_load_lines (context,
error)) {
retval = FALSE;
goto out;
}
if (cinfo->output_scanline >= cinfo->output_height) {
retval = TRUE;
goto out;
}
} else {
/* we're decompressing buffered (progressive)
* so feed jpeg lib scanlines
*/
/* keep going until we've done all passes */
while (!jpeg_input_complete (cinfo)) {
if (!context->in_output) {
if (jpeg_start_output (cinfo, cinfo->input_scan_number)) {
context->in_output = TRUE;
context->dptr = context->pixbuf->pixels;
}
else
break;
}
/* get scanlines from jpeg lib */
if (! gdk_pixbuf__jpeg_image_load_lines (context,
error)) {
retval = FALSE;
goto out;
}
if (cinfo->output_scanline >= cinfo->output_height &&
jpeg_finish_output (cinfo))
context->in_output = FALSE;
else
break;
}
if (jpeg_input_complete (cinfo)) {
/* did entire image */
retval = TRUE;
goto out;
}
else
continue;
}
}
out:
jpeg_destroy_exif_context (&exif_context);
return retval;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'jpeg: Throw error when number of color components is unsupported
Explicitly check "3" or "4" output color components.
gdk-pixbuf assumed that the value of output_components to be either
3 or 4, but not an invalid value (9) or an unsupported value (1).
The way the buffer size was deduced was using a naive "== 4" check,
with a 1, 3 or 9 color component picture getting the same buffer size,
a size just sufficient for 3 color components, causing invalid writes
later when libjpeg-turbo was decoding the image.
CVE-2017-2862
Sent by from Marcin 'Icewall' Noga of Cisco Talos
https://bugzilla.gnome.org/show_bug.cgi?id=784866'</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: gss_wrap( OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
gss_buffer_t input_message_buffer,
int *conf_state,
gss_buffer_t output_message_buffer)
{
/* EXPORT DELETE START */
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
status = val_wrap_args(minor_status, context_handle,
conf_req_flag, qop_req,
input_message_buffer, conf_state,
output_message_buffer);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (mech) {
if (mech->gss_wrap) {
status = mech->gss_wrap(minor_status,
ctx->internal_ctx_id,
conf_req_flag,
qop_req,
input_message_buffer,
conf_state,
output_message_buffer);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else if (mech->gss_wrap_aead ||
(mech->gss_wrap_iov && mech->gss_wrap_iov_length)) {
status = gssint_wrap_aead(mech,
minor_status,
ctx,
conf_req_flag,
(gss_qop_t)qop_req,
GSS_C_NO_BUFFER,
input_message_buffer,
conf_state,
output_message_buffer);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
/* EXPORT DELETE END */
return (GSS_S_BAD_MECH);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
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: gss_export_sec_context(minor_status,
context_handle,
interprocess_token)
OM_uint32 * minor_status;
gss_ctx_id_t * context_handle;
gss_buffer_t interprocess_token;
{
OM_uint32 status;
OM_uint32 length;
gss_union_ctx_id_t ctx = NULL;
gss_mechanism mech;
gss_buffer_desc token = GSS_C_EMPTY_BUFFER;
char *buf;
status = val_exp_sec_ctx_args(minor_status,
context_handle, interprocess_token);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) *context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (!mech)
return GSS_S_BAD_MECH;
if (!mech->gss_export_sec_context)
return (GSS_S_UNAVAILABLE);
status = mech->gss_export_sec_context(minor_status,
&ctx->internal_ctx_id, &token);
if (status != GSS_S_COMPLETE) {
map_error(minor_status, mech);
goto cleanup;
}
length = token.length + 4 + ctx->mech_type->length;
interprocess_token->length = length;
interprocess_token->value = malloc(length);
if (interprocess_token->value == 0) {
*minor_status = ENOMEM;
status = GSS_S_FAILURE;
goto cleanup;
}
buf = interprocess_token->value;
length = ctx->mech_type->length;
buf[3] = (unsigned char) (length & 0xFF);
length >>= 8;
buf[2] = (unsigned char) (length & 0xFF);
length >>= 8;
buf[1] = (unsigned char) (length & 0xFF);
length >>= 8;
buf[0] = (unsigned char) (length & 0xFF);
memcpy(buf+4, ctx->mech_type->elements, (size_t) ctx->mech_type->length);
memcpy(buf+4+ctx->mech_type->length, token.value, token.length);
status = GSS_S_COMPLETE;
cleanup:
(void) gss_release_buffer(minor_status, &token);
if (ctx != NULL && ctx->internal_ctx_id == GSS_C_NO_CONTEXT) {
/* If the mech deleted its context, delete the union context. */
free(ctx->mech_type->elements);
free(ctx->mech_type);
free(ctx);
*context_handle = GSS_C_NO_CONTEXT;
}
return status;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
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: gss_process_context_token (minor_status,
context_handle,
token_buffer)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
gss_buffer_t token_buffer;
{
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
if (minor_status == NULL)
return (GSS_S_CALL_INACCESSIBLE_WRITE);
*minor_status = 0;
if (context_handle == GSS_C_NO_CONTEXT)
return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT);
if (token_buffer == GSS_C_NO_BUFFER)
return (GSS_S_CALL_INACCESSIBLE_READ);
if (GSS_EMPTY_BUFFER(token_buffer))
return (GSS_S_CALL_INACCESSIBLE_READ);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (mech) {
if (mech->gss_process_context_token) {
status = mech->gss_process_context_token(
minor_status,
ctx->internal_ctx_id,
token_buffer);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
return (GSS_S_BAD_MECH);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
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: gss_pseudo_random (OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int prf_key,
const gss_buffer_t prf_in,
ssize_t desired_output_len,
gss_buffer_t prf_out)
{
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
if (minor_status == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
if (context_handle == GSS_C_NO_CONTEXT)
return GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT;
if (prf_in == GSS_C_NO_BUFFER)
return GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT;
if (prf_out == GSS_C_NO_BUFFER)
return GSS_S_CALL_INACCESSIBLE_WRITE | GSS_S_NO_CONTEXT;
prf_out->length = 0;
prf_out->value = NULL;
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (mech != NULL) {
if (mech->gss_pseudo_random != NULL) {
status = mech->gss_pseudo_random(minor_status,
ctx->internal_ctx_id,
prf_key,
prf_in,
desired_output_len,
prf_out);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else
status = GSS_S_UNAVAILABLE;
return status;
}
return GSS_S_BAD_MECH;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
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: gss_inquire_context(
OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
gss_name_t *src_name,
gss_name_t *targ_name,
OM_uint32 *lifetime_rec,
gss_OID *mech_type,
OM_uint32 *ctx_flags,
int *locally_initiated,
int *opened)
{
gss_union_ctx_id_t ctx;
gss_mechanism mech;
OM_uint32 status, temp_minor;
gss_OID actual_mech;
gss_name_t localTargName = NULL, localSourceName = NULL;
status = val_inq_ctx_args(minor_status,
context_handle,
src_name, targ_name,
lifetime_rec,
mech_type, ctx_flags,
locally_initiated, opened);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (!mech || !mech->gss_inquire_context || !mech->gss_display_name ||
!mech->gss_release_name) {
return (GSS_S_UNAVAILABLE);
}
status = mech->gss_inquire_context(
minor_status,
ctx->internal_ctx_id,
(src_name ? &localSourceName : NULL),
(targ_name ? &localTargName : NULL),
lifetime_rec,
&actual_mech,
ctx_flags,
locally_initiated,
opened);
if (status != GSS_S_COMPLETE) {
map_error(minor_status, mech);
return status;
}
/* need to convert names */
if (src_name) {
if (localSourceName) {
status = gssint_convert_name_to_union_name(minor_status, mech,
localSourceName, src_name);
if (status != GSS_S_COMPLETE) {
if (localTargName)
mech->gss_release_name(&temp_minor, &localTargName);
return (status);
}
} else {
*src_name = GSS_C_NO_NAME;
}
}
if (targ_name) {
if (localTargName) {
status = gssint_convert_name_to_union_name(minor_status, mech,
localTargName, targ_name);
if (status != GSS_S_COMPLETE) {
if (src_name)
(void) gss_release_name(&temp_minor, src_name);
return (status);
}
}
else {
*targ_name = GSS_C_NO_NAME;
}
}
if (mech_type)
*mech_type = gssint_get_public_oid(actual_mech);
return(GSS_S_COMPLETE);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-415'], 'message': 'Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup'</s> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.