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: static int php_snmp_write_oid_output_format(php_snmp_object *snmp_object, zval *newval TSRMLS_DC)
{
zval ztmp;
int ret = SUCCESS;
if (Z_TYPE_P(newval) != IS_LONG) {
ztmp = *newval;
zval_copy_ctor(&ztmp);
convert_to_long(&ztmp);
newval = &ztmp;
}
switch(Z_LVAL_P(newval)) {
case NETSNMP_OID_OUTPUT_SUFFIX:
case NETSNMP_OID_OUTPUT_MODULE:
case NETSNMP_OID_OUTPUT_FULL:
case NETSNMP_OID_OUTPUT_NUMERIC:
case NETSNMP_OID_OUTPUT_UCD:
case NETSNMP_OID_OUTPUT_NONE:
snmp_object->oid_output_format = Z_LVAL_P(newval);
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown SNMP output print format '%ld'", Z_LVAL_P(newval));
ret = FAILURE;
break;
}
if (newval == &ztmp) {
zval_dtor(newval);
}
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #72479 - same as #72434'</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 php_snmp_object_free_storage(void *object TSRMLS_DC)
{
php_snmp_object *intern = (php_snmp_object *)object;
if (!intern) {
return;
}
netsnmp_session_free(&(intern->session));
zend_object_std_dtor(&intern->zo TSRMLS_CC);
efree(intern);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #72479 - same as #72434'</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 php_snmp_internal(INTERNAL_FUNCTION_PARAMETERS, int st,
struct snmp_session *session,
struct objid_query *objid_query)
{
struct snmp_session *ss;
struct snmp_pdu *pdu=NULL, *response;
struct variable_list *vars;
oid root[MAX_NAME_LEN];
size_t rootlen = 0;
int status, count, found;
char buf[2048];
char buf2[2048];
int keepwalking=1;
char *err;
zval *snmpval = NULL;
int snmp_errno;
/* we start with retval=FALSE. If any actual data is acquired, retval will be set to appropriate type */
RETVAL_FALSE;
/* reset errno and errstr */
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_NOERROR, "");
if (st & SNMP_CMD_WALK) { /* remember root OID */
memmove((char *)root, (char *)(objid_query->vars[0].name), (objid_query->vars[0].name_length) * sizeof(oid));
rootlen = objid_query->vars[0].name_length;
objid_query->offset = objid_query->count;
}
if ((ss = snmp_open(session)) == NULL) {
snmp_error(session, NULL, NULL, &err);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open snmp connection: %s", err);
free(err);
RETVAL_FALSE;
return;
}
if ((st & SNMP_CMD_SET) && objid_query->count > objid_query->step) {
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES, "Can not fit all OIDs for SET query into one packet, using multiple queries");
}
while (keepwalking) {
keepwalking = 0;
if (st & SNMP_CMD_WALK) {
if (session->version == SNMP_VERSION_1) {
pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
} else {
pdu = snmp_pdu_create(SNMP_MSG_GETBULK);
pdu->non_repeaters = objid_query->non_repeaters;
pdu->max_repetitions = objid_query->max_repetitions;
}
snmp_add_null_var(pdu, objid_query->vars[0].name, objid_query->vars[0].name_length);
} else {
if (st & SNMP_CMD_GET) {
pdu = snmp_pdu_create(SNMP_MSG_GET);
} else if (st & SNMP_CMD_GETNEXT) {
pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
} else if (st & SNMP_CMD_SET) {
pdu = snmp_pdu_create(SNMP_MSG_SET);
} else {
snmp_close(ss);
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Unknown SNMP command (internals)");
RETVAL_FALSE;
return;
}
for (count = 0; objid_query->offset < objid_query->count && count < objid_query->step; objid_query->offset++, count++){
if (st & SNMP_CMD_SET) {
if ((snmp_errno = snmp_add_var(pdu, objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length, objid_query->vars[objid_query->offset].type, objid_query->vars[objid_query->offset].value))) {
snprint_objid(buf, sizeof(buf), objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Could not add variable: OID='%s' type='%c' value='%s': %s", buf, objid_query->vars[objid_query->offset].type, objid_query->vars[objid_query->offset].value, snmp_api_errstring(snmp_errno));
snmp_free_pdu(pdu);
snmp_close(ss);
RETVAL_FALSE;
return;
}
} else {
snmp_add_null_var(pdu, objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length);
}
}
if(pdu->variables == NULL){
snmp_free_pdu(pdu);
snmp_close(ss);
RETVAL_FALSE;
return;
}
}
retry:
status = snmp_synch_response(ss, pdu, &response);
if (status == STAT_SUCCESS) {
if (response->errstat == SNMP_ERR_NOERROR) {
if (st & SNMP_CMD_SET) {
if (objid_query->offset < objid_query->count) { /* we have unprocessed OIDs */
keepwalking = 1;
continue;
}
snmp_free_pdu(response);
snmp_close(ss);
RETVAL_TRUE;
return;
}
for (vars = response->variables; vars; vars = vars->next_variable) {
/* do not output errors as values */
if ( vars->type == SNMP_ENDOFMIBVIEW ||
vars->type == SNMP_NOSUCHOBJECT ||
vars->type == SNMP_NOSUCHINSTANCE ) {
if ((st & SNMP_CMD_WALK) && Z_TYPE_P(return_value) == IS_ARRAY) {
break;
}
snprint_objid(buf, sizeof(buf), vars->name, vars->name_length);
snprint_value(buf2, sizeof(buf2), vars->name, vars->name_length, vars);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at '%s': %s", buf, buf2);
continue;
}
if ((st & SNMP_CMD_WALK) &&
(vars->name_length < rootlen || memcmp(root, vars->name, rootlen * sizeof(oid)))) { /* not part of this subtree */
if (Z_TYPE_P(return_value) == IS_ARRAY) { /* some records are fetched already, shut down further lookup */
keepwalking = 0;
} else {
/* first fetched OID is out of subtree, fallback to GET query */
st |= SNMP_CMD_GET;
st ^= SNMP_CMD_WALK;
objid_query->offset = 0;
keepwalking = 1;
}
break;
}
MAKE_STD_ZVAL(snmpval);
php_snmp_getvalue(vars, snmpval TSRMLS_CC, objid_query->valueretrieval);
if (objid_query->array_output) {
if (Z_TYPE_P(return_value) == IS_BOOL) {
array_init(return_value);
}
if (st & SNMP_NUMERIC_KEYS) {
add_next_index_zval(return_value, snmpval);
} else if (st & SNMP_ORIGINAL_NAMES_AS_KEYS && st & SNMP_CMD_GET) {
found = 0;
for (count = 0; count < objid_query->count; count++) {
if (objid_query->vars[count].name_length == vars->name_length && snmp_oid_compare(objid_query->vars[count].name, objid_query->vars[count].name_length, vars->name, vars->name_length) == 0) {
found = 1;
objid_query->vars[count].name_length = 0; /* mark this name as used */
break;
}
}
if (found) {
add_assoc_zval(return_value, objid_query->vars[count].oid, snmpval);
} else {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not find original OID name for '%s'", buf2);
}
} else if (st & SNMP_USE_SUFFIX_AS_KEYS && st & SNMP_CMD_WALK) {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
if (rootlen <= vars->name_length && snmp_oid_compare(root, rootlen, vars->name, rootlen) == 0) {
buf2[0] = '\0';
count = rootlen;
while(count < vars->name_length){
sprintf(buf, "%lu.", vars->name[count]);
strcat(buf2, buf);
count++;
}
buf2[strlen(buf2) - 1] = '\0'; /* remove trailing '.' */
}
add_assoc_zval(return_value, buf2, snmpval);
} else {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
add_assoc_zval(return_value, buf2, snmpval);
}
} else {
*return_value = *snmpval;
zval_copy_ctor(return_value);
zval_ptr_dtor(&snmpval);
break;
}
/* OID increase check */
if (st & SNMP_CMD_WALK) {
if (objid_query->oid_increasing_check == TRUE && snmp_oid_compare(objid_query->vars[0].name, objid_query->vars[0].name_length, vars->name, vars->name_length) >= 0) {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_NOT_INCREASING, "Error: OID not increasing: %s", buf2);
keepwalking = 0;
} else {
memmove((char *)(objid_query->vars[0].name), (char *)vars->name, vars->name_length * sizeof(oid));
objid_query->vars[0].name_length = vars->name_length;
keepwalking = 1;
}
}
}
if (objid_query->offset < objid_query->count) { /* we have unprocessed OIDs */
keepwalking = 1;
}
} else {
if (st & SNMP_CMD_WALK && response->errstat == SNMP_ERR_TOOBIG && objid_query->max_repetitions > 1) { /* Answer will not fit into single packet */
objid_query->max_repetitions /= 2;
snmp_free_pdu(response);
keepwalking = 1;
continue;
}
if (!(st & SNMP_CMD_WALK) || response->errstat != SNMP_ERR_NOSUCHNAME || Z_TYPE_P(return_value) == IS_BOOL) {
for ( count=1, vars = response->variables;
vars && count != response->errindex;
vars = vars->next_variable, count++);
if (st & (SNMP_CMD_GET | SNMP_CMD_GETNEXT) && response->errstat == SNMP_ERR_TOOBIG && objid_query->step > 1) { /* Answer will not fit into single packet */
objid_query->offset = ((objid_query->offset > objid_query->step) ? (objid_query->offset - objid_query->step) : 0 );
objid_query->step /= 2;
snmp_free_pdu(response);
keepwalking = 1;
continue;
}
if (vars) {
snprint_objid(buf, sizeof(buf), vars->name, vars->name_length);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at '%s': %s", buf, snmp_errstring(response->errstat));
} else {
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at %u object_id: %s", response->errindex, snmp_errstring(response->errstat));
}
if (st & (SNMP_CMD_GET | SNMP_CMD_GETNEXT)) { /* cut out bogus OID and retry */
if ((pdu = snmp_fix_pdu(response, ((st & SNMP_CMD_GET) ? SNMP_MSG_GET : SNMP_MSG_GETNEXT) )) != NULL) {
snmp_free_pdu(response);
goto retry;
}
}
snmp_free_pdu(response);
snmp_close(ss);
if (objid_query->array_output) {
zval_dtor(return_value);
}
RETVAL_FALSE;
return;
}
}
} else if (status == STAT_TIMEOUT) {
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_TIMEOUT, "No response from %s", session->peername);
if (objid_query->array_output) {
zval_dtor(return_value);
}
snmp_close(ss);
RETVAL_FALSE;
return;
} else { /* status == STAT_ERROR */
snmp_error(ss, NULL, NULL, &err);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_GENERIC, "Fatal error: %s", err);
free(err);
if (objid_query->array_output) {
zval_dtor(return_value);
}
snmp_close(ss);
RETVAL_FALSE;
return;
}
if (response) {
snmp_free_pdu(response);
}
} /* keepwalking */
snmp_close(ss);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #72479 - same as #72434'</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 simplestring_addn(simplestring* target, const char* source, int add_len) {
if(target && source) {
if(!target->str) {
simplestring_init_str(target);
}
if(target->len + add_len + 1 > target->size) {
/* newsize is current length + new length */
int newsize = target->len + add_len + 1;
int incr = target->size * 2;
/* align to SIMPLESTRING_INCR increments */
newsize = newsize - (newsize % incr) + incr;
target->str = (char*)realloc(target->str, newsize);
target->size = target->str ? newsize : 0;
}
if(target->str) {
if(add_len) {
memcpy(target->str + target->len, source, add_len);
}
target->len += add_len;
target->str[target->len] = 0; /* null terminate */
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72606: heap-buffer-overflow (write) simplestring_addn simplestring.c'</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_stream *php_stream_zip_opener(php_stream_wrapper *wrapper,
char *path,
char *mode,
int options,
char **opened_path,
php_stream_context *context STREAMS_DC TSRMLS_DC)
{
int path_len;
char *file_basename;
size_t file_basename_len;
char file_dirname[MAXPATHLEN];
struct zip *za;
struct zip_file *zf = NULL;
char *fragment;
int fragment_len;
int err;
php_stream *stream = NULL;
struct php_zip_stream_data_t *self;
fragment = strchr(path, '#');
if (!fragment) {
return NULL;
}
if (strncasecmp("zip://", path, 6) == 0) {
path += 6;
}
fragment_len = strlen(fragment);
if (fragment_len < 1) {
return NULL;
}
path_len = strlen(path);
if (path_len >= MAXPATHLEN || mode[0] != 'r') {
return NULL;
}
memcpy(file_dirname, path, path_len - fragment_len);
file_dirname[path_len - fragment_len] = '\0';
php_basename(path, path_len - fragment_len, NULL, 0, &file_basename, &file_basename_len TSRMLS_CC);
fragment++;
if (ZIP_OPENBASEDIR_CHECKPATH(file_dirname)) {
efree(file_basename);
return NULL;
}
za = zip_open(file_dirname, ZIP_CREATE, &err);
if (za) {
zf = zip_fopen(za, fragment, 0);
if (zf) {
self = emalloc(sizeof(*self));
self->za = za;
self->zf = zf;
self->stream = NULL;
self->cursor = 0;
stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode);
if (opened_path) {
*opened_path = estrdup(path);
}
} else {
zip_close(za);
}
}
efree(file_basename);
if (!stream) {
return NULL;
} else {
return stream;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Fix fir bug #72520'</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 esp_reg_write(ESPState *s, uint32_t saddr, uint64_t val)
{
trace_esp_mem_writeb(saddr, s->wregs[saddr], val);
switch (saddr) {
case ESP_TCHI:
s->tchi_written = true;
/* fall through */
case ESP_TCLO:
case ESP_TCMID:
s->rregs[ESP_RSTAT] &= ~STAT_TC;
break;
case ESP_FIFO:
if (s->do_cmd) {
if (s->cmdlen < TI_BUFSZ) {
s->cmdbuf[s->cmdlen++] = val & 0xff;
} else {
trace_esp_error_fifo_overrun();
}
} else if (s->ti_wptr == TI_BUFSZ - 1) {
trace_esp_error_fifo_overrun();
} else {
s->ti_size++;
s->ti_buf[s->ti_wptr++] = val & 0xff;
}
break;
case ESP_CMD:
s->rregs[saddr] = val;
if (val & CMD_DMA) {
s->dma = 1;
/* Reload DMA counter. */
s->rregs[ESP_TCLO] = s->wregs[ESP_TCLO];
s->rregs[ESP_TCMID] = s->wregs[ESP_TCMID];
s->rregs[ESP_TCHI] = s->wregs[ESP_TCHI];
} else {
s->dma = 0;
}
switch(val & CMD_CMD) {
case CMD_NOP:
trace_esp_mem_writeb_cmd_nop(val);
break;
case CMD_FLUSH:
trace_esp_mem_writeb_cmd_flush(val);
//s->ti_size = 0;
s->rregs[ESP_RINTR] = INTR_FC;
s->rregs[ESP_RSEQ] = 0;
s->rregs[ESP_RFLAGS] = 0;
break;
case CMD_RESET:
trace_esp_mem_writeb_cmd_reset(val);
esp_soft_reset(s);
break;
case CMD_BUSRESET:
trace_esp_mem_writeb_cmd_bus_reset(val);
s->rregs[ESP_RINTR] = INTR_RST;
if (!(s->wregs[ESP_CFG1] & CFG1_RESREPT)) {
esp_raise_irq(s);
}
break;
case CMD_TI:
handle_ti(s);
break;
case CMD_ICCS:
trace_esp_mem_writeb_cmd_iccs(val);
write_response(s);
s->rregs[ESP_RINTR] = INTR_FC;
s->rregs[ESP_RSTAT] |= STAT_MI;
break;
case CMD_MSGACC:
trace_esp_mem_writeb_cmd_msgacc(val);
s->rregs[ESP_RINTR] = INTR_DC;
s->rregs[ESP_RSEQ] = 0;
s->rregs[ESP_RFLAGS] = 0;
esp_raise_irq(s);
break;
case CMD_PAD:
trace_esp_mem_writeb_cmd_pad(val);
s->rregs[ESP_RSTAT] = STAT_TC;
s->rregs[ESP_RINTR] = INTR_FC;
s->rregs[ESP_RSEQ] = 0;
break;
case CMD_SATN:
trace_esp_mem_writeb_cmd_satn(val);
break;
case CMD_RSTATN:
trace_esp_mem_writeb_cmd_rstatn(val);
break;
case CMD_SEL:
trace_esp_mem_writeb_cmd_sel(val);
handle_s_without_atn(s);
break;
case CMD_SELATN:
trace_esp_mem_writeb_cmd_selatn(val);
handle_satn(s);
break;
case CMD_SELATNS:
trace_esp_mem_writeb_cmd_selatns(val);
handle_satn_stop(s);
break;
case CMD_ENSEL:
trace_esp_mem_writeb_cmd_ensel(val);
s->rregs[ESP_RINTR] = 0;
break;
case CMD_DISSEL:
trace_esp_mem_writeb_cmd_dissel(val);
s->rregs[ESP_RINTR] = 0;
esp_raise_irq(s);
break;
default:
trace_esp_error_unhandled_command(val);
break;
}
break;
case ESP_WBUSID ... ESP_WSYNO:
break;
case ESP_CFG1:
case ESP_CFG2: case ESP_CFG3:
case ESP_RES3: case ESP_RES4:
s->rregs[saddr] = val;
break;
case ESP_WCCF ... ESP_WTEST:
break;
default:
trace_esp_error_invalid_write(val, saddr);
return;
}
s->wregs[saddr] = val;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'scsi: esp: make cmdbuf big enough for maximum CDB size
While doing DMA read into ESP command buffer 's->cmdbuf', it could
write past the 's->cmdbuf' area, if it was transferring more than 16
bytes. Increase the command buffer size to 32, which is maximum when
's->do_cmd' is set, and add a check on 'len' to avoid OOB access.
Reported-by: Li Qiang <[email protected]>
Signed-off-by: Prasad J Pandit <[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 void handle_ti(ESPState *s)
{
uint32_t dmalen, minlen;
if (s->dma && !s->dma_enabled) {
s->dma_cb = handle_ti;
return;
}
dmalen = s->rregs[ESP_TCLO];
dmalen |= s->rregs[ESP_TCMID] << 8;
dmalen |= s->rregs[ESP_TCHI] << 16;
if (dmalen==0) {
dmalen=0x10000;
}
s->dma_counter = dmalen;
if (s->do_cmd)
minlen = (dmalen < 32) ? dmalen : 32;
else if (s->ti_size < 0)
minlen = (dmalen < -s->ti_size) ? dmalen : -s->ti_size;
else
minlen = (dmalen < s->ti_size) ? dmalen : s->ti_size;
trace_esp_handle_ti(minlen);
if (s->dma) {
s->dma_left = minlen;
s->rregs[ESP_RSTAT] &= ~STAT_TC;
esp_do_dma(s);
}
if (s->do_cmd) {
trace_esp_handle_ti_cmd(s->cmdlen);
s->ti_size = 0;
s->cmdlen = 0;
s->do_cmd = 0;
do_cmd(s, s->cmdbuf);
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'scsi: esp: make cmdbuf big enough for maximum CDB size
While doing DMA read into ESP command buffer 's->cmdbuf', it could
write past the 's->cmdbuf' area, if it was transferring more than 16
bytes. Increase the command buffer size to 32, which is maximum when
's->do_cmd' is set, and add a check on 'len' to avoid OOB access.
Reported-by: Li Qiang <[email protected]>
Signed-off-by: Prasad J Pandit <[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 _Bool have_gcrypt (void) /* {{{ */
{
static _Bool result = 0;
static _Bool need_init = 1;
if (!need_init)
return (result);
need_init = 0;
#if HAVE_LIBGCRYPT
# if GCRYPT_VERSION_NUMBER < 0x010600
gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
# endif
if (!gcry_check_version (GCRYPT_VERSION))
return (0);
gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
result = 1;
return (1);
#else
return(0);
#endif
} /* }}} _Bool have_gcrypt */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'network plugin, libcollectdclient: Check return value of gcry_control().
Fixes: #1665'</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 ext2_fill_super(struct super_block *sb, void *data, int silent)
{
struct buffer_head * bh;
struct ext2_sb_info * sbi;
struct ext2_super_block * es;
struct inode *root;
unsigned long block;
unsigned long sb_block = get_sb_block(&data);
unsigned long logic_sb_block;
unsigned long offset = 0;
unsigned long def_mount_opts;
long ret = -EINVAL;
int blocksize = BLOCK_SIZE;
int db_count;
int i, j;
__le32 features;
int err;
err = -ENOMEM;
sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
if (!sbi)
goto failed;
sbi->s_blockgroup_lock =
kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
if (!sbi->s_blockgroup_lock) {
kfree(sbi);
goto failed;
}
sb->s_fs_info = sbi;
sbi->s_sb_block = sb_block;
spin_lock_init(&sbi->s_lock);
/*
* See what the current blocksize for the device is, and
* use that as the blocksize. Otherwise (or if the blocksize
* is smaller than the default) use the default.
* This is important for devices that have a hardware
* sectorsize that is larger than the default.
*/
blocksize = sb_min_blocksize(sb, BLOCK_SIZE);
if (!blocksize) {
ext2_msg(sb, KERN_ERR, "error: unable to set blocksize");
goto failed_sbi;
}
/*
* If the superblock doesn't start on a hardware sector boundary,
* calculate the offset.
*/
if (blocksize != BLOCK_SIZE) {
logic_sb_block = (sb_block*BLOCK_SIZE) / blocksize;
offset = (sb_block*BLOCK_SIZE) % blocksize;
} else {
logic_sb_block = sb_block;
}
if (!(bh = sb_bread(sb, logic_sb_block))) {
ext2_msg(sb, KERN_ERR, "error: unable to read superblock");
goto failed_sbi;
}
/*
* Note: s_es must be initialized as soon as possible because
* some ext2 macro-instructions depend on its value
*/
es = (struct ext2_super_block *) (((char *)bh->b_data) + offset);
sbi->s_es = es;
sb->s_magic = le16_to_cpu(es->s_magic);
if (sb->s_magic != EXT2_SUPER_MAGIC)
goto cantfind_ext2;
/* Set defaults before we parse the mount options */
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
if (def_mount_opts & EXT2_DEFM_DEBUG)
set_opt(sbi->s_mount_opt, DEBUG);
if (def_mount_opts & EXT2_DEFM_BSDGROUPS)
set_opt(sbi->s_mount_opt, GRPID);
if (def_mount_opts & EXT2_DEFM_UID16)
set_opt(sbi->s_mount_opt, NO_UID32);
#ifdef CONFIG_EXT2_FS_XATTR
if (def_mount_opts & EXT2_DEFM_XATTR_USER)
set_opt(sbi->s_mount_opt, XATTR_USER);
#endif
#ifdef CONFIG_EXT2_FS_POSIX_ACL
if (def_mount_opts & EXT2_DEFM_ACL)
set_opt(sbi->s_mount_opt, POSIX_ACL);
#endif
if (le16_to_cpu(sbi->s_es->s_errors) == EXT2_ERRORS_PANIC)
set_opt(sbi->s_mount_opt, ERRORS_PANIC);
else if (le16_to_cpu(sbi->s_es->s_errors) == EXT2_ERRORS_CONTINUE)
set_opt(sbi->s_mount_opt, ERRORS_CONT);
else
set_opt(sbi->s_mount_opt, ERRORS_RO);
sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));
sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));
set_opt(sbi->s_mount_opt, RESERVATION);
if (!parse_options((char *) data, sb))
goto failed_mount;
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
((EXT2_SB(sb)->s_mount_opt & EXT2_MOUNT_POSIX_ACL) ?
MS_POSIXACL : 0);
sb->s_iflags |= SB_I_CGROUPWB;
if (le32_to_cpu(es->s_rev_level) == EXT2_GOOD_OLD_REV &&
(EXT2_HAS_COMPAT_FEATURE(sb, ~0U) ||
EXT2_HAS_RO_COMPAT_FEATURE(sb, ~0U) ||
EXT2_HAS_INCOMPAT_FEATURE(sb, ~0U)))
ext2_msg(sb, KERN_WARNING,
"warning: feature flags set on rev 0 fs, "
"running e2fsck is recommended");
/*
* Check feature flags regardless of the revision level, since we
* previously didn't change the revision level when setting the flags,
* so there is a chance incompat flags are set on a rev 0 filesystem.
*/
features = EXT2_HAS_INCOMPAT_FEATURE(sb, ~EXT2_FEATURE_INCOMPAT_SUPP);
if (features) {
ext2_msg(sb, KERN_ERR, "error: couldn't mount because of "
"unsupported optional features (%x)",
le32_to_cpu(features));
goto failed_mount;
}
if (!(sb->s_flags & MS_RDONLY) &&
(features = EXT2_HAS_RO_COMPAT_FEATURE(sb, ~EXT2_FEATURE_RO_COMPAT_SUPP))){
ext2_msg(sb, KERN_ERR, "error: couldn't mount RDWR because of "
"unsupported optional features (%x)",
le32_to_cpu(features));
goto failed_mount;
}
blocksize = BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);
if (sbi->s_mount_opt & EXT2_MOUNT_DAX) {
if (blocksize != PAGE_SIZE) {
ext2_msg(sb, KERN_ERR,
"error: unsupported blocksize for dax");
goto failed_mount;
}
if (!sb->s_bdev->bd_disk->fops->direct_access) {
ext2_msg(sb, KERN_ERR,
"error: device does not support dax");
goto failed_mount;
}
}
/* If the blocksize doesn't match, re-read the thing.. */
if (sb->s_blocksize != blocksize) {
brelse(bh);
if (!sb_set_blocksize(sb, blocksize)) {
ext2_msg(sb, KERN_ERR,
"error: bad blocksize %d", blocksize);
goto failed_sbi;
}
logic_sb_block = (sb_block*BLOCK_SIZE) / blocksize;
offset = (sb_block*BLOCK_SIZE) % blocksize;
bh = sb_bread(sb, logic_sb_block);
if(!bh) {
ext2_msg(sb, KERN_ERR, "error: couldn't read"
"superblock on 2nd try");
goto failed_sbi;
}
es = (struct ext2_super_block *) (((char *)bh->b_data) + offset);
sbi->s_es = es;
if (es->s_magic != cpu_to_le16(EXT2_SUPER_MAGIC)) {
ext2_msg(sb, KERN_ERR, "error: magic mismatch");
goto failed_mount;
}
}
sb->s_maxbytes = ext2_max_size(sb->s_blocksize_bits);
sb->s_max_links = EXT2_LINK_MAX;
if (le32_to_cpu(es->s_rev_level) == EXT2_GOOD_OLD_REV) {
sbi->s_inode_size = EXT2_GOOD_OLD_INODE_SIZE;
sbi->s_first_ino = EXT2_GOOD_OLD_FIRST_INO;
} else {
sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
if ((sbi->s_inode_size < EXT2_GOOD_OLD_INODE_SIZE) ||
!is_power_of_2(sbi->s_inode_size) ||
(sbi->s_inode_size > blocksize)) {
ext2_msg(sb, KERN_ERR,
"error: unsupported inode size: %d",
sbi->s_inode_size);
goto failed_mount;
}
}
sbi->s_frag_size = EXT2_MIN_FRAG_SIZE <<
le32_to_cpu(es->s_log_frag_size);
if (sbi->s_frag_size == 0)
goto cantfind_ext2;
sbi->s_frags_per_block = sb->s_blocksize / sbi->s_frag_size;
sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
sbi->s_frags_per_group = le32_to_cpu(es->s_frags_per_group);
sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
if (EXT2_INODE_SIZE(sb) == 0)
goto cantfind_ext2;
sbi->s_inodes_per_block = sb->s_blocksize / EXT2_INODE_SIZE(sb);
if (sbi->s_inodes_per_block == 0 || sbi->s_inodes_per_group == 0)
goto cantfind_ext2;
sbi->s_itb_per_group = sbi->s_inodes_per_group /
sbi->s_inodes_per_block;
sbi->s_desc_per_block = sb->s_blocksize /
sizeof (struct ext2_group_desc);
sbi->s_sbh = bh;
sbi->s_mount_state = le16_to_cpu(es->s_state);
sbi->s_addr_per_block_bits =
ilog2 (EXT2_ADDR_PER_BLOCK(sb));
sbi->s_desc_per_block_bits =
ilog2 (EXT2_DESC_PER_BLOCK(sb));
if (sb->s_magic != EXT2_SUPER_MAGIC)
goto cantfind_ext2;
if (sb->s_blocksize != bh->b_size) {
if (!silent)
ext2_msg(sb, KERN_ERR, "error: unsupported blocksize");
goto failed_mount;
}
if (sb->s_blocksize != sbi->s_frag_size) {
ext2_msg(sb, KERN_ERR,
"error: fragsize %lu != blocksize %lu"
"(not supported yet)",
sbi->s_frag_size, sb->s_blocksize);
goto failed_mount;
}
if (sbi->s_blocks_per_group > sb->s_blocksize * 8) {
ext2_msg(sb, KERN_ERR,
"error: #blocks per group too big: %lu",
sbi->s_blocks_per_group);
goto failed_mount;
}
if (sbi->s_frags_per_group > sb->s_blocksize * 8) {
ext2_msg(sb, KERN_ERR,
"error: #fragments per group too big: %lu",
sbi->s_frags_per_group);
goto failed_mount;
}
if (sbi->s_inodes_per_group > sb->s_blocksize * 8) {
ext2_msg(sb, KERN_ERR,
"error: #inodes per group too big: %lu",
sbi->s_inodes_per_group);
goto failed_mount;
}
if (EXT2_BLOCKS_PER_GROUP(sb) == 0)
goto cantfind_ext2;
sbi->s_groups_count = ((le32_to_cpu(es->s_blocks_count) -
le32_to_cpu(es->s_first_data_block) - 1)
/ EXT2_BLOCKS_PER_GROUP(sb)) + 1;
db_count = (sbi->s_groups_count + EXT2_DESC_PER_BLOCK(sb) - 1) /
EXT2_DESC_PER_BLOCK(sb);
sbi->s_group_desc = kmalloc (db_count * sizeof (struct buffer_head *), GFP_KERNEL);
if (sbi->s_group_desc == NULL) {
ext2_msg(sb, KERN_ERR, "error: not enough memory");
goto failed_mount;
}
bgl_lock_init(sbi->s_blockgroup_lock);
sbi->s_debts = kcalloc(sbi->s_groups_count, sizeof(*sbi->s_debts), GFP_KERNEL);
if (!sbi->s_debts) {
ext2_msg(sb, KERN_ERR, "error: not enough memory");
goto failed_mount_group_desc;
}
for (i = 0; i < db_count; i++) {
block = descriptor_loc(sb, logic_sb_block, i);
sbi->s_group_desc[i] = sb_bread(sb, block);
if (!sbi->s_group_desc[i]) {
for (j = 0; j < i; j++)
brelse (sbi->s_group_desc[j]);
ext2_msg(sb, KERN_ERR,
"error: unable to read group descriptors");
goto failed_mount_group_desc;
}
}
if (!ext2_check_descriptors (sb)) {
ext2_msg(sb, KERN_ERR, "group descriptors corrupted");
goto failed_mount2;
}
sbi->s_gdb_count = db_count;
get_random_bytes(&sbi->s_next_generation, sizeof(u32));
spin_lock_init(&sbi->s_next_gen_lock);
/* per fileystem reservation list head & lock */
spin_lock_init(&sbi->s_rsv_window_lock);
sbi->s_rsv_window_root = RB_ROOT;
/*
* Add a single, static dummy reservation to the start of the
* reservation window list --- it gives us a placeholder for
* append-at-start-of-list which makes the allocation logic
* _much_ simpler.
*/
sbi->s_rsv_window_head.rsv_start = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
sbi->s_rsv_window_head.rsv_end = EXT2_RESERVE_WINDOW_NOT_ALLOCATED;
sbi->s_rsv_window_head.rsv_alloc_hit = 0;
sbi->s_rsv_window_head.rsv_goal_size = 0;
ext2_rsv_window_add(sb, &sbi->s_rsv_window_head);
err = percpu_counter_init(&sbi->s_freeblocks_counter,
ext2_count_free_blocks(sb), GFP_KERNEL);
if (!err) {
err = percpu_counter_init(&sbi->s_freeinodes_counter,
ext2_count_free_inodes(sb), GFP_KERNEL);
}
if (!err) {
err = percpu_counter_init(&sbi->s_dirs_counter,
ext2_count_dirs(sb), GFP_KERNEL);
}
if (err) {
ext2_msg(sb, KERN_ERR, "error: insufficient memory");
goto failed_mount3;
}
/*
* set up enough so that it can read an inode
*/
sb->s_op = &ext2_sops;
sb->s_export_op = &ext2_export_ops;
sb->s_xattr = ext2_xattr_handlers;
#ifdef CONFIG_QUOTA
sb->dq_op = &dquot_operations;
sb->s_qcop = &dquot_quotactl_ops;
sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP;
#endif
root = ext2_iget(sb, EXT2_ROOT_INO);
if (IS_ERR(root)) {
ret = PTR_ERR(root);
goto failed_mount3;
}
if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
iput(root);
ext2_msg(sb, KERN_ERR, "error: corrupt root inode, run e2fsck");
goto failed_mount3;
}
sb->s_root = d_make_root(root);
if (!sb->s_root) {
ext2_msg(sb, KERN_ERR, "error: get root inode failed");
ret = -ENOMEM;
goto failed_mount3;
}
if (EXT2_HAS_COMPAT_FEATURE(sb, EXT3_FEATURE_COMPAT_HAS_JOURNAL))
ext2_msg(sb, KERN_WARNING,
"warning: mounting ext3 filesystem as ext2");
if (ext2_setup_super (sb, es, sb->s_flags & MS_RDONLY))
sb->s_flags |= MS_RDONLY;
ext2_write_super(sb);
return 0;
cantfind_ext2:
if (!silent)
ext2_msg(sb, KERN_ERR,
"error: can't find an ext2 filesystem on dev %s.",
sb->s_id);
goto failed_mount;
failed_mount3:
percpu_counter_destroy(&sbi->s_freeblocks_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
failed_mount2:
for (i = 0; i < db_count; i++)
brelse(sbi->s_group_desc[i]);
failed_mount_group_desc:
kfree(sbi->s_group_desc);
kfree(sbi->s_debts);
failed_mount:
brelse(bh);
failed_sbi:
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
failed:
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[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: ext2_xattr_put_super(struct super_block *sb)
{
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[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: ext2_xattr_set(struct inode *inode, int name_index, const char *name,
const void *value, size_t value_len, int flags)
{
struct super_block *sb = inode->i_sb;
struct buffer_head *bh = NULL;
struct ext2_xattr_header *header = NULL;
struct ext2_xattr_entry *here, *last;
size_t name_len, free, min_offs = sb->s_blocksize;
int not_found = 1, error;
char *end;
/*
* header -- Points either into bh, or to a temporarily
* allocated buffer.
* here -- The named entry found, or the place for inserting, within
* the block pointed to by header.
* last -- Points right after the last named entry within the block
* pointed to by header.
* min_offs -- The offset of the first value (values are aligned
* towards the end of the block).
* end -- Points right after the block pointed to by header.
*/
ea_idebug(inode, "name=%d.%s, value=%p, value_len=%ld",
name_index, name, value, (long)value_len);
if (value == NULL)
value_len = 0;
if (name == NULL)
return -EINVAL;
name_len = strlen(name);
if (name_len > 255 || value_len > sb->s_blocksize)
return -ERANGE;
down_write(&EXT2_I(inode)->xattr_sem);
if (EXT2_I(inode)->i_file_acl) {
/* The inode already has an extended attribute block. */
bh = sb_bread(sb, EXT2_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)),
le32_to_cpu(HDR(bh)->h_refcount));
header = HDR(bh);
end = bh->b_data + bh->b_size;
if (header->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) ||
header->h_blocks != cpu_to_le32(1)) {
bad_block: ext2_error(sb, "ext2_xattr_set",
"inode %ld: bad block %d", inode->i_ino,
EXT2_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
/* Find the named attribute. */
here = FIRST_ENTRY(bh);
while (!IS_LAST_ENTRY(here)) {
struct ext2_xattr_entry *next = EXT2_XATTR_NEXT(here);
if ((char *)next >= end)
goto bad_block;
if (!here->e_value_block && here->e_value_size) {
size_t offs = le16_to_cpu(here->e_value_offs);
if (offs < min_offs)
min_offs = offs;
}
not_found = name_index - here->e_name_index;
if (!not_found)
not_found = name_len - here->e_name_len;
if (!not_found)
not_found = memcmp(name, here->e_name,name_len);
if (not_found <= 0)
break;
here = next;
}
last = here;
/* We still need to compute min_offs and last. */
while (!IS_LAST_ENTRY(last)) {
struct ext2_xattr_entry *next = EXT2_XATTR_NEXT(last);
if ((char *)next >= end)
goto bad_block;
if (!last->e_value_block && last->e_value_size) {
size_t offs = le16_to_cpu(last->e_value_offs);
if (offs < min_offs)
min_offs = offs;
}
last = next;
}
/* Check whether we have enough space left. */
free = min_offs - ((char*)last - (char*)header) - sizeof(__u32);
} else {
/* We will use a new extended attribute block. */
free = sb->s_blocksize -
sizeof(struct ext2_xattr_header) - sizeof(__u32);
here = last = NULL; /* avoid gcc uninitialized warning. */
}
if (not_found) {
/* Request to remove a nonexistent attribute? */
error = -ENODATA;
if (flags & XATTR_REPLACE)
goto cleanup;
error = 0;
if (value == NULL)
goto cleanup;
} else {
/* Request to create an existing attribute? */
error = -EEXIST;
if (flags & XATTR_CREATE)
goto cleanup;
if (!here->e_value_block && here->e_value_size) {
size_t size = le32_to_cpu(here->e_value_size);
if (le16_to_cpu(here->e_value_offs) + size >
sb->s_blocksize || size > sb->s_blocksize)
goto bad_block;
free += EXT2_XATTR_SIZE(size);
}
free += EXT2_XATTR_LEN(name_len);
}
error = -ENOSPC;
if (free < EXT2_XATTR_LEN(name_len) + EXT2_XATTR_SIZE(value_len))
goto cleanup;
/* Here we know that we can set the new attribute. */
if (header) {
struct mb_cache_entry *ce;
/* assert(header == HDR(bh)); */
ce = mb_cache_entry_get(ext2_xattr_cache, bh->b_bdev,
bh->b_blocknr);
lock_buffer(bh);
if (header->h_refcount == cpu_to_le32(1)) {
ea_bdebug(bh, "modifying in-place");
if (ce)
mb_cache_entry_free(ce);
/* keep the buffer locked while modifying it. */
} else {
int offset;
if (ce)
mb_cache_entry_release(ce);
unlock_buffer(bh);
ea_bdebug(bh, "cloning");
header = kmalloc(bh->b_size, GFP_KERNEL);
error = -ENOMEM;
if (header == NULL)
goto cleanup;
memcpy(header, HDR(bh), bh->b_size);
header->h_refcount = cpu_to_le32(1);
offset = (char *)here - bh->b_data;
here = ENTRY((char *)header + offset);
offset = (char *)last - bh->b_data;
last = ENTRY((char *)header + offset);
}
} else {
/* Allocate a buffer where we construct the new block. */
header = kzalloc(sb->s_blocksize, GFP_KERNEL);
error = -ENOMEM;
if (header == NULL)
goto cleanup;
end = (char *)header + sb->s_blocksize;
header->h_magic = cpu_to_le32(EXT2_XATTR_MAGIC);
header->h_blocks = header->h_refcount = cpu_to_le32(1);
last = here = ENTRY(header+1);
}
/* Iff we are modifying the block in-place, bh is locked here. */
if (not_found) {
/* Insert the new name. */
size_t size = EXT2_XATTR_LEN(name_len);
size_t rest = (char *)last - (char *)here;
memmove((char *)here + size, here, rest);
memset(here, 0, size);
here->e_name_index = name_index;
here->e_name_len = name_len;
memcpy(here->e_name, name, name_len);
} else {
if (!here->e_value_block && here->e_value_size) {
char *first_val = (char *)header + min_offs;
size_t offs = le16_to_cpu(here->e_value_offs);
char *val = (char *)header + offs;
size_t size = EXT2_XATTR_SIZE(
le32_to_cpu(here->e_value_size));
if (size == EXT2_XATTR_SIZE(value_len)) {
/* The old and the new value have the same
size. Just replace. */
here->e_value_size = cpu_to_le32(value_len);
memset(val + size - EXT2_XATTR_PAD, 0,
EXT2_XATTR_PAD); /* Clear pad bytes. */
memcpy(val, value, value_len);
goto skip_replace;
}
/* Remove the old value. */
memmove(first_val + size, first_val, val - first_val);
memset(first_val, 0, size);
here->e_value_offs = 0;
min_offs += size;
/* Adjust all value offsets. */
last = ENTRY(header+1);
while (!IS_LAST_ENTRY(last)) {
size_t o = le16_to_cpu(last->e_value_offs);
if (!last->e_value_block && o < offs)
last->e_value_offs =
cpu_to_le16(o + size);
last = EXT2_XATTR_NEXT(last);
}
}
if (value == NULL) {
/* Remove the old name. */
size_t size = EXT2_XATTR_LEN(name_len);
last = ENTRY((char *)last - size);
memmove(here, (char*)here + size,
(char*)last - (char*)here);
memset(last, 0, size);
}
}
if (value != NULL) {
/* Insert the new value. */
here->e_value_size = cpu_to_le32(value_len);
if (value_len) {
size_t size = EXT2_XATTR_SIZE(value_len);
char *val = (char *)header + min_offs - size;
here->e_value_offs =
cpu_to_le16((char *)val - (char *)header);
memset(val + size - EXT2_XATTR_PAD, 0,
EXT2_XATTR_PAD); /* Clear the pad bytes. */
memcpy(val, value, value_len);
}
}
skip_replace:
if (IS_LAST_ENTRY(ENTRY(header+1))) {
/* This block is now empty. */
if (bh && header == HDR(bh))
unlock_buffer(bh); /* we were modifying in-place. */
error = ext2_xattr_set2(inode, bh, NULL);
} else {
ext2_xattr_rehash(header, here);
if (bh && header == HDR(bh))
unlock_buffer(bh); /* we were modifying in-place. */
error = ext2_xattr_set2(inode, bh, header);
}
cleanup:
brelse(bh);
if (!(bh && header == HDR(bh)))
kfree(header);
up_write(&EXT2_I(inode)->xattr_sem);
return error;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[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: ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb_cache_entry_find_first(ext2_xattr_cache, inode->i_sb->s_bdev,
hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_cache_find",
"inode %ld: block %ld read error",
inode->i_ino, (unsigned long) ce->e_block);
} else {
lock_buffer(bh);
if (le32_to_cpu(HDR(bh)->h_refcount) >
EXT2_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %ld refcount %d>%d",
(unsigned long) ce->e_block,
le32_to_cpu(HDR(bh)->h_refcount),
EXT2_XATTR_REFCOUNT_MAX);
} else if (!ext2_xattr_cmp(header, HDR(bh))) {
ea_bdebug(bh, "b_count=%d",
atomic_read(&(bh->b_count)));
mb_cache_entry_release(ce);
return bh;
}
unlock_buffer(bh);
brelse(bh);
}
ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[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: exit_ext2_xattr(void)
{
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[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: ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh,
struct ext2_xattr_header *header)
{
struct super_block *sb = inode->i_sb;
struct buffer_head *new_bh = NULL;
int error;
if (header) {
new_bh = ext2_xattr_cache_find(inode, header);
if (new_bh) {
/* We found an identical block in the cache. */
if (new_bh == old_bh) {
ea_bdebug(new_bh, "keeping this block");
} else {
/* The old block is released after updating
the inode. */
ea_bdebug(new_bh, "reusing block");
error = dquot_alloc_block(inode, 1);
if (error) {
unlock_buffer(new_bh);
goto cleanup;
}
le32_add_cpu(&HDR(new_bh)->h_refcount, 1);
ea_bdebug(new_bh, "refcount now=%d",
le32_to_cpu(HDR(new_bh)->h_refcount));
}
unlock_buffer(new_bh);
} else if (old_bh && header == HDR(old_bh)) {
/* Keep this block. No need to lock the block as we
don't need to change the reference count. */
new_bh = old_bh;
get_bh(new_bh);
ext2_xattr_cache_insert(new_bh);
} else {
/* We need to allocate a new block */
ext2_fsblk_t goal = ext2_group_first_block_no(sb,
EXT2_I(inode)->i_block_group);
int block = ext2_new_block(inode, goal, &error);
if (error)
goto cleanup;
ea_idebug(inode, "creating block %d", block);
new_bh = sb_getblk(sb, block);
if (unlikely(!new_bh)) {
ext2_free_blocks(inode, block, 1);
mark_inode_dirty(inode);
error = -ENOMEM;
goto cleanup;
}
lock_buffer(new_bh);
memcpy(new_bh->b_data, header, new_bh->b_size);
set_buffer_uptodate(new_bh);
unlock_buffer(new_bh);
ext2_xattr_cache_insert(new_bh);
ext2_xattr_update_super_block(sb);
}
mark_buffer_dirty(new_bh);
if (IS_SYNC(inode)) {
sync_dirty_buffer(new_bh);
error = -EIO;
if (buffer_req(new_bh) && !buffer_uptodate(new_bh))
goto cleanup;
}
}
/* Update the inode. */
EXT2_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
inode->i_ctime = CURRENT_TIME_SEC;
if (IS_SYNC(inode)) {
error = sync_inode_metadata(inode, 1);
/* In case sync failed due to ENOSPC the inode was actually
* written (only some dirty data were not) so we just proceed
* as if nothing happened and cleanup the unused block */
if (error && error != -ENOSPC) {
if (new_bh && new_bh != old_bh) {
dquot_free_block_nodirty(inode, 1);
mark_inode_dirty(inode);
}
goto cleanup;
}
} else
mark_inode_dirty(inode);
error = 0;
if (old_bh && old_bh != new_bh) {
struct mb_cache_entry *ce;
/*
* If there was an old block and we are no longer using it,
* release the old block.
*/
ce = mb_cache_entry_get(ext2_xattr_cache, old_bh->b_bdev,
old_bh->b_blocknr);
lock_buffer(old_bh);
if (HDR(old_bh)->h_refcount == cpu_to_le32(1)) {
/* Free the old block. */
if (ce)
mb_cache_entry_free(ce);
ea_bdebug(old_bh, "freeing");
ext2_free_blocks(inode, old_bh->b_blocknr, 1);
mark_inode_dirty(inode);
/* We let our caller release old_bh, so we
* need to duplicate the buffer before. */
get_bh(old_bh);
bforget(old_bh);
} else {
/* Decrement the refcount only. */
le32_add_cpu(&HDR(old_bh)->h_refcount, -1);
if (ce)
mb_cache_entry_release(ce);
dquot_free_block_nodirty(inode, 1);
mark_inode_dirty(inode);
mark_buffer_dirty(old_bh);
ea_bdebug(old_bh, "refcount now=%d",
le32_to_cpu(HDR(old_bh)->h_refcount));
}
unlock_buffer(old_bh);
}
cleanup:
brelse(new_bh);
return error;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[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: ext2_xattr_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = d_inode(dentry);
struct buffer_head *bh = NULL;
struct ext2_xattr_entry *entry;
char *end;
size_t rest = buffer_size;
int error;
ea_idebug(inode, "buffer=%p, buffer_size=%ld",
buffer, (long)buffer_size);
down_read(&EXT2_I(inode)->xattr_sem);
error = 0;
if (!EXT2_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %d", EXT2_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(HDR(bh)->h_refcount));
end = bh->b_data + bh->b_size;
if (HDR(bh)->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) ||
HDR(bh)->h_blocks != cpu_to_le32(1)) {
bad_block: ext2_error(inode->i_sb, "ext2_xattr_list",
"inode %ld: bad block %d", inode->i_ino,
EXT2_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
/* check the on-disk data structure */
entry = FIRST_ENTRY(bh);
while (!IS_LAST_ENTRY(entry)) {
struct ext2_xattr_entry *next = EXT2_XATTR_NEXT(entry);
if ((char *)next >= end)
goto bad_block;
entry = next;
}
if (ext2_xattr_cache_insert(bh))
ea_idebug(inode, "cache insert failed");
/* list the attribute names */
for (entry = FIRST_ENTRY(bh); !IS_LAST_ENTRY(entry);
entry = EXT2_XATTR_NEXT(entry)) {
const struct xattr_handler *handler =
ext2_xattr_handler(entry->e_name_index);
if (handler && (!handler->list || handler->list(dentry))) {
const char *prefix = handler->prefix ?: handler->name;
size_t prefix_len = strlen(prefix);
size_t size = prefix_len + entry->e_name_len + 1;
if (buffer) {
if (size > rest) {
error = -ERANGE;
goto cleanup;
}
memcpy(buffer, prefix, prefix_len);
buffer += prefix_len;
memcpy(buffer, entry->e_name, entry->e_name_len);
buffer += entry->e_name_len;
*buffer++ = 0;
}
rest -= size;
}
}
error = buffer_size - rest; /* total size */
cleanup:
brelse(bh);
up_read(&EXT2_I(inode)->xattr_sem);
return error;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[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: init_ext2_xattr(void)
{
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[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: ext2_xattr_put_super(struct super_block *sb)
{
mb_cache_shrink(sb->s_bdev);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[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 dbd_db_login(SV* dbh, imp_dbh_t* imp_dbh, char* dbname, char* user,
char* password) {
#ifdef dTHR
dTHR;
#endif
dTHX;
D_imp_xxh(dbh);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->connect: dsn = %s, uid = %s, pwd = %s\n",
dbname ? dbname : "NULL",
user ? user : "NULL",
password ? password : "NULL");
imp_dbh->stats.auto_reconnects_ok= 0;
imp_dbh->stats.auto_reconnects_failed= 0;
imp_dbh->bind_type_guessing= FALSE;
imp_dbh->bind_comment_placeholders= FALSE;
imp_dbh->has_transactions= TRUE;
/* Safer we flip this to TRUE perl side if we detect a mod_perl env. */
imp_dbh->auto_reconnect = FALSE;
/* HELMUT */
#if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
imp_dbh->enable_utf8 = FALSE; /* initialize mysql_enable_utf8 */
#endif
if (!my_login(aTHX_ dbh, imp_dbh))
{
do_error(dbh, mysql_errno(imp_dbh->pmysql),
mysql_error(imp_dbh->pmysql) ,mysql_sqlstate(imp_dbh->pmysql));
return FALSE;
}
/*
* Tell DBI, that dbh->disconnect should be called for this handle
*/
DBIc_ACTIVE_on(imp_dbh);
/* Tell DBI, that dbh->destroy should be called for this handle */
DBIc_on(imp_dbh, DBIcf_IMPSET);
return TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'fix use-after-free crash in RT #97625'</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 Get8BIMProperty(const Image *image,const char *key,
ExceptionInfo *exception)
{
char
*attribute,
format[MagickPathExtent],
name[MagickPathExtent],
*resource;
const StringInfo
*profile;
const unsigned char
*info;
long
start,
stop;
MagickBooleanType
status;
register ssize_t
i;
size_t
length;
ssize_t
count,
id,
sub_number;
/*
There are no newlines in path names, so it's safe as terminator.
*/
profile=GetImageProfile(image,"8bim");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop,
name,format);
if ((count != 2) && (count != 3) && (count != 4))
return(MagickFalse);
if (count < 4)
(void) CopyMagickString(format,"SVG",MagickPathExtent);
if (count < 3)
*name='\0';
sub_number=1;
if (*name == '#')
sub_number=(ssize_t) StringToLong(&name[1]);
sub_number=MagickMax(sub_number,1L);
resource=(char *) NULL;
status=MagickFalse;
length=GetStringInfoLength(profile);
info=GetStringInfoDatum(profile);
while ((length > 0) && (status == MagickFalse))
{
if (ReadPropertyByte(&info,&length) != (unsigned char) '8')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'B')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'I')
continue;
if (ReadPropertyByte(&info,&length) != (unsigned char) 'M')
continue;
id=(ssize_t) ReadPropertyMSBShort(&info,&length);
if (id < (ssize_t) start)
continue;
if (id > (ssize_t) stop)
continue;
if (resource != (char *) NULL)
resource=DestroyString(resource);
count=(ssize_t) ReadPropertyByte(&info,&length);
if ((count != 0) && ((size_t) count <= length))
{
resource=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
resource=(char *) AcquireQuantumMemory((size_t) count+
MagickPathExtent,sizeof(*resource));
if (resource != (char *) NULL)
{
for (i=0; i < (ssize_t) count; i++)
resource[i]=(char) ReadPropertyByte(&info,&length);
resource[count]='\0';
}
}
if ((count & 0x01) == 0)
(void) ReadPropertyByte(&info,&length);
count=(ssize_t) ReadPropertyMSBLong(&info,&length);
if ((*name != '\0') && (*name != '#'))
if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0))
{
/*
No name match, scroll forward and try next.
*/
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
if ((*name == '#') && (sub_number != 1))
{
/*
No numbered match, scroll forward and try next.
*/
sub_number--;
info+=count;
length-=MagickMin(count,(ssize_t) length);
continue;
}
/*
We have the resource of interest.
*/
attribute=(char *) NULL;
if (~((size_t) count) >= (MagickPathExtent-1))
attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent,
sizeof(*attribute));
if (attribute != (char *) NULL)
{
(void) CopyMagickMemory(attribute,(char *) info,(size_t) count);
attribute[count]='\0';
info+=count;
length-=MagickMin(count,(ssize_t) length);
if ((id <= 1999) || (id >= 2999))
(void) SetImageProperty((Image *) image,key,(const char *)
attribute,exception);
else
{
char
*path;
if (LocaleCompare(format,"svg") == 0)
path=TraceSVGClippath((unsigned char *) attribute,(size_t) count,
image->columns,image->rows);
else
path=TracePSClippath((unsigned char *) attribute,(size_t) count);
(void) SetImageProperty((Image *) image,key,(const char *) path,
exception);
path=DestroyString(path);
}
attribute=DestroyString(attribute);
status=MagickTrue;
}
}
if (resource != (char *) NULL)
resource=DestroyString(resource);
return(status);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Prevent buffer overflow (bug report from Ibrahim el-sayed)'</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: _rsa_blind (const struct rsa_public_key *pub,
void *random_ctx, nettle_random_func *random,
mpz_t c, mpz_t ri)
{
mpz_t r;
mpz_init(r);
/* c = c*(r^e)
* ri = r^(-1)
*/
do
{
nettle_mpz_random(r, random_ctx, random, pub->n);
/* invert r */
}
while (!mpz_invert (ri, r, pub->n));
/* c = c*(r^e) mod n */
mpz_powm(r, r, pub->e, pub->n);
mpz_mul(c, c, r);
mpz_fdiv_r(c, c, pub->n);
mpz_clear(r);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-203'], 'message': 'Use mpz_powm_sec.'</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: rsa_compute_root_tr(const struct rsa_public_key *pub,
const struct rsa_private_key *key,
void *random_ctx, nettle_random_func *random,
mpz_t x, const mpz_t m)
{
int res;
mpz_t t, mb, xb, ri;
mpz_init (mb);
mpz_init (xb);
mpz_init (ri);
mpz_init (t);
rsa_blind (pub, random_ctx, random, mb, ri, m);
rsa_compute_root (key, xb, mb);
mpz_powm(t, xb, pub->e, pub->n);
res = (mpz_cmp(mb, t) == 0);
if (res)
rsa_unblind (pub, x, ri, xb);
mpz_clear (mb);
mpz_clear (xb);
mpz_clear (ri);
mpz_clear (t);
return res;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-203'], 'message': 'Use mpz_powm_sec.'</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: rsa_compute_root_tr(const struct rsa_public_key *pub,
const struct rsa_private_key *key,
void *random_ctx, nettle_random_func *random,
mpz_t x, const mpz_t m)
{
int res;
mpz_t t, mb, xb, ri;
mpz_init (mb);
mpz_init (xb);
mpz_init (ri);
mpz_init (t);
rsa_blind (pub, random_ctx, random, mb, ri, m);
rsa_compute_root (key, xb, mb);
mpz_powm_sec(t, xb, pub->e, pub->n);
res = (mpz_cmp(mb, t) == 0);
if (res)
rsa_unblind (pub, x, ri, xb);
mpz_clear (mb);
mpz_clear (xb);
mpz_clear (ri);
mpz_clear (t);
return res;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-203'], 'message': 'Reject invalid keys, with even moduli, in rsa_compute_root_tr.'</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 long ioctl_file_dedupe_range(struct file *file, void __user *arg)
{
struct file_dedupe_range __user *argp = arg;
struct file_dedupe_range *same = NULL;
int ret;
unsigned long size;
u16 count;
if (get_user(count, &argp->dest_count)) {
ret = -EFAULT;
goto out;
}
size = offsetof(struct file_dedupe_range __user, info[count]);
same = memdup_user(argp, size);
if (IS_ERR(same)) {
ret = PTR_ERR(same);
same = NULL;
goto out;
}
ret = vfs_dedupe_file_range(file, same);
if (ret)
goto out;
ret = copy_to_user(argp, same, size);
if (ret)
ret = -EFAULT;
out:
kfree(same);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362', 'CWE-119', 'CWE-787'], 'message': 'vfs: ioctl: prevent double-fetch in dedupe ioctl
This prevents a double-fetch from user space that can lead to to an
undersized allocation and heap overflow.
Fixes: 54dbc1517237 ("vfs: hoist the btrfs deduplication ioctl to the vfs")
Signed-off-by: Scott Bauer <[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: recv_and_process_client_pkt(void /*int fd*/)
{
ssize_t size;
//uint8_t version;
len_and_sockaddr *to;
struct sockaddr *from;
msg_t msg;
uint8_t query_status;
l_fixedpt_t query_xmttime;
to = get_sock_lsa(G_listen_fd);
from = xzalloc(to->len);
size = recv_from_to(G_listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
char *addr;
if (size < 0) {
if (errno == EAGAIN)
goto bail;
bb_perror_msg_and_die("recv");
}
addr = xmalloc_sockaddr2dotted_noport(from);
bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
free(addr);
goto bail;
}
query_status = msg.m_status;
query_xmttime = msg.m_xmttime;
/* Build a reply packet */
memset(&msg, 0, sizeof(msg));
msg.m_status = G.stratum < MAXSTRAT ? (G.ntp_status & LI_MASK) : LI_ALARM;
msg.m_status |= (query_status & VERSION_MASK);
msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
MODE_SERVER : MODE_SYM_PAS;
msg.m_stratum = G.stratum;
msg.m_ppoll = G.poll_exp;
msg.m_precision_exp = G_precision_exp;
/* this time was obtained between poll() and recv() */
msg.m_rectime = d_to_lfp(G.cur_time);
msg.m_xmttime = d_to_lfp(gettime1900d()); /* this instant */
if (G.peer_cnt == 0) {
/* we have no peers: "stratum 1 server" mode. reftime = our own time */
G.reftime = G.cur_time;
}
msg.m_reftime = d_to_lfp(G.reftime);
msg.m_orgtime = query_xmttime;
msg.m_rootdelay = d_to_sfp(G.rootdelay);
//simple code does not do this, fix simple code!
msg.m_rootdisp = d_to_sfp(G.rootdisp);
//version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3;
/* We reply from the local address packet was sent to,
* this makes to/from look swapped here: */
do_sendto(G_listen_fd,
/*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
&msg, size);
bail:
free(to);
free(from);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'ntpd: respond only to client and symmetric active packets
The busybox NTP implementation doesn't check the NTP mode of packets
received on the server port and responds to any packet with the right
size. This includes responses from another NTP server. An attacker can
send a packet with a spoofed source address in order to create an
infinite loop of responses between two busybox NTP servers. Adding
more packets to the loop increases the traffic between the servers
until one of them has a fully loaded CPU and/or network.
Signed-off-by: Miroslav Lichvar <[email protected]>
Signed-off-by: Denys Vlasenko <[email protected]>'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: MagickExport MagickBooleanType EqualizeImage(Image *image,
ExceptionInfo *exception)
{
#define EqualizeImageTag "Equalize/Image"
CacheView
*image_view;
double
black[CompositePixelChannel+1],
*equalize_map,
*histogram,
*map,
white[CompositePixelChannel+1];
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
/*
Allocate and initialize histogram arrays.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (AccelerateEqualizeImage(image,exception) != MagickFalse)
return(MagickTrue);
#endif
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL,
GetPixelChannels(image)*sizeof(*equalize_map));
histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)*
sizeof(*histogram));
map=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)*
sizeof(*map));
if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) ||
(map == (double *) NULL))
{
if (map != (double *) NULL)
map=(double *) RelinquishMagickMemory(map);
if (histogram != (double *) NULL)
histogram=(double *) RelinquishMagickMemory(histogram);
if (equalize_map != (double *) NULL)
equalize_map=(double *) RelinquishMagickMemory(equalize_map);
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++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
intensity=p[i];
if ((image->channel_mask & SyncChannels) != 0)
intensity=GetPixelIntensity(image,p);
histogram[GetPixelChannels(image)*ScaleQuantumToMap(intensity)+i]++;
}
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Integrate the histogram to get the equalization map.
*/
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
intensity;
register ssize_t
j;
intensity=0.0;
for (j=0; j <= (ssize_t) MaxMap; j++)
{
intensity+=histogram[GetPixelChannels(image)*j+i];
map[GetPixelChannels(image)*j+i]=intensity;
}
}
(void) ResetMagickMemory(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)*
sizeof(*equalize_map));
(void) ResetMagickMemory(black,0,sizeof(*black));
(void) ResetMagickMemory(white,0,sizeof(*white));
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
register ssize_t
j;
black[i]=map[i];
white[i]=map[GetPixelChannels(image)*MaxMap+i];
if (black[i] != white[i])
for (j=0; j <= (ssize_t) MaxMap; j++)
equalize_map[GetPixelChannels(image)*j+i]=(double)
ScaleMapToQuantum((double) ((MaxMap*(map[
GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i])));
}
histogram=(double *) RelinquishMagickMemory(histogram);
map=(double *) RelinquishMagickMemory(map);
if (image->storage_class == PseudoClass)
{
register ssize_t
j;
/*
Equalize colormap.
*/
for (j=0; j < (ssize_t) image->colors; j++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel=GetPixelChannelChannel(image,RedPixelChannel);
if (black[channel] != white[channel])
image->colormap[j].red=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+
channel];
}
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel=GetPixelChannelChannel(image,
GreenPixelChannel);
if (black[channel] != white[channel])
image->colormap[j].green=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+
channel];
}
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel=GetPixelChannelChannel(image,BluePixelChannel);
if (black[channel] != white[channel])
image->colormap[j].blue=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+
channel];
}
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
{
PixelChannel channel=GetPixelChannelChannel(image,
AlphaPixelChannel);
if (black[channel] != white[channel])
image->colormap[j].alpha=equalize_map[GetPixelChannels(image)*
ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+
channel];
}
}
}
/*
Equalize image.
*/
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 (GetPixelReadMask(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) || (black[j] == white[j]))
continue;
q[j]=ClampToQuantum(equalize_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_EqualizeImage)
#endif
proceed=SetImageProgress(image,EqualizeImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
equalize_map=(double *) RelinquishMagickMemory(equalize_map);
return(status);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Evaluate lazy pixel cache morphology to prevent buffer overflow (bug report from Ibrahim M. El-Sayed)'</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: ipv6_renew_options(struct sock *sk, struct ipv6_txoptions *opt,
int newtype,
struct ipv6_opt_hdr __user *newopt, int newoptlen)
{
int tot_len = 0;
char *p;
struct ipv6_txoptions *opt2;
int err;
if (opt) {
if (newtype != IPV6_HOPOPTS && opt->hopopt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->hopopt));
if (newtype != IPV6_RTHDRDSTOPTS && opt->dst0opt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst0opt));
if (newtype != IPV6_RTHDR && opt->srcrt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->srcrt));
if (newtype != IPV6_DSTOPTS && opt->dst1opt)
tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst1opt));
}
if (newopt && newoptlen)
tot_len += CMSG_ALIGN(newoptlen);
if (!tot_len)
return NULL;
tot_len += sizeof(*opt2);
opt2 = sock_kmalloc(sk, tot_len, GFP_ATOMIC);
if (!opt2)
return ERR_PTR(-ENOBUFS);
memset(opt2, 0, tot_len);
opt2->tot_len = tot_len;
p = (char *)(opt2 + 1);
err = ipv6_renew_option(opt ? opt->hopopt : NULL, newopt, newoptlen,
newtype != IPV6_HOPOPTS,
&opt2->hopopt, &p);
if (err)
goto out;
err = ipv6_renew_option(opt ? opt->dst0opt : NULL, newopt, newoptlen,
newtype != IPV6_RTHDRDSTOPTS,
&opt2->dst0opt, &p);
if (err)
goto out;
err = ipv6_renew_option(opt ? opt->srcrt : NULL, newopt, newoptlen,
newtype != IPV6_RTHDR,
(struct ipv6_opt_hdr **)&opt2->srcrt, &p);
if (err)
goto out;
err = ipv6_renew_option(opt ? opt->dst1opt : NULL, newopt, newoptlen,
newtype != IPV6_DSTOPTS,
&opt2->dst1opt, &p);
if (err)
goto out;
opt2->opt_nflen = (opt2->hopopt ? ipv6_optlen(opt2->hopopt) : 0) +
(opt2->dst0opt ? ipv6_optlen(opt2->dst0opt) : 0) +
(opt2->srcrt ? ipv6_optlen(opt2->srcrt) : 0);
opt2->opt_flen = (opt2->dst1opt ? ipv6_optlen(opt2->dst1opt) : 0);
return opt2;
out:
sock_kfree_s(sk, opt2, opt2->tot_len);
return ERR_PTR(err);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[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 tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst,
struct flowi *fl,
struct request_sock *req,
struct tcp_fastopen_cookie *foc,
bool attach_req)
{
struct inet_request_sock *ireq = inet_rsk(req);
struct ipv6_pinfo *np = inet6_sk(sk);
struct flowi6 *fl6 = &fl->u.ip6;
struct sk_buff *skb;
int err = -ENOMEM;
/* First, grab a route. */
if (!dst && (dst = inet6_csk_route_req(sk, fl6, req,
IPPROTO_TCP)) == NULL)
goto done;
skb = tcp_make_synack(sk, dst, req, foc, attach_req);
if (skb) {
__tcp_v6_send_check(skb, &ireq->ir_v6_loc_addr,
&ireq->ir_v6_rmt_addr);
fl6->daddr = ireq->ir_v6_rmt_addr;
if (np->repflow && ireq->pktopts)
fl6->flowlabel = ip6_flowlabel(ipv6_hdr(ireq->pktopts));
err = ip6_xmit(sk, skb, fl6, np->opt, np->tclass);
err = net_xmit_eval(err);
}
done:
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[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 do_ipv6_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct net *net = sock_net(sk);
int val, valbool;
int retv = -ENOPROTOOPT;
bool needs_rtnl = setsockopt_needs_rtnl(optname);
if (!optval)
val = 0;
else {
if (optlen >= sizeof(int)) {
if (get_user(val, (int __user *) optval))
return -EFAULT;
} else
val = 0;
}
valbool = (val != 0);
if (ip6_mroute_opt(optname))
return ip6_mroute_setsockopt(sk, optname, optval, optlen);
if (needs_rtnl)
rtnl_lock();
lock_sock(sk);
switch (optname) {
case IPV6_ADDRFORM:
if (optlen < sizeof(int))
goto e_inval;
if (val == PF_INET) {
struct ipv6_txoptions *opt;
struct sk_buff *pktopt;
if (sk->sk_type == SOCK_RAW)
break;
if (sk->sk_protocol == IPPROTO_UDP ||
sk->sk_protocol == IPPROTO_UDPLITE) {
struct udp_sock *up = udp_sk(sk);
if (up->pending == AF_INET6) {
retv = -EBUSY;
break;
}
} else if (sk->sk_protocol != IPPROTO_TCP)
break;
if (sk->sk_state != TCP_ESTABLISHED) {
retv = -ENOTCONN;
break;
}
if (ipv6_only_sock(sk) ||
!ipv6_addr_v4mapped(&sk->sk_v6_daddr)) {
retv = -EADDRNOTAVAIL;
break;
}
fl6_free_socklist(sk);
ipv6_sock_mc_close(sk);
/*
* Sock is moving from IPv6 to IPv4 (sk_prot), so
* remove it from the refcnt debug socks count in the
* original family...
*/
sk_refcnt_debug_dec(sk);
if (sk->sk_protocol == IPPROTO_TCP) {
struct inet_connection_sock *icsk = inet_csk(sk);
local_bh_disable();
sock_prot_inuse_add(net, sk->sk_prot, -1);
sock_prot_inuse_add(net, &tcp_prot, 1);
local_bh_enable();
sk->sk_prot = &tcp_prot;
icsk->icsk_af_ops = &ipv4_specific;
sk->sk_socket->ops = &inet_stream_ops;
sk->sk_family = PF_INET;
tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
} else {
struct proto *prot = &udp_prot;
if (sk->sk_protocol == IPPROTO_UDPLITE)
prot = &udplite_prot;
local_bh_disable();
sock_prot_inuse_add(net, sk->sk_prot, -1);
sock_prot_inuse_add(net, prot, 1);
local_bh_enable();
sk->sk_prot = prot;
sk->sk_socket->ops = &inet_dgram_ops;
sk->sk_family = PF_INET;
}
opt = xchg(&np->opt, NULL);
if (opt)
sock_kfree_s(sk, opt, opt->tot_len);
pktopt = xchg(&np->pktoptions, NULL);
kfree_skb(pktopt);
sk->sk_destruct = inet_sock_destruct;
/*
* ... and add it to the refcnt debug socks count
* in the new family. -acme
*/
sk_refcnt_debug_inc(sk);
module_put(THIS_MODULE);
retv = 0;
break;
}
goto e_inval;
case IPV6_V6ONLY:
if (optlen < sizeof(int) ||
inet_sk(sk)->inet_num)
goto e_inval;
sk->sk_ipv6only = valbool;
retv = 0;
break;
case IPV6_RECVPKTINFO:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.rxinfo = valbool;
retv = 0;
break;
case IPV6_2292PKTINFO:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.rxoinfo = valbool;
retv = 0;
break;
case IPV6_RECVHOPLIMIT:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.rxhlim = valbool;
retv = 0;
break;
case IPV6_2292HOPLIMIT:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.rxohlim = valbool;
retv = 0;
break;
case IPV6_RECVRTHDR:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.srcrt = valbool;
retv = 0;
break;
case IPV6_2292RTHDR:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.osrcrt = valbool;
retv = 0;
break;
case IPV6_RECVHOPOPTS:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.hopopts = valbool;
retv = 0;
break;
case IPV6_2292HOPOPTS:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.ohopopts = valbool;
retv = 0;
break;
case IPV6_RECVDSTOPTS:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.dstopts = valbool;
retv = 0;
break;
case IPV6_2292DSTOPTS:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.odstopts = valbool;
retv = 0;
break;
case IPV6_TCLASS:
if (optlen < sizeof(int))
goto e_inval;
if (val < -1 || val > 0xff)
goto e_inval;
/* RFC 3542, 6.5: default traffic class of 0x0 */
if (val == -1)
val = 0;
np->tclass = val;
retv = 0;
break;
case IPV6_RECVTCLASS:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.rxtclass = valbool;
retv = 0;
break;
case IPV6_FLOWINFO:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.rxflow = valbool;
retv = 0;
break;
case IPV6_RECVPATHMTU:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.rxpmtu = valbool;
retv = 0;
break;
case IPV6_TRANSPARENT:
if (valbool && !ns_capable(net->user_ns, CAP_NET_ADMIN) &&
!ns_capable(net->user_ns, CAP_NET_RAW)) {
retv = -EPERM;
break;
}
if (optlen < sizeof(int))
goto e_inval;
/* we don't have a separate transparent bit for IPV6 we use the one in the IPv4 socket */
inet_sk(sk)->transparent = valbool;
retv = 0;
break;
case IPV6_RECVORIGDSTADDR:
if (optlen < sizeof(int))
goto e_inval;
np->rxopt.bits.rxorigdstaddr = valbool;
retv = 0;
break;
case IPV6_HOPOPTS:
case IPV6_RTHDRDSTOPTS:
case IPV6_RTHDR:
case IPV6_DSTOPTS:
{
struct ipv6_txoptions *opt;
/* remove any sticky options header with a zero option
* length, per RFC3542.
*/
if (optlen == 0)
optval = NULL;
else if (!optval)
goto e_inval;
else if (optlen < sizeof(struct ipv6_opt_hdr) ||
optlen & 0x7 || optlen > 8 * 255)
goto e_inval;
/* hop-by-hop / destination options are privileged option */
retv = -EPERM;
if (optname != IPV6_RTHDR && !ns_capable(net->user_ns, CAP_NET_RAW))
break;
opt = ipv6_renew_options(sk, np->opt, optname,
(struct ipv6_opt_hdr __user *)optval,
optlen);
if (IS_ERR(opt)) {
retv = PTR_ERR(opt);
break;
}
/* routing header option needs extra check */
retv = -EINVAL;
if (optname == IPV6_RTHDR && opt && opt->srcrt) {
struct ipv6_rt_hdr *rthdr = opt->srcrt;
switch (rthdr->type) {
#if IS_ENABLED(CONFIG_IPV6_MIP6)
case IPV6_SRCRT_TYPE_2:
if (rthdr->hdrlen != 2 ||
rthdr->segments_left != 1)
goto sticky_done;
break;
#endif
default:
goto sticky_done;
}
}
retv = 0;
opt = ipv6_update_options(sk, opt);
sticky_done:
if (opt)
sock_kfree_s(sk, opt, opt->tot_len);
break;
}
case IPV6_PKTINFO:
{
struct in6_pktinfo pkt;
if (optlen == 0)
goto e_inval;
else if (optlen < sizeof(struct in6_pktinfo) || !optval)
goto e_inval;
if (copy_from_user(&pkt, optval, sizeof(struct in6_pktinfo))) {
retv = -EFAULT;
break;
}
if (sk->sk_bound_dev_if && pkt.ipi6_ifindex != sk->sk_bound_dev_if)
goto e_inval;
np->sticky_pktinfo.ipi6_ifindex = pkt.ipi6_ifindex;
np->sticky_pktinfo.ipi6_addr = pkt.ipi6_addr;
retv = 0;
break;
}
case IPV6_2292PKTOPTIONS:
{
struct ipv6_txoptions *opt = NULL;
struct msghdr msg;
struct flowi6 fl6;
int junk;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.flowi6_mark = sk->sk_mark;
if (optlen == 0)
goto update;
/* 1K is probably excessive
* 1K is surely not enough, 2K per standard header is 16K.
*/
retv = -EINVAL;
if (optlen > 64*1024)
break;
opt = sock_kmalloc(sk, sizeof(*opt) + optlen, GFP_KERNEL);
retv = -ENOBUFS;
if (!opt)
break;
memset(opt, 0, sizeof(*opt));
opt->tot_len = sizeof(*opt) + optlen;
retv = -EFAULT;
if (copy_from_user(opt+1, optval, optlen))
goto done;
msg.msg_controllen = optlen;
msg.msg_control = (void *)(opt+1);
retv = ip6_datagram_send_ctl(net, sk, &msg, &fl6, opt, &junk,
&junk, &junk);
if (retv)
goto done;
update:
retv = 0;
opt = ipv6_update_options(sk, opt);
done:
if (opt)
sock_kfree_s(sk, opt, opt->tot_len);
break;
}
case IPV6_UNICAST_HOPS:
if (optlen < sizeof(int))
goto e_inval;
if (val > 255 || val < -1)
goto e_inval;
np->hop_limit = val;
retv = 0;
break;
case IPV6_MULTICAST_HOPS:
if (sk->sk_type == SOCK_STREAM)
break;
if (optlen < sizeof(int))
goto e_inval;
if (val > 255 || val < -1)
goto e_inval;
np->mcast_hops = (val == -1 ? IPV6_DEFAULT_MCASTHOPS : val);
retv = 0;
break;
case IPV6_MULTICAST_LOOP:
if (optlen < sizeof(int))
goto e_inval;
if (val != valbool)
goto e_inval;
np->mc_loop = valbool;
retv = 0;
break;
case IPV6_UNICAST_IF:
{
struct net_device *dev = NULL;
int ifindex;
if (optlen != sizeof(int))
goto e_inval;
ifindex = (__force int)ntohl((__force __be32)val);
if (ifindex == 0) {
np->ucast_oif = 0;
retv = 0;
break;
}
dev = dev_get_by_index(net, ifindex);
retv = -EADDRNOTAVAIL;
if (!dev)
break;
dev_put(dev);
retv = -EINVAL;
if (sk->sk_bound_dev_if)
break;
np->ucast_oif = ifindex;
retv = 0;
break;
}
case IPV6_MULTICAST_IF:
if (sk->sk_type == SOCK_STREAM)
break;
if (optlen < sizeof(int))
goto e_inval;
if (val) {
struct net_device *dev;
if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != val)
goto e_inval;
dev = dev_get_by_index(net, val);
if (!dev) {
retv = -ENODEV;
break;
}
dev_put(dev);
}
np->mcast_oif = val;
retv = 0;
break;
case IPV6_ADD_MEMBERSHIP:
case IPV6_DROP_MEMBERSHIP:
{
struct ipv6_mreq mreq;
if (optlen < sizeof(struct ipv6_mreq))
goto e_inval;
retv = -EPROTO;
if (inet_sk(sk)->is_icsk)
break;
retv = -EFAULT;
if (copy_from_user(&mreq, optval, sizeof(struct ipv6_mreq)))
break;
if (optname == IPV6_ADD_MEMBERSHIP)
retv = ipv6_sock_mc_join(sk, mreq.ipv6mr_ifindex, &mreq.ipv6mr_multiaddr);
else
retv = ipv6_sock_mc_drop(sk, mreq.ipv6mr_ifindex, &mreq.ipv6mr_multiaddr);
break;
}
case IPV6_JOIN_ANYCAST:
case IPV6_LEAVE_ANYCAST:
{
struct ipv6_mreq mreq;
if (optlen < sizeof(struct ipv6_mreq))
goto e_inval;
retv = -EFAULT;
if (copy_from_user(&mreq, optval, sizeof(struct ipv6_mreq)))
break;
if (optname == IPV6_JOIN_ANYCAST)
retv = ipv6_sock_ac_join(sk, mreq.ipv6mr_ifindex, &mreq.ipv6mr_acaddr);
else
retv = ipv6_sock_ac_drop(sk, mreq.ipv6mr_ifindex, &mreq.ipv6mr_acaddr);
break;
}
case MCAST_JOIN_GROUP:
case MCAST_LEAVE_GROUP:
{
struct group_req greq;
struct sockaddr_in6 *psin6;
if (optlen < sizeof(struct group_req))
goto e_inval;
retv = -EFAULT;
if (copy_from_user(&greq, optval, sizeof(struct group_req)))
break;
if (greq.gr_group.ss_family != AF_INET6) {
retv = -EADDRNOTAVAIL;
break;
}
psin6 = (struct sockaddr_in6 *)&greq.gr_group;
if (optname == MCAST_JOIN_GROUP)
retv = ipv6_sock_mc_join(sk, greq.gr_interface,
&psin6->sin6_addr);
else
retv = ipv6_sock_mc_drop(sk, greq.gr_interface,
&psin6->sin6_addr);
break;
}
case MCAST_JOIN_SOURCE_GROUP:
case MCAST_LEAVE_SOURCE_GROUP:
case MCAST_BLOCK_SOURCE:
case MCAST_UNBLOCK_SOURCE:
{
struct group_source_req greqs;
int omode, add;
if (optlen < sizeof(struct group_source_req))
goto e_inval;
if (copy_from_user(&greqs, optval, sizeof(greqs))) {
retv = -EFAULT;
break;
}
if (greqs.gsr_group.ss_family != AF_INET6 ||
greqs.gsr_source.ss_family != AF_INET6) {
retv = -EADDRNOTAVAIL;
break;
}
if (optname == MCAST_BLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 1;
} else if (optname == MCAST_UNBLOCK_SOURCE) {
omode = MCAST_EXCLUDE;
add = 0;
} else if (optname == MCAST_JOIN_SOURCE_GROUP) {
struct sockaddr_in6 *psin6;
psin6 = (struct sockaddr_in6 *)&greqs.gsr_group;
retv = ipv6_sock_mc_join(sk, greqs.gsr_interface,
&psin6->sin6_addr);
/* prior join w/ different source is ok */
if (retv && retv != -EADDRINUSE)
break;
omode = MCAST_INCLUDE;
add = 1;
} else /* MCAST_LEAVE_SOURCE_GROUP */ {
omode = MCAST_INCLUDE;
add = 0;
}
retv = ip6_mc_source(add, omode, sk, &greqs);
break;
}
case MCAST_MSFILTER:
{
struct group_filter *gsf;
if (optlen < GROUP_FILTER_SIZE(0))
goto e_inval;
if (optlen > sysctl_optmem_max) {
retv = -ENOBUFS;
break;
}
gsf = kmalloc(optlen, GFP_KERNEL);
if (!gsf) {
retv = -ENOBUFS;
break;
}
retv = -EFAULT;
if (copy_from_user(gsf, optval, optlen)) {
kfree(gsf);
break;
}
/* numsrc >= (4G-140)/128 overflow in 32 bits */
if (gsf->gf_numsrc >= 0x1ffffffU ||
gsf->gf_numsrc > sysctl_mld_max_msf) {
kfree(gsf);
retv = -ENOBUFS;
break;
}
if (GROUP_FILTER_SIZE(gsf->gf_numsrc) > optlen) {
kfree(gsf);
retv = -EINVAL;
break;
}
retv = ip6_mc_msfilter(sk, gsf);
kfree(gsf);
break;
}
case IPV6_ROUTER_ALERT:
if (optlen < sizeof(int))
goto e_inval;
retv = ip6_ra_control(sk, val);
break;
case IPV6_MTU_DISCOVER:
if (optlen < sizeof(int))
goto e_inval;
if (val < IPV6_PMTUDISC_DONT || val > IPV6_PMTUDISC_OMIT)
goto e_inval;
np->pmtudisc = val;
retv = 0;
break;
case IPV6_MTU:
if (optlen < sizeof(int))
goto e_inval;
if (val && val < IPV6_MIN_MTU)
goto e_inval;
np->frag_size = val;
retv = 0;
break;
case IPV6_RECVERR:
if (optlen < sizeof(int))
goto e_inval;
np->recverr = valbool;
if (!val)
skb_queue_purge(&sk->sk_error_queue);
retv = 0;
break;
case IPV6_FLOWINFO_SEND:
if (optlen < sizeof(int))
goto e_inval;
np->sndflow = valbool;
retv = 0;
break;
case IPV6_FLOWLABEL_MGR:
retv = ipv6_flowlabel_opt(sk, optval, optlen);
break;
case IPV6_IPSEC_POLICY:
case IPV6_XFRM_POLICY:
retv = -EPERM;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
break;
retv = xfrm_user_policy(sk, optname, optval, optlen);
break;
case IPV6_ADDR_PREFERENCES:
{
unsigned int pref = 0;
unsigned int prefmask = ~0;
if (optlen < sizeof(int))
goto e_inval;
retv = -EINVAL;
/* check PUBLIC/TMP/PUBTMP_DEFAULT conflicts */
switch (val & (IPV6_PREFER_SRC_PUBLIC|
IPV6_PREFER_SRC_TMP|
IPV6_PREFER_SRC_PUBTMP_DEFAULT)) {
case IPV6_PREFER_SRC_PUBLIC:
pref |= IPV6_PREFER_SRC_PUBLIC;
break;
case IPV6_PREFER_SRC_TMP:
pref |= IPV6_PREFER_SRC_TMP;
break;
case IPV6_PREFER_SRC_PUBTMP_DEFAULT:
break;
case 0:
goto pref_skip_pubtmp;
default:
goto e_inval;
}
prefmask &= ~(IPV6_PREFER_SRC_PUBLIC|
IPV6_PREFER_SRC_TMP);
pref_skip_pubtmp:
/* check HOME/COA conflicts */
switch (val & (IPV6_PREFER_SRC_HOME|IPV6_PREFER_SRC_COA)) {
case IPV6_PREFER_SRC_HOME:
break;
case IPV6_PREFER_SRC_COA:
pref |= IPV6_PREFER_SRC_COA;
case 0:
goto pref_skip_coa;
default:
goto e_inval;
}
prefmask &= ~IPV6_PREFER_SRC_COA;
pref_skip_coa:
/* check CGA/NONCGA conflicts */
switch (val & (IPV6_PREFER_SRC_CGA|IPV6_PREFER_SRC_NONCGA)) {
case IPV6_PREFER_SRC_CGA:
case IPV6_PREFER_SRC_NONCGA:
case 0:
break;
default:
goto e_inval;
}
np->srcprefs = (np->srcprefs & prefmask) | pref;
retv = 0;
break;
}
case IPV6_MINHOPCOUNT:
if (optlen < sizeof(int))
goto e_inval;
if (val < 0 || val > 255)
goto e_inval;
np->min_hopcount = val;
retv = 0;
break;
case IPV6_DONTFRAG:
np->dontfrag = valbool;
retv = 0;
break;
case IPV6_AUTOFLOWLABEL:
np->autoflowlabel = valbool;
retv = 0;
break;
}
release_sock(sk);
if (needs_rtnl)
rtnl_unlock();
return retv;
e_inval:
release_sock(sk);
if (needs_rtnl)
rtnl_unlock();
return -EINVAL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[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: ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt)
{
struct ipv6_txoptions *opt2;
opt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC);
if (opt2) {
long dif = (char *)opt2 - (char *)opt;
memcpy(opt2, opt, opt->tot_len);
if (opt2->hopopt)
*((char **)&opt2->hopopt) += dif;
if (opt2->dst0opt)
*((char **)&opt2->dst0opt) += dif;
if (opt2->dst1opt)
*((char **)&opt2->dst1opt) += dif;
if (opt2->srcrt)
*((char **)&opt2->srcrt) += dif;
}
return opt2;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[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 l2tp_ip6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct ipv6_txoptions opt_space;
DECLARE_SOCKADDR(struct sockaddr_l2tpip6 *, lsa, msg->msg_name);
struct in6_addr *daddr, *final_p, final;
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct flowi6 fl6;
int addr_len = msg->msg_namelen;
int hlimit = -1;
int tclass = -1;
int dontfrag = -1;
int transhdrlen = 4; /* zero session-id */
int ulen = len + transhdrlen;
int err;
/* Rough check on arithmetic overflow,
better check is made in ip6_append_data().
*/
if (len > INT_MAX)
return -EMSGSIZE;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/*
* Get and verify the address.
*/
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = sk->sk_mark;
if (lsa) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (lsa->l2tp_family && lsa->l2tp_family != AF_INET6)
return -EAFNOSUPPORT;
daddr = &lsa->l2tp_addr;
if (np->sndflow) {
fl6.flowlabel = lsa->l2tp_flowinfo & IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
}
}
/*
* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
lsa->l2tp_scope_id &&
ipv6_addr_type(daddr) & IPV6_ADDR_LINKLOCAL)
fl6.flowi6_oif = lsa->l2tp_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,
&hlimit, &tclass, &dontfrag);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel & IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
}
if (!(opt->opt_nflen|opt->opt_flen))
opt = NULL;
}
if (opt == NULL)
opt = np->opt;
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
fl6.flowi6_proto = sk->sk_protocol;
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (hlimit < 0)
hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
if (tclass < 0)
tclass = np->tclass;
if (dontfrag < 0)
dontfrag = np->dontfrag;
if (msg->msg_flags & MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
lock_sock(sk);
err = ip6_append_data(sk, ip_generic_getfrag, msg,
ulen, transhdrlen, hlimit, tclass, opt,
&fl6, (struct rt6_info *)dst,
msg->msg_flags, dontfrag);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = l2tp_ip6_push_pending_frames(sk);
release_sock(sk);
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
return err < 0 ? err : len;
do_confirm:
dst_confirm(dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[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 dccp_v6_connect(struct sock *sk, struct sockaddr *uaddr,
int addr_len)
{
struct sockaddr_in6 *usin = (struct sockaddr_in6 *)uaddr;
struct inet_connection_sock *icsk = inet_csk(sk);
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct dccp_sock *dp = dccp_sk(sk);
struct in6_addr *saddr = NULL, *final_p, final;
struct flowi6 fl6;
struct dst_entry *dst;
int addr_type;
int err;
dp->dccps_role = DCCP_ROLE_CLIENT;
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (usin->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
memset(&fl6, 0, sizeof(fl6));
if (np->sndflow) {
fl6.flowlabel = usin->sin6_flowinfo & IPV6_FLOWINFO_MASK;
IP6_ECN_flow_init(fl6.flowlabel);
if (fl6.flowlabel & IPV6_FLOWLABEL_MASK) {
struct ip6_flowlabel *flowlabel;
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
fl6_sock_release(flowlabel);
}
}
/*
* connect() to INADDR_ANY means loopback (BSD'ism).
*/
if (ipv6_addr_any(&usin->sin6_addr))
usin->sin6_addr.s6_addr[15] = 1;
addr_type = ipv6_addr_type(&usin->sin6_addr);
if (addr_type & IPV6_ADDR_MULTICAST)
return -ENETUNREACH;
if (addr_type & IPV6_ADDR_LINKLOCAL) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
usin->sin6_scope_id) {
/* If interface is set while binding, indices
* must coincide.
*/
if (sk->sk_bound_dev_if &&
sk->sk_bound_dev_if != usin->sin6_scope_id)
return -EINVAL;
sk->sk_bound_dev_if = usin->sin6_scope_id;
}
/* Connect to link-local address requires an interface */
if (!sk->sk_bound_dev_if)
return -EINVAL;
}
sk->sk_v6_daddr = usin->sin6_addr;
np->flow_label = fl6.flowlabel;
/*
* DCCP over IPv4
*/
if (addr_type == IPV6_ADDR_MAPPED) {
u32 exthdrlen = icsk->icsk_ext_hdr_len;
struct sockaddr_in sin;
SOCK_DEBUG(sk, "connect: ipv4 mapped\n");
if (__ipv6_only_sock(sk))
return -ENETUNREACH;
sin.sin_family = AF_INET;
sin.sin_port = usin->sin6_port;
sin.sin_addr.s_addr = usin->sin6_addr.s6_addr32[3];
icsk->icsk_af_ops = &dccp_ipv6_mapped;
sk->sk_backlog_rcv = dccp_v4_do_rcv;
err = dccp_v4_connect(sk, (struct sockaddr *)&sin, sizeof(sin));
if (err) {
icsk->icsk_ext_hdr_len = exthdrlen;
icsk->icsk_af_ops = &dccp_ipv6_af_ops;
sk->sk_backlog_rcv = dccp_v6_do_rcv;
goto failure;
}
np->saddr = sk->sk_v6_rcv_saddr;
return err;
}
if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr))
saddr = &sk->sk_v6_rcv_saddr;
fl6.flowi6_proto = IPPROTO_DCCP;
fl6.daddr = sk->sk_v6_daddr;
fl6.saddr = saddr ? *saddr : np->saddr;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.fl6_dport = usin->sin6_port;
fl6.fl6_sport = inet->inet_sport;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
final_p = fl6_update_dst(&fl6, np->opt, &final);
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto failure;
}
if (saddr == NULL) {
saddr = &fl6.saddr;
sk->sk_v6_rcv_saddr = *saddr;
}
/* set the source address */
np->saddr = *saddr;
inet->inet_rcv_saddr = LOOPBACK4_IPV6;
__ip6_dst_store(sk, dst, NULL, NULL);
icsk->icsk_ext_hdr_len = 0;
if (np->opt != NULL)
icsk->icsk_ext_hdr_len = (np->opt->opt_flen +
np->opt->opt_nflen);
inet->inet_dport = usin->sin6_port;
dccp_set_state(sk, DCCP_REQUESTING);
err = inet6_hash_connect(&dccp_death_row, sk);
if (err)
goto late_failure;
dp->dccps_iss = secure_dccpv6_sequence_number(np->saddr.s6_addr32,
sk->sk_v6_daddr.s6_addr32,
inet->inet_sport,
inet->inet_dport);
err = dccp_connect(sk);
if (err)
goto late_failure;
return 0;
late_failure:
dccp_set_state(sk, DCCP_CLOSED);
__sk_dst_reset(sk);
failure:
inet->inet_dport = 0;
sk->sk_route_caps = 0;
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[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 do_ipv6_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen, unsigned int flags)
{
struct ipv6_pinfo *np = inet6_sk(sk);
int len;
int val;
if (ip6_mroute_opt(optname))
return ip6_mroute_getsockopt(sk, optname, optval, optlen);
if (get_user(len, optlen))
return -EFAULT;
switch (optname) {
case IPV6_ADDRFORM:
if (sk->sk_protocol != IPPROTO_UDP &&
sk->sk_protocol != IPPROTO_UDPLITE &&
sk->sk_protocol != IPPROTO_TCP)
return -ENOPROTOOPT;
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
val = sk->sk_family;
break;
case MCAST_MSFILTER:
{
struct group_filter gsf;
int err;
if (len < GROUP_FILTER_SIZE(0))
return -EINVAL;
if (copy_from_user(&gsf, optval, GROUP_FILTER_SIZE(0)))
return -EFAULT;
if (gsf.gf_group.ss_family != AF_INET6)
return -EADDRNOTAVAIL;
lock_sock(sk);
err = ip6_mc_msfget(sk, &gsf,
(struct group_filter __user *)optval, optlen);
release_sock(sk);
return err;
}
case IPV6_2292PKTOPTIONS:
{
struct msghdr msg;
struct sk_buff *skb;
if (sk->sk_type != SOCK_STREAM)
return -ENOPROTOOPT;
msg.msg_control = optval;
msg.msg_controllen = len;
msg.msg_flags = flags;
lock_sock(sk);
skb = np->pktoptions;
if (skb)
ip6_datagram_recv_ctl(sk, &msg, skb);
release_sock(sk);
if (!skb) {
if (np->rxopt.bits.rxinfo) {
struct in6_pktinfo src_info;
src_info.ipi6_ifindex = np->mcast_oif ? np->mcast_oif :
np->sticky_pktinfo.ipi6_ifindex;
src_info.ipi6_addr = np->mcast_oif ? sk->sk_v6_daddr : np->sticky_pktinfo.ipi6_addr;
put_cmsg(&msg, SOL_IPV6, IPV6_PKTINFO, sizeof(src_info), &src_info);
}
if (np->rxopt.bits.rxhlim) {
int hlim = np->mcast_hops;
put_cmsg(&msg, SOL_IPV6, IPV6_HOPLIMIT, sizeof(hlim), &hlim);
}
if (np->rxopt.bits.rxtclass) {
int tclass = (int)ip6_tclass(np->rcv_flowinfo);
put_cmsg(&msg, SOL_IPV6, IPV6_TCLASS, sizeof(tclass), &tclass);
}
if (np->rxopt.bits.rxoinfo) {
struct in6_pktinfo src_info;
src_info.ipi6_ifindex = np->mcast_oif ? np->mcast_oif :
np->sticky_pktinfo.ipi6_ifindex;
src_info.ipi6_addr = np->mcast_oif ? sk->sk_v6_daddr :
np->sticky_pktinfo.ipi6_addr;
put_cmsg(&msg, SOL_IPV6, IPV6_2292PKTINFO, sizeof(src_info), &src_info);
}
if (np->rxopt.bits.rxohlim) {
int hlim = np->mcast_hops;
put_cmsg(&msg, SOL_IPV6, IPV6_2292HOPLIMIT, sizeof(hlim), &hlim);
}
if (np->rxopt.bits.rxflow) {
__be32 flowinfo = np->rcv_flowinfo;
put_cmsg(&msg, SOL_IPV6, IPV6_FLOWINFO, sizeof(flowinfo), &flowinfo);
}
}
len -= msg.msg_controllen;
return put_user(len, optlen);
}
case IPV6_MTU:
{
struct dst_entry *dst;
val = 0;
rcu_read_lock();
dst = __sk_dst_get(sk);
if (dst)
val = dst_mtu(dst);
rcu_read_unlock();
if (!val)
return -ENOTCONN;
break;
}
case IPV6_V6ONLY:
val = sk->sk_ipv6only;
break;
case IPV6_RECVPKTINFO:
val = np->rxopt.bits.rxinfo;
break;
case IPV6_2292PKTINFO:
val = np->rxopt.bits.rxoinfo;
break;
case IPV6_RECVHOPLIMIT:
val = np->rxopt.bits.rxhlim;
break;
case IPV6_2292HOPLIMIT:
val = np->rxopt.bits.rxohlim;
break;
case IPV6_RECVRTHDR:
val = np->rxopt.bits.srcrt;
break;
case IPV6_2292RTHDR:
val = np->rxopt.bits.osrcrt;
break;
case IPV6_HOPOPTS:
case IPV6_RTHDRDSTOPTS:
case IPV6_RTHDR:
case IPV6_DSTOPTS:
{
lock_sock(sk);
len = ipv6_getsockopt_sticky(sk, np->opt,
optname, optval, len);
release_sock(sk);
/* check if ipv6_getsockopt_sticky() returns err code */
if (len < 0)
return len;
return put_user(len, optlen);
}
case IPV6_RECVHOPOPTS:
val = np->rxopt.bits.hopopts;
break;
case IPV6_2292HOPOPTS:
val = np->rxopt.bits.ohopopts;
break;
case IPV6_RECVDSTOPTS:
val = np->rxopt.bits.dstopts;
break;
case IPV6_2292DSTOPTS:
val = np->rxopt.bits.odstopts;
break;
case IPV6_TCLASS:
val = np->tclass;
break;
case IPV6_RECVTCLASS:
val = np->rxopt.bits.rxtclass;
break;
case IPV6_FLOWINFO:
val = np->rxopt.bits.rxflow;
break;
case IPV6_RECVPATHMTU:
val = np->rxopt.bits.rxpmtu;
break;
case IPV6_PATHMTU:
{
struct dst_entry *dst;
struct ip6_mtuinfo mtuinfo;
if (len < sizeof(mtuinfo))
return -EINVAL;
len = sizeof(mtuinfo);
memset(&mtuinfo, 0, sizeof(mtuinfo));
rcu_read_lock();
dst = __sk_dst_get(sk);
if (dst)
mtuinfo.ip6m_mtu = dst_mtu(dst);
rcu_read_unlock();
if (!mtuinfo.ip6m_mtu)
return -ENOTCONN;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &mtuinfo, len))
return -EFAULT;
return 0;
}
case IPV6_TRANSPARENT:
val = inet_sk(sk)->transparent;
break;
case IPV6_RECVORIGDSTADDR:
val = np->rxopt.bits.rxorigdstaddr;
break;
case IPV6_UNICAST_HOPS:
case IPV6_MULTICAST_HOPS:
{
struct dst_entry *dst;
if (optname == IPV6_UNICAST_HOPS)
val = np->hop_limit;
else
val = np->mcast_hops;
if (val < 0) {
rcu_read_lock();
dst = __sk_dst_get(sk);
if (dst)
val = ip6_dst_hoplimit(dst);
rcu_read_unlock();
}
if (val < 0)
val = sock_net(sk)->ipv6.devconf_all->hop_limit;
break;
}
case IPV6_MULTICAST_LOOP:
val = np->mc_loop;
break;
case IPV6_MULTICAST_IF:
val = np->mcast_oif;
break;
case IPV6_UNICAST_IF:
val = (__force int)htonl((__u32) np->ucast_oif);
break;
case IPV6_MTU_DISCOVER:
val = np->pmtudisc;
break;
case IPV6_RECVERR:
val = np->recverr;
break;
case IPV6_FLOWINFO_SEND:
val = np->sndflow;
break;
case IPV6_FLOWLABEL_MGR:
{
struct in6_flowlabel_req freq;
int flags;
if (len < sizeof(freq))
return -EINVAL;
if (copy_from_user(&freq, optval, sizeof(freq)))
return -EFAULT;
if (freq.flr_action != IPV6_FL_A_GET)
return -EINVAL;
len = sizeof(freq);
flags = freq.flr_flags;
memset(&freq, 0, sizeof(freq));
val = ipv6_flowlabel_opt_get(sk, &freq, flags);
if (val < 0)
return val;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &freq, len))
return -EFAULT;
return 0;
}
case IPV6_ADDR_PREFERENCES:
val = 0;
if (np->srcprefs & IPV6_PREFER_SRC_TMP)
val |= IPV6_PREFER_SRC_TMP;
else if (np->srcprefs & IPV6_PREFER_SRC_PUBLIC)
val |= IPV6_PREFER_SRC_PUBLIC;
else {
/* XXX: should we return system default? */
val |= IPV6_PREFER_SRC_PUBTMP_DEFAULT;
}
if (np->srcprefs & IPV6_PREFER_SRC_COA)
val |= IPV6_PREFER_SRC_COA;
else
val |= IPV6_PREFER_SRC_HOME;
break;
case IPV6_MINHOPCOUNT:
val = np->min_hopcount;
break;
case IPV6_DONTFRAG:
val = np->dontfrag;
break;
case IPV6_AUTOFLOWLABEL:
val = np->autoflowlabel;
break;
default:
return -ENOPROTOOPT;
}
len = min_t(unsigned int, sizeof(int), len);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[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 __ip6_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct in6_addr *daddr, *final_p, final;
struct dst_entry *dst;
struct flowi6 fl6;
struct ip6_flowlabel *flowlabel = NULL;
struct ipv6_txoptions *opt;
int addr_type;
int err;
if (usin->sin6_family == AF_INET) {
if (__ipv6_only_sock(sk))
return -EAFNOSUPPORT;
err = __ip4_datagram_connect(sk, uaddr, addr_len);
goto ipv4_connected;
}
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (usin->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
memset(&fl6, 0, sizeof(fl6));
if (np->sndflow) {
fl6.flowlabel = usin->sin6_flowinfo&IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
}
addr_type = ipv6_addr_type(&usin->sin6_addr);
if (addr_type == IPV6_ADDR_ANY) {
/*
* connect to self
*/
usin->sin6_addr.s6_addr[15] = 0x01;
}
daddr = &usin->sin6_addr;
if (addr_type == IPV6_ADDR_MAPPED) {
struct sockaddr_in sin;
if (__ipv6_only_sock(sk)) {
err = -ENETUNREACH;
goto out;
}
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = daddr->s6_addr32[3];
sin.sin_port = usin->sin6_port;
err = __ip4_datagram_connect(sk,
(struct sockaddr *) &sin,
sizeof(sin));
ipv4_connected:
if (err)
goto out;
ipv6_addr_set_v4mapped(inet->inet_daddr, &sk->sk_v6_daddr);
if (ipv6_addr_any(&np->saddr) ||
ipv6_mapped_addr_any(&np->saddr))
ipv6_addr_set_v4mapped(inet->inet_saddr, &np->saddr);
if (ipv6_addr_any(&sk->sk_v6_rcv_saddr) ||
ipv6_mapped_addr_any(&sk->sk_v6_rcv_saddr)) {
ipv6_addr_set_v4mapped(inet->inet_rcv_saddr,
&sk->sk_v6_rcv_saddr);
if (sk->sk_prot->rehash)
sk->sk_prot->rehash(sk);
}
goto out;
}
if (__ipv6_addr_needs_scope_id(addr_type)) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
usin->sin6_scope_id) {
if (sk->sk_bound_dev_if &&
sk->sk_bound_dev_if != usin->sin6_scope_id) {
err = -EINVAL;
goto out;
}
sk->sk_bound_dev_if = usin->sin6_scope_id;
}
if (!sk->sk_bound_dev_if && (addr_type & IPV6_ADDR_MULTICAST))
sk->sk_bound_dev_if = np->mcast_oif;
/* Connect to link-local address requires an interface */
if (!sk->sk_bound_dev_if) {
err = -EINVAL;
goto out;
}
}
sk->sk_v6_daddr = *daddr;
np->flow_label = fl6.flowlabel;
inet->inet_dport = usin->sin6_port;
/*
* Check for a route to destination an obtain the
* destination cache for it.
*/
fl6.flowi6_proto = sk->sk_protocol;
fl6.daddr = sk->sk_v6_daddr;
fl6.saddr = np->saddr;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.flowi6_mark = sk->sk_mark;
fl6.fl6_dport = inet->inet_dport;
fl6.fl6_sport = inet->inet_sport;
if (!fl6.flowi6_oif && (addr_type&IPV6_ADDR_MULTICAST))
fl6.flowi6_oif = np->mcast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
opt = flowlabel ? flowlabel->opt : np->opt;
final_p = fl6_update_dst(&fl6, opt, &final);
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
err = 0;
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
/* source address lookup done in ip6_dst_lookup */
if (ipv6_addr_any(&np->saddr))
np->saddr = fl6.saddr;
if (ipv6_addr_any(&sk->sk_v6_rcv_saddr)) {
sk->sk_v6_rcv_saddr = fl6.saddr;
inet->inet_rcv_saddr = LOOPBACK4_IPV6;
if (sk->sk_prot->rehash)
sk->sk_prot->rehash(sk);
}
ip6_dst_store(sk, dst,
ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr) ?
&sk->sk_v6_daddr : NULL,
#ifdef CONFIG_IPV6_SUBTREES
ipv6_addr_equal(&fl6.saddr, &np->saddr) ?
&np->saddr :
#endif
NULL);
sk->sk_state = TCP_ESTABLISHED;
sk_set_txhash(sk);
out:
fl6_sock_release(flowlabel);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[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 struct sock *dccp_v6_request_recv_sock(const struct sock *sk,
struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst,
struct request_sock *req_unhash,
bool *own_req)
{
struct inet_request_sock *ireq = inet_rsk(req);
struct ipv6_pinfo *newnp;
const struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_sock *newinet;
struct dccp6_sock *newdp6;
struct sock *newsk;
if (skb->protocol == htons(ETH_P_IP)) {
/*
* v6 mapped
*/
newsk = dccp_v4_request_recv_sock(sk, skb, req, dst,
req_unhash, own_req);
if (newsk == NULL)
return NULL;
newdp6 = (struct dccp6_sock *)newsk;
newinet = inet_sk(newsk);
newinet->pinet6 = &newdp6->inet6;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newnp->saddr = newsk->sk_v6_rcv_saddr;
inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped;
newsk->sk_backlog_rcv = dccp_v4_do_rcv;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks count
* here, dccp_create_openreq_child now does this for us, see the comment in
* that function for the gory details. -acme
*/
/* It is tricky place. Until this moment IPv4 tcp
worked with IPv6 icsk.icsk_af_ops.
Sync it now.
*/
dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie);
return newsk;
}
if (sk_acceptq_is_full(sk))
goto out_overflow;
if (!dst) {
struct flowi6 fl6;
dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP);
if (!dst)
goto out;
}
newsk = dccp_create_openreq_child(sk, req, skb);
if (newsk == NULL)
goto out_nonewsk;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks
* count here, dccp_create_openreq_child now does this for us, see the
* comment in that function for the gory details. -acme
*/
__ip6_dst_store(newsk, dst, NULL, NULL);
newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM |
NETIF_F_TSO);
newdp6 = (struct dccp6_sock *)newsk;
newinet = inet_sk(newsk);
newinet->pinet6 = &newdp6->inet6;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr;
newnp->saddr = ireq->ir_v6_loc_addr;
newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr;
newsk->sk_bound_dev_if = ireq->ir_iif;
/* Now IPv6 options...
First: no IPv4 options.
*/
newinet->inet_opt = NULL;
/* Clone RX bits */
newnp->rxopt.all = np->rxopt.all;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/*
* Clone native IPv6 options from listening socket (if any)
*
* Yes, keeping reference count would be much more clever, but we make
* one more one thing there: reattach optmem to newsk.
*/
if (np->opt != NULL)
newnp->opt = ipv6_dup_options(newsk, np->opt);
inet_csk(newsk)->icsk_ext_hdr_len = 0;
if (newnp->opt != NULL)
inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen +
newnp->opt->opt_flen);
dccp_sync_mss(newsk, dst_mtu(dst));
newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6;
newinet->inet_rcv_saddr = LOOPBACK4_IPV6;
if (__inet_inherit_port(sk, newsk) < 0) {
inet_csk_prepare_forced_close(newsk);
dccp_done(newsk);
goto out;
}
*own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash));
/* Clone pktoptions received with SYN, if we own the req */
if (*own_req && ireq->pktopts) {
newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC);
consume_skb(ireq->pktopts);
ireq->pktopts = NULL;
if (newnp->pktoptions)
skb_set_owner_r(newnp->pktoptions, newsk);
}
return newsk;
out_overflow:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
out_nonewsk:
dst_release(dst);
out:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS);
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[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 struct sock *tcp_v6_syn_recv_sock(const struct sock *sk, struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst,
struct request_sock *req_unhash,
bool *own_req)
{
struct inet_request_sock *ireq;
struct ipv6_pinfo *newnp;
const struct ipv6_pinfo *np = inet6_sk(sk);
struct tcp6_sock *newtcp6sk;
struct inet_sock *newinet;
struct tcp_sock *newtp;
struct sock *newsk;
#ifdef CONFIG_TCP_MD5SIG
struct tcp_md5sig_key *key;
#endif
struct flowi6 fl6;
if (skb->protocol == htons(ETH_P_IP)) {
/*
* v6 mapped
*/
newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst,
req_unhash, own_req);
if (!newsk)
return NULL;
newtcp6sk = (struct tcp6_sock *)newsk;
inet_sk(newsk)->pinet6 = &newtcp6sk->inet6;
newinet = inet_sk(newsk);
newnp = inet6_sk(newsk);
newtp = tcp_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newnp->saddr = newsk->sk_v6_rcv_saddr;
inet_csk(newsk)->icsk_af_ops = &ipv6_mapped;
newsk->sk_backlog_rcv = tcp_v4_do_rcv;
#ifdef CONFIG_TCP_MD5SIG
newtp->af_specific = &tcp_sock_ipv6_mapped_specific;
#endif
newnp->ipv6_ac_list = NULL;
newnp->ipv6_fl_list = NULL;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = tcp_v6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb));
if (np->repflow)
newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb));
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks count
* here, tcp_create_openreq_child now does this for us, see the comment in
* that function for the gory details. -acme
*/
/* It is tricky place. Until this moment IPv4 tcp
worked with IPv6 icsk.icsk_af_ops.
Sync it now.
*/
tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie);
return newsk;
}
ireq = inet_rsk(req);
if (sk_acceptq_is_full(sk))
goto out_overflow;
if (!dst) {
dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_TCP);
if (!dst)
goto out;
}
newsk = tcp_create_openreq_child(sk, req, skb);
if (!newsk)
goto out_nonewsk;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks
* count here, tcp_create_openreq_child now does this for us, see the
* comment in that function for the gory details. -acme
*/
newsk->sk_gso_type = SKB_GSO_TCPV6;
__ip6_dst_store(newsk, dst, NULL, NULL);
inet6_sk_rx_dst_set(newsk, skb);
newtcp6sk = (struct tcp6_sock *)newsk;
inet_sk(newsk)->pinet6 = &newtcp6sk->inet6;
newtp = tcp_sk(newsk);
newinet = inet_sk(newsk);
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr;
newnp->saddr = ireq->ir_v6_loc_addr;
newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr;
newsk->sk_bound_dev_if = ireq->ir_iif;
/* Now IPv6 options...
First: no IPv4 options.
*/
newinet->inet_opt = NULL;
newnp->ipv6_ac_list = NULL;
newnp->ipv6_fl_list = NULL;
/* Clone RX bits */
newnp->rxopt.all = np->rxopt.all;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = tcp_v6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb));
if (np->repflow)
newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb));
/* Clone native IPv6 options from listening socket (if any)
Yes, keeping reference count would be much more clever,
but we make one more one thing there: reattach optmem
to newsk.
*/
if (np->opt)
newnp->opt = ipv6_dup_options(newsk, np->opt);
inet_csk(newsk)->icsk_ext_hdr_len = 0;
if (newnp->opt)
inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen +
newnp->opt->opt_flen);
tcp_ca_openreq_child(newsk, dst);
tcp_sync_mss(newsk, dst_mtu(dst));
newtp->advmss = dst_metric_advmss(dst);
if (tcp_sk(sk)->rx_opt.user_mss &&
tcp_sk(sk)->rx_opt.user_mss < newtp->advmss)
newtp->advmss = tcp_sk(sk)->rx_opt.user_mss;
tcp_initialize_rcv_mss(newsk);
newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6;
newinet->inet_rcv_saddr = LOOPBACK4_IPV6;
#ifdef CONFIG_TCP_MD5SIG
/* Copy over the MD5 key from the original socket */
key = tcp_v6_md5_do_lookup(sk, &newsk->sk_v6_daddr);
if (key) {
/* We're using one, so create a matching key
* on the newsk structure. If we fail to get
* memory, then we end up not copying the key
* across. Shucks.
*/
tcp_md5_do_add(newsk, (union tcp_md5_addr *)&newsk->sk_v6_daddr,
AF_INET6, key->key, key->keylen,
sk_gfp_atomic(sk, GFP_ATOMIC));
}
#endif
if (__inet_inherit_port(sk, newsk) < 0) {
inet_csk_prepare_forced_close(newsk);
tcp_done(newsk);
goto out;
}
*own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash));
if (*own_req) {
tcp_move_syn(newtp, req);
/* Clone pktoptions received with SYN, if we own the req */
if (ireq->pktopts) {
newnp->pktoptions = skb_clone(ireq->pktopts,
sk_gfp_atomic(sk, GFP_ATOMIC));
consume_skb(ireq->pktopts);
ireq->pktopts = NULL;
if (newnp->pktoptions)
skb_set_owner_r(newnp->pktoptions, newsk);
}
}
return newsk;
out_overflow:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
out_nonewsk:
dst_release(dst);
out:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS);
return NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[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 struct dst_entry *inet6_csk_route_socket(struct sock *sk,
struct flowi6 *fl6)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct in6_addr *final_p, final;
struct dst_entry *dst;
memset(fl6, 0, sizeof(*fl6));
fl6->flowi6_proto = sk->sk_protocol;
fl6->daddr = sk->sk_v6_daddr;
fl6->saddr = np->saddr;
fl6->flowlabel = np->flow_label;
IP6_ECN_flow_xmit(sk, fl6->flowlabel);
fl6->flowi6_oif = sk->sk_bound_dev_if;
fl6->flowi6_mark = sk->sk_mark;
fl6->fl6_sport = inet->inet_sport;
fl6->fl6_dport = inet->inet_dport;
security_sk_classify_flow(sk, flowi6_to_flowi(fl6));
final_p = fl6_update_dst(fl6, np->opt, &final);
dst = __inet6_csk_dst_check(sk, np->dst_cookie);
if (!dst) {
dst = ip6_dst_lookup_flow(sk, fl6, final_p);
if (!IS_ERR(dst))
__inet6_csk_dst_store(sk, dst, NULL, NULL);
}
return dst;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[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: mix_pool(byte *pool)
{
char *hashbuf = pool + POOLSIZE;
char *p, *pend;
int i, n;
RMD160_CONTEXT md;
rmd160_init( &md );
#if DIGESTLEN != 20
#error must have a digest length of 20 for ripe-md-160
#endif
/* loop over the pool */
pend = pool + POOLSIZE;
memcpy(hashbuf, pend - DIGESTLEN, DIGESTLEN );
memcpy(hashbuf+DIGESTLEN, pool, BLOCKLEN-DIGESTLEN);
rmd160_mixblock( &md, hashbuf);
memcpy(pool, hashbuf, DIGESTLEN);
p = pool;
for( n=1; n < POOLBLOCKS; n++ ) {
memcpy(hashbuf, p, DIGESTLEN );
p += DIGESTLEN;
if( p+DIGESTLEN+BLOCKLEN < pend )
memcpy(hashbuf+DIGESTLEN, p+DIGESTLEN, BLOCKLEN-DIGESTLEN);
else {
char *pp = p+DIGESTLEN;
for(i=DIGESTLEN; i < BLOCKLEN; i++ ) {
if( pp >= pend )
pp = pool;
hashbuf[i] = *pp++;
}
}
rmd160_mixblock( &md, hashbuf);
memcpy(p, hashbuf, DIGESTLEN);
}
burn_stack (384); /* for the rmd160_mixblock() */
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-200'], 'message': 'random: Hash continuous areas in the csprng pool.
* cipher/random.c (mix_pool): Store the first hash at the end of the
pool.
--
This fixes a long standing bug (since 1998) in Libgcrypt and GnuPG.
An attacker who obtains 580 bytes of the random number from the
standard RNG can trivially predict the next 20 bytes of output.
This bug does not affect the default generation of
keys because running gpg for key creation creates at most 2 keys from
the pool: For a single 4096 bit RSA key 512 byte of random are
required and thus for the second key (encryption subkey), 20 bytes
could be predicted from the the first key. However, the security of
an OpenPGP key depends on the primary key (which was generated first)
and thus the 20 predictable bytes should not be a problem. For the
default key length of 2048 bit nothing will be predictable.
For the former default of DSA+Elgamal key it is complicate to give an
answer: For 2048 bit keys a pool of 30 non-secret candidate primes of
about 300 bits each are first created. This reads at least 1140 bytes
from the pool and thus parts could be predicted. At some point a 256
bit secret is read from the pool; which in the worst case might be
partly predictable.
The bug was found and reported by Felix Dörre and Vladimir Klebanov,
Karlsruhe Institute of Technology. A paper describing the problem in
detail will shortly be published.
CVE-id: CVE-2016-6313
Signed-off-by: Werner Koch <[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 tcp_check_send_head(struct sock *sk, struct sk_buff *skb_unlinked)
{
if (sk->sk_send_head == skb_unlinked)
sk->sk_send_head = NULL;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416', 'CWE-269'], 'message': 'tcp: fix use after free in tcp_xmit_retransmit_queue()
When tcp_sendmsg() allocates a fresh and empty skb, it puts it at the
tail of the write queue using tcp_add_write_queue_tail()
Then it attempts to copy user data into this fresh skb.
If the copy fails, we undo the work and remove the fresh skb.
Unfortunately, this undo lacks the change done to tp->highest_sack and
we can leave a dangling pointer (to a freed skb)
Later, tcp_xmit_retransmit_queue() can dereference this pointer and
access freed memory. For regular kernels where memory is not unmapped,
this might cause SACK bugs because tcp_highest_sack_seq() is buggy,
returning garbage instead of tp->snd_nxt, but with various debug
features like CONFIG_DEBUG_PAGEALLOC, this can crash the kernel.
This bug was found by Marco Grassi thanks to syzkaller.
Fixes: 6859d49475d4 ("[TCP]: Abstract tp->highest_sack accessing & point to next skb")
Reported-by: Marco Grassi <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Ilpo Järvinen <[email protected]>
Cc: Yuchung Cheng <[email protected]>
Cc: Neal Cardwell <[email protected]>
Acked-by: Neal Cardwell <[email protected]>
Reviewed-by: Cong Wang <[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: Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G)
{
int i, j;
Curves16Data* c16;
c16 = (Curves16Data*)_cmsMallocZero(ContextID, sizeof(Curves16Data));
if (c16 == NULL) return NULL;
c16 ->nCurves = nCurves;
c16 ->nElements = nElements;
c16->Curves = (cmsUInt16Number**) _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*));
if (c16 ->Curves == NULL) return NULL;
for (i=0; i < nCurves; i++) {
c16->Curves[i] = (cmsUInt16Number*) _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number));
if (c16->Curves[i] == NULL) {
for (j=0; j < i; j++) {
_cmsFree(ContextID, c16->Curves[j]);
}
_cmsFree(ContextID, c16->Curves);
_cmsFree(ContextID, c16);
return NULL;
}
if (nElements == 256) {
for (j=0; j < nElements; j++) {
c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j));
}
}
else {
for (j=0; j < nElements; j++) {
c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j);
}
}
}
return c16;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Contributed fixes from Oracle
Two minor glitches'</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 ovl_copy_up_locked(struct dentry *workdir, struct dentry *upperdir,
struct dentry *dentry, struct path *lowerpath,
struct kstat *stat, struct iattr *attr,
const char *link)
{
struct inode *wdir = workdir->d_inode;
struct inode *udir = upperdir->d_inode;
struct dentry *newdentry = NULL;
struct dentry *upper = NULL;
umode_t mode = stat->mode;
int err;
newdentry = ovl_lookup_temp(workdir, dentry);
err = PTR_ERR(newdentry);
if (IS_ERR(newdentry))
goto out;
upper = lookup_one_len(dentry->d_name.name, upperdir,
dentry->d_name.len);
err = PTR_ERR(upper);
if (IS_ERR(upper))
goto out1;
/* Can't properly set mode on creation because of the umask */
stat->mode &= S_IFMT;
err = ovl_create_real(wdir, newdentry, stat, link, NULL, true);
stat->mode = mode;
if (err)
goto out2;
if (S_ISREG(stat->mode)) {
struct path upperpath;
ovl_path_upper(dentry, &upperpath);
BUG_ON(upperpath.dentry != NULL);
upperpath.dentry = newdentry;
err = ovl_copy_up_data(lowerpath, &upperpath, stat->size);
if (err)
goto out_cleanup;
}
err = ovl_copy_xattr(lowerpath->dentry, newdentry);
if (err)
goto out_cleanup;
mutex_lock(&newdentry->d_inode->i_mutex);
err = ovl_set_attr(newdentry, stat);
if (!err && attr)
err = notify_change(newdentry, attr, NULL);
mutex_unlock(&newdentry->d_inode->i_mutex);
if (err)
goto out_cleanup;
err = ovl_do_rename(wdir, newdentry, udir, upper, 0);
if (err)
goto out_cleanup;
ovl_dentry_update(dentry, newdentry);
newdentry = NULL;
/*
* Non-directores become opaque when copied up.
*/
if (!S_ISDIR(stat->mode))
ovl_dentry_set_opaque(dentry, true);
out2:
dput(upper);
out1:
dput(newdentry);
out:
return err;
out_cleanup:
ovl_cleanup(wdir, newdentry);
goto out;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'ovl: fix dentry reference leak
In ovl_copy_up_locked(), newdentry is leaked if the function exits through
out_cleanup as this just to out after calling ovl_cleanup() - which doesn't
actually release the ref on newdentry.
The out_cleanup segment should instead exit through out2 as certainly
newdentry leaks - and possibly upper does also, though this isn't caught
given the catch of newdentry.
Without this fix, something like the following is seen:
BUG: Dentry ffff880023e9eb20{i=f861,n=#ffff880023e82d90} still in use (1) [unmount of tmpfs tmpfs]
BUG: Dentry ffff880023ece640{i=0,n=bigfile} still in use (1) [unmount of tmpfs tmpfs]
when unmounting the upper layer after an error occurred in copyup.
An error can be induced by creating a big file in a lower layer with
something like:
dd if=/dev/zero of=/lower/a/bigfile bs=65536 count=1 seek=$((0xf000))
to create a large file (4.1G). Overlay an upper layer that is too small
(on tmpfs might do) and then induce a copy up by opening it writably.
Reported-by: Ulrich Obergfell <[email protected]>
Signed-off-by: David Howells <[email protected]>
Signed-off-by: Miklos Szeredi <[email protected]>
Cc: <[email protected]> # v3.18+'</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 __jfs_set_acl(tid_t tid, struct inode *inode, int type,
struct posix_acl *acl)
{
char *ea_name;
int rc;
int size = 0;
char *value = NULL;
switch (type) {
case ACL_TYPE_ACCESS:
ea_name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
rc = posix_acl_equiv_mode(acl, &inode->i_mode);
if (rc < 0)
return rc;
inode->i_ctime = CURRENT_TIME;
mark_inode_dirty(inode);
if (rc == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
ea_name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_KERNEL);
if (!value)
return -ENOMEM;
rc = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (rc < 0)
goto out;
}
rc = __jfs_setxattr(tid, inode, ea_name, value, size, 0);
out:
kfree(value);
if (!rc)
set_cached_acl(inode, type, acl);
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-862', 'CWE-285'], 'message': 'posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[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 hfsplus_set_posix_acl(struct inode *inode, struct posix_acl *acl,
int type)
{
int err;
char *xattr_name;
size_t size = 0;
char *value = NULL;
hfs_dbg(ACL_MOD, "[%s]: ino %lu\n", __func__, inode->i_ino);
switch (type) {
case ACL_TYPE_ACCESS:
xattr_name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
err = posix_acl_equiv_mode(acl, &inode->i_mode);
if (err < 0)
return err;
}
err = 0;
break;
case ACL_TYPE_DEFAULT:
xattr_name = XATTR_NAME_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
if (unlikely(size > HFSPLUS_MAX_INLINE_DATA_SIZE))
return -ENOMEM;
value = (char *)hfsplus_alloc_attr_entry();
if (unlikely(!value))
return -ENOMEM;
err = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (unlikely(err < 0))
goto end_set_acl;
}
err = __hfsplus_setxattr(inode, xattr_name, value, size, 0);
end_set_acl:
hfsplus_destroy_attr_entry((hfsplus_attr_entry *)value);
if (!err)
set_cached_acl(inode, type, acl);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-862', 'CWE-285'], 'message': 'posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[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 __f2fs_set_acl(struct inode *inode, int type,
struct posix_acl *acl, struct page *ipage)
{
int name_index;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return error;
set_acl_inode(inode, inode->i_mode);
if (error == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = f2fs_acl_to_disk(acl, &size);
if (IS_ERR(value)) {
clear_inode_flag(inode, FI_ACL_MODE);
return (int)PTR_ERR(value);
}
}
error = f2fs_setxattr(inode, name_index, "", value, size, ipage, 0);
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
clear_inode_flag(inode, FI_ACL_MODE);
return error;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-862', 'CWE-285'], 'message': 'posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[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: __ext4_set_acl(handle_t *handle, struct inode *inode, int type,
struct posix_acl *acl)
{
int name_index;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return error;
else {
inode->i_ctime = ext4_current_time(inode);
ext4_mark_inode_dirty(handle, inode);
if (error == 0)
acl = NULL;
}
}
break;
case ACL_TYPE_DEFAULT:
name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = ext4_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = ext4_xattr_set_handle(handle, inode, name_index, "",
value, size, 0);
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-862', 'CWE-285'], 'message': 'posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[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 ceph_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int ret = 0, size = 0;
const char *name = NULL;
char *value = NULL;
struct iattr newattrs;
umode_t new_mode = inode->i_mode, old_mode = inode->i_mode;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
ret = posix_acl_equiv_mode(acl, &new_mode);
if (ret < 0)
goto out;
if (ret == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode)) {
ret = acl ? -EINVAL : 0;
goto out;
}
name = XATTR_NAME_POSIX_ACL_DEFAULT;
break;
default:
ret = -EINVAL;
goto out;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
value = kmalloc(size, GFP_NOFS);
if (!value) {
ret = -ENOMEM;
goto out;
}
ret = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (ret < 0)
goto out_free;
}
if (new_mode != old_mode) {
newattrs.ia_mode = new_mode;
newattrs.ia_valid = ATTR_MODE;
ret = __ceph_setattr(inode, &newattrs);
if (ret)
goto out_free;
}
ret = __ceph_setxattr(inode, name, value, size, 0);
if (ret) {
if (new_mode != old_mode) {
newattrs.ia_mode = old_mode;
newattrs.ia_valid = ATTR_MODE;
__ceph_setattr(inode, &newattrs);
}
goto out_free;
}
ceph_set_cached_acl(inode, type, acl);
out_free:
kfree(value);
out:
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-862', 'CWE-285'], 'message': 'posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[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: xfs_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error = 0;
if (!acl)
goto set_acl;
error = -E2BIG;
if (acl->a_count > XFS_ACL_MAX_ENTRIES(XFS_M(inode->i_sb)))
return error;
if (type == ACL_TYPE_ACCESS) {
umode_t mode = inode->i_mode;
error = posix_acl_equiv_mode(acl, &mode);
if (error <= 0) {
acl = NULL;
if (error < 0)
return error;
}
error = xfs_set_mode(inode, mode);
if (error)
return error;
}
set_acl:
return __xfs_set_acl(inode, type, acl);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-862', 'CWE-285'], 'message': 'posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[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: ext2_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int name_index;
void *value = NULL;
size_t size = 0;
int error;
switch(type) {
case ACL_TYPE_ACCESS:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return error;
else {
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
if (error == 0)
acl = NULL;
}
}
break;
case ACL_TYPE_DEFAULT:
name_index = EXT2_XATTR_INDEX_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = ext2_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = ext2_xattr_set(inode, name_index, "", value, size, 0);
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-862', 'CWE-285'], 'message': 'posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[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: vmxnet3_io_bar0_write(void *opaque, hwaddr addr,
uint64_t val, unsigned size)
{
VMXNET3State *s = opaque;
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_TXPROD,
VMXNET3_DEVICE_MAX_TX_QUEUES, VMXNET3_REG_ALIGN)) {
int tx_queue_idx =
VMW_MULTIREG_IDX_BY_ADDR(addr, VMXNET3_REG_TXPROD,
VMXNET3_REG_ALIGN);
assert(tx_queue_idx <= s->txq_num);
vmxnet3_process_tx_queue(s, tx_queue_idx);
return;
}
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_IMR,
VMXNET3_MAX_INTRS, VMXNET3_REG_ALIGN)) {
int l = VMW_MULTIREG_IDX_BY_ADDR(addr, VMXNET3_REG_IMR,
VMXNET3_REG_ALIGN);
VMW_CBPRN("Interrupt mask for line %d written: 0x%" PRIx64, l, val);
vmxnet3_on_interrupt_mask_changed(s, l, val);
return;
}
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD,
VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN) ||
VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD2,
VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN)) {
return;
}
VMW_WRPRN("BAR0 unknown write [%" PRIx64 "] = %" PRIx64 ", size %d",
(uint64_t) addr, val, size);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-416'], 'message': 'net: vmxnet3: check for device_active before write
Vmxnet3 device emulator does not check if the device is active,
before using it for write. It leads to a use after free issue,
if the vmxnet3_io_bar0_write routine is called after the device is
deactivated. Add check to avoid it.
Reported-by: Li Qiang <[email protected]>
Signed-off-by: Prasad J Pandit <[email protected]>
Acked-by: Dmitry Fleytman <[email protected]>
Signed-off-by: Jason Wang <[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 net_tx_pkt_init(struct NetTxPkt **pkt, PCIDevice *pci_dev,
uint32_t max_frags, bool has_virt_hdr)
{
struct NetTxPkt *p = g_malloc0(sizeof *p);
p->pci_dev = pci_dev;
p->vec = g_malloc((sizeof *p->vec) *
(max_frags + NET_TX_PKT_PL_START_FRAG));
p->raw = g_malloc((sizeof *p->raw) * max_frags);
p->max_payload_frags = max_frags;
p->max_raw_frags = max_frags;
p->has_virt_hdr = has_virt_hdr;
p->vec[NET_TX_PKT_VHDR_FRAG].iov_base = &p->virt_hdr;
p->vec[NET_TX_PKT_VHDR_FRAG].iov_len =
p->has_virt_hdr ? sizeof p->virt_hdr : 0;
p->vec[NET_TX_PKT_L2HDR_FRAG].iov_base = &p->l2_hdr;
p->vec[NET_TX_PKT_L3HDR_FRAG].iov_base = &p->l3_hdr;
*pkt = p;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'net: vmxnet: use g_new for pkt initialisation
When network transport abstraction layer initialises pkt, the maximum
fragmentation count is not checked. This could lead to an integer
overflow causing a NULL pointer dereference. Replace g_malloc() with
g_new() to catch the multiplication overflow.
Reported-by: Li Qiang <[email protected]>
Signed-off-by: Prasad J Pandit <[email protected]>
Acked-by: Dmitry Fleytman <[email protected]>
Signed-off-by: Jason Wang <[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: eog_image_load_error_message_area_new (const gchar *caption,
const GError *error)
{
GtkWidget *message_area;
gchar *error_message = NULL;
gchar *message_details = NULL;
gchar *pango_escaped_caption = NULL;
g_return_val_if_fail (caption != NULL, NULL);
g_return_val_if_fail (error != NULL, NULL);
/* Escape the caption string with respect to pango markup.
This is necessary because otherwise characters like "&" will
be interpreted as the beginning of a pango entity inside
the message area GtkLabel. */
pango_escaped_caption = g_markup_escape_text (caption, -1);
error_message = g_strdup_printf (_("Could not load image '%s'."),
pango_escaped_caption);
message_details = g_strdup (error->message);
message_area = create_error_message_area (error_message,
message_details,
EOG_ERROR_MESSAGE_AREA_CANCEL_BUTTON);
g_free (pango_escaped_caption);
g_free (error_message);
g_free (message_details);
return message_area;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'EogErrorMessageArea: Make sure error messages are valid UTF8
GMarkup requires valid UTF8 input strings and would cause odd
looking messages if given invalid input. This could also trigger an
out-of-bounds write in glib before 2.44.1. Reported by kaslovdmitri.
https://bugzilla.gnome.org/show_bug.cgi?id=770143'</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 rsa_verify_hash_ex(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int padding,
int hash_idx, unsigned long saltlen,
int *stat, rsa_key *key)
{
unsigned long modulus_bitlen, modulus_bytelen, x;
int err;
unsigned char *tmpbuf;
LTC_ARGCHK(hash != NULL);
LTC_ARGCHK(sig != NULL);
LTC_ARGCHK(stat != NULL);
LTC_ARGCHK(key != NULL);
/* default to invalid */
*stat = 0;
/* valid padding? */
if ((padding != LTC_LTC_PKCS_1_V1_5) &&
(padding != LTC_LTC_PKCS_1_PSS)) {
return CRYPT_PK_INVALID_PADDING;
}
if (padding == LTC_LTC_PKCS_1_PSS) {
/* valid hash ? */
if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
return err;
}
}
/* get modulus len in bits */
modulus_bitlen = mp_count_bits( (key->N));
/* outlen must be at least the size of the modulus */
modulus_bytelen = mp_unsigned_bin_size( (key->N));
if (modulus_bytelen != siglen) {
return CRYPT_INVALID_PACKET;
}
/* allocate temp buffer for decoded sig */
tmpbuf = XMALLOC(siglen);
if (tmpbuf == NULL) {
return CRYPT_MEM;
}
/* RSA decode it */
x = siglen;
if ((err = ltc_mp.rsa_me(sig, siglen, tmpbuf, &x, PK_PUBLIC, key)) != CRYPT_OK) {
XFREE(tmpbuf);
return err;
}
/* make sure the output is the right size */
if (x != siglen) {
XFREE(tmpbuf);
return CRYPT_INVALID_PACKET;
}
if (padding == LTC_LTC_PKCS_1_PSS) {
/* PSS decode and verify it */
err = pkcs_1_pss_decode(hash, hashlen, tmpbuf, x, saltlen, hash_idx, modulus_bitlen, stat);
} else {
/* LTC_PKCS #1 v1.5 decode it */
unsigned char *out;
unsigned long outlen, loid[16];
int decoded;
ltc_asn1_list digestinfo[2], siginfo[2];
/* not all hashes have OIDs... so sad */
if (hash_descriptor[hash_idx]->OIDlen == 0) {
err = CRYPT_INVALID_ARG;
goto bail_2;
}
/* allocate temp buffer for decoded hash */
outlen = ((modulus_bitlen >> 3) + (modulus_bitlen & 7 ? 1 : 0)) - 3;
out = XMALLOC(outlen);
if (out == NULL) {
err = CRYPT_MEM;
goto bail_2;
}
if ((err = pkcs_1_v1_5_decode(tmpbuf, x, LTC_LTC_PKCS_1_EMSA, modulus_bitlen, out, &outlen, &decoded)) != CRYPT_OK) {
XFREE(out);
goto bail_2;
}
/* now we must decode out[0...outlen-1] using ASN.1, test the OID and then test the hash */
/* construct the SEQUENCE
SEQUENCE {
SEQUENCE {hashoid OID
blah NULL
}
hash OCTET STRING
}
*/
LTC_SET_ASN1(digestinfo, 0, LTC_ASN1_OBJECT_IDENTIFIER, loid, sizeof(loid)/sizeof(loid[0]));
LTC_SET_ASN1(digestinfo, 1, LTC_ASN1_NULL, NULL, 0);
LTC_SET_ASN1(siginfo, 0, LTC_ASN1_SEQUENCE, digestinfo, 2);
LTC_SET_ASN1(siginfo, 1, LTC_ASN1_OCTET_STRING, tmpbuf, siglen);
if ((err = der_decode_sequence(out, outlen, siginfo, 2)) != CRYPT_OK) {
XFREE(out);
goto bail_2;
}
/* test OID */
if ((digestinfo[0].size == hash_descriptor[hash_idx]->OIDlen) &&
(XMEMCMP(digestinfo[0].data, hash_descriptor[hash_idx]->OID, sizeof(unsigned long) * hash_descriptor[hash_idx]->OIDlen) == 0) &&
(siginfo[1].size == hashlen) &&
(XMEMCMP(siginfo[1].data, hash, hashlen) == 0)) {
*stat = 1;
}
#ifdef LTC_CLEAN_STACK
zeromem(out, outlen);
#endif
XFREE(out);
}
bail_2:
#ifdef LTC_CLEAN_STACK
zeromem(tmpbuf, siglen);
#endif
XFREE(tmpbuf);
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'rsa_verify_hash: fix possible bleichenbacher signature attack
Fixes CVE-2016-6129
cherry-picked from:
https://github.com/libtom/libtomcrypt/commit/5eb9743410ce4657e9d54fef26a2ee31a1b5dd09
Acked-by: Jerome Forissier <[email protected]>
Tested-by: Jens Wiklander <[email protected]> (QEMU)
Signed-off-by: Joakim Bech <[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: gnutls_ocsp_resp_check_crt(gnutls_ocsp_resp_t resp,
unsigned int indx, gnutls_x509_crt_t crt)
{
int ret;
gnutls_digest_algorithm_t digest;
gnutls_datum_t rdn_hash = { NULL, 0 }, rserial = {
NULL, 0};
gnutls_datum_t cserial = { NULL, 0 };
gnutls_datum_t dn = { NULL, 0 };
uint8_t cdn_hash[MAX_HASH_SIZE];
size_t t, hash_len;
ret =
gnutls_ocsp_resp_get_single(resp, indx, &digest, &rdn_hash,
NULL, &rserial, NULL, NULL, NULL,
NULL, NULL);
if (ret < 0)
return gnutls_assert_val(ret);
if (rserial.size == 0 || digest == GNUTLS_DIG_UNKNOWN) {
ret = gnutls_assert_val(GNUTLS_E_OCSP_RESPONSE_ERROR);
goto cleanup;
}
hash_len = _gnutls_hash_get_algo_len(hash_to_entry(digest));
if (hash_len != rdn_hash.size) {
ret = gnutls_assert_val(GNUTLS_E_OCSP_RESPONSE_ERROR);
goto cleanup;
}
cserial.size = rserial.size;
cserial.data = gnutls_malloc(cserial.size);
if (cserial.data == NULL) {
ret = gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
goto cleanup;
}
t = cserial.size;
ret = gnutls_x509_crt_get_serial(crt, cserial.data, &t);
if (ret < 0) {
gnutls_assert();
goto cleanup;
}
if (rserial.size != cserial.size
|| memcmp(cserial.data, rserial.data, rserial.size) != 0) {
ret = GNUTLS_E_OCSP_RESPONSE_ERROR;
gnutls_assert();
goto cleanup;
}
ret = gnutls_x509_crt_get_raw_issuer_dn(crt, &dn);
if (ret < 0) {
gnutls_assert();
goto cleanup;
}
ret = _gnutls_hash_fast(digest, dn.data, dn.size, cdn_hash);
if (ret < 0) {
gnutls_assert();
goto cleanup;
}
if (memcmp(cdn_hash, rdn_hash.data, hash_len) != 0) {
ret = GNUTLS_E_OCSP_RESPONSE_ERROR;
gnutls_assert();
goto cleanup;
}
ret = 0;
cleanup:
gnutls_free(rdn_hash.data);
gnutls_free(rserial.data);
gnutls_free(cserial.data);
gnutls_free(dn.data);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'ocsp: corrected the comparison of the serial size in OCSP response
Previously the OCSP certificate check wouldn't verify the serial length
and could succeed in cases it shouldn't.
Reported by Stefan Buehler.'</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_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,
opj_cp_t *p_cp,
OPJ_UINT32 p_tile_no)
{
/* loop */
OPJ_UINT32 pino;
OPJ_UINT32 compno, resno;
/* to store w, h, dx and dy fro all components and resolutions */
OPJ_UINT32 * l_tmp_data;
OPJ_UINT32 ** l_tmp_ptr;
/* encoding prameters to set */
OPJ_UINT32 l_max_res;
OPJ_UINT32 l_max_prec;
OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1;
OPJ_UINT32 l_dx_min,l_dy_min;
OPJ_UINT32 l_bound;
OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ;
OPJ_UINT32 l_data_stride;
/* pointers */
opj_pi_iterator_t *l_pi = 00;
opj_tcp_t *l_tcp = 00;
const opj_tccp_t *l_tccp = 00;
opj_pi_comp_t *l_current_comp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_pi_iterator_t * l_current_pi = 00;
OPJ_UINT32 * l_encoding_value_ptr = 00;
/* preconditions in debug */
assert(p_cp != 00);
assert(p_image != 00);
assert(p_tile_no < p_cp->tw * p_cp->th);
/* initializations */
l_tcp = &p_cp->tcps[p_tile_no];
l_bound = l_tcp->numpocs+1;
l_data_stride = 4 * OPJ_J2K_MAXRLVLS;
l_tmp_data = (OPJ_UINT32*)opj_malloc(
l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32));
if
(! l_tmp_data)
{
return 00;
}
l_tmp_ptr = (OPJ_UINT32**)opj_malloc(
p_image->numcomps * sizeof(OPJ_UINT32 *));
if
(! l_tmp_ptr)
{
opj_free(l_tmp_data);
return 00;
}
/* memory allocation for pi */
l_pi = opj_pi_create(p_image, p_cp, p_tile_no);
if (!l_pi) {
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
return 00;
}
l_encoding_value_ptr = l_tmp_data;
/* update pointer array */
for
(compno = 0; compno < p_image->numcomps; ++compno)
{
l_tmp_ptr[compno] = l_encoding_value_ptr;
l_encoding_value_ptr += l_data_stride;
}
/* get encoding parameters */
opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr);
/* step calculations */
l_step_p = 1;
l_step_c = l_max_prec * l_step_p;
l_step_r = p_image->numcomps * l_step_c;
l_step_l = l_max_res * l_step_r;
/* set values for first packet iterator */
l_current_pi = l_pi;
/* memory allocation for include */
l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));
if
(!l_current_pi->include)
{
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
opj_pi_destroy(l_pi, l_bound);
return 00;
}
/* special treatment for the first packet iterator */
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_img_comp->dx;*/
/*l_current_pi->dy = l_img_comp->dy;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
++l_current_pi;
for (pino = 1 ; pino<l_bound ; ++pino )
{
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_dx_min;*/
/*l_current_pi->dy = l_dy_min;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
/* special treatment*/
l_current_pi->include = (l_current_pi-1)->include;
++l_current_pi;
}
opj_free(l_tmp_data);
l_tmp_data = 00;
opj_free(l_tmp_ptr);
l_tmp_ptr = 00;
if
(l_tcp->POC)
{
opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res);
}
else
{
opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res);
}
return l_pi;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190', 'CWE-125', 'CWE-787'], 'message': 'Fix an integer overflow issue (#809)
Prevent an integer overflow issue in function opj_pi_create_decode of
pi.c.'</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 OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block, opj_event_mgr_t* manager)
{
OPJ_UINT32 (*l_gain_ptr)(OPJ_UINT32) = 00;
OPJ_UINT32 compno, resno, bandno, precno, cblkno;
opj_tcp_t * l_tcp = 00;
opj_cp_t * l_cp = 00;
opj_tcd_tile_t * l_tile = 00;
opj_tccp_t *l_tccp = 00;
opj_tcd_tilecomp_t *l_tilec = 00;
opj_image_comp_t * l_image_comp = 00;
opj_tcd_resolution_t *l_res = 00;
opj_tcd_band_t *l_band = 00;
opj_stepsize_t * l_step_size = 00;
opj_tcd_precinct_t *l_current_precinct = 00;
opj_image_t *l_image = 00;
OPJ_UINT32 p,q;
OPJ_UINT32 l_level_no;
OPJ_UINT32 l_pdx, l_pdy;
OPJ_UINT32 l_gain;
OPJ_INT32 l_x0b, l_y0b;
OPJ_UINT32 l_tx0, l_ty0;
/* extent of precincts , top left, bottom right**/
OPJ_INT32 l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end, l_br_prc_y_end;
/* number of precinct for a resolution */
OPJ_UINT32 l_nb_precincts;
/* room needed to store l_nb_precinct precinct for a resolution */
OPJ_UINT32 l_nb_precinct_size;
/* number of code blocks for a precinct*/
OPJ_UINT32 l_nb_code_blocks;
/* room needed to store l_nb_code_blocks code blocks for a precinct*/
OPJ_UINT32 l_nb_code_blocks_size;
/* size of data for a tile */
OPJ_UINT32 l_data_size;
l_cp = p_tcd->cp;
l_tcp = &(l_cp->tcps[p_tile_no]);
l_tile = p_tcd->tcd_image->tiles;
l_tccp = l_tcp->tccps;
l_tilec = l_tile->comps;
l_image = p_tcd->image;
l_image_comp = p_tcd->image->comps;
p = p_tile_no % l_cp->tw; /* tile coordinates */
q = p_tile_no / l_cp->tw;
/*fprintf(stderr, "Tile coordinate = %d,%d\n", p, q);*/
/* 4 borders of the tile rescale on the image if necessary */
l_tx0 = l_cp->tx0 + p * l_cp->tdx; /* can't be greater than l_image->x1 so won't overflow */
l_tile->x0 = (OPJ_INT32)opj_uint_max(l_tx0, l_image->x0);
l_tile->x1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, l_cp->tdx), l_image->x1);
l_ty0 = l_cp->ty0 + q * l_cp->tdy; /* can't be greater than l_image->y1 so won't overflow */
l_tile->y0 = (OPJ_INT32)opj_uint_max(l_ty0, l_image->y0);
l_tile->y1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, l_cp->tdy), l_image->y1);
/* testcase 1888.pdf.asan.35.988 */
if (l_tccp->numresolutions == 0) {
opj_event_msg(manager, EVT_ERROR, "tiles require at least one resolution\n");
return OPJ_FALSE;
}
/*fprintf(stderr, "Tile border = %d,%d,%d,%d\n", l_tile->x0, l_tile->y0,l_tile->x1,l_tile->y1);*/
/*tile->numcomps = image->numcomps; */
for (compno = 0; compno < l_tile->numcomps; ++compno) {
/*fprintf(stderr, "compno = %d/%d\n", compno, l_tile->numcomps);*/
l_image_comp->resno_decoded = 0;
/* border of each l_tile component (global) */
l_tilec->x0 = opj_int_ceildiv(l_tile->x0, (OPJ_INT32)l_image_comp->dx);
l_tilec->y0 = opj_int_ceildiv(l_tile->y0, (OPJ_INT32)l_image_comp->dy);
l_tilec->x1 = opj_int_ceildiv(l_tile->x1, (OPJ_INT32)l_image_comp->dx);
l_tilec->y1 = opj_int_ceildiv(l_tile->y1, (OPJ_INT32)l_image_comp->dy);
/*fprintf(stderr, "\tTile compo border = %d,%d,%d,%d\n", l_tilec->x0, l_tilec->y0,l_tilec->x1,l_tilec->y1);*/
/* compute l_data_size with overflow check */
l_data_size = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0);
/* issue 733, l_data_size == 0U, probably something wrong should be checked before getting here */
if ((l_data_size > 0U) && ((((OPJ_UINT32)-1) / l_data_size) < (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0))) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_data_size = l_data_size * (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0);
if ((((OPJ_UINT32)-1) / (OPJ_UINT32)sizeof(OPJ_UINT32)) < l_data_size) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_data_size = l_data_size * (OPJ_UINT32)sizeof(OPJ_UINT32);
l_tilec->numresolutions = l_tccp->numresolutions;
if (l_tccp->numresolutions < l_cp->m_specific_param.m_dec.m_reduce) {
l_tilec->minimum_num_resolutions = 1;
}
else {
l_tilec->minimum_num_resolutions = l_tccp->numresolutions - l_cp->m_specific_param.m_dec.m_reduce;
}
l_tilec->data_size_needed = l_data_size;
if (p_tcd->m_is_decoder && !opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_data_size = l_tilec->numresolutions * (OPJ_UINT32)sizeof(opj_tcd_resolution_t);
if (l_tilec->resolutions == 00) {
l_tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(l_data_size);
if (! l_tilec->resolutions ) {
return OPJ_FALSE;
}
/*fprintf(stderr, "\tAllocate resolutions of tilec (opj_tcd_resolution_t): %d\n",l_data_size);*/
l_tilec->resolutions_size = l_data_size;
memset(l_tilec->resolutions,0,l_data_size);
}
else if (l_data_size > l_tilec->resolutions_size) {
opj_tcd_resolution_t* new_resolutions = (opj_tcd_resolution_t *) opj_realloc(l_tilec->resolutions, l_data_size);
if (! new_resolutions) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile resolutions\n");
opj_free(l_tilec->resolutions);
l_tilec->resolutions = NULL;
l_tilec->resolutions_size = 0;
return OPJ_FALSE;
}
l_tilec->resolutions = new_resolutions;
/*fprintf(stderr, "\tReallocate data of tilec (int): from %d to %d x OPJ_UINT32\n", l_tilec->resolutions_size, l_data_size);*/
memset(((OPJ_BYTE*) l_tilec->resolutions)+l_tilec->resolutions_size,0,l_data_size - l_tilec->resolutions_size);
l_tilec->resolutions_size = l_data_size;
}
l_level_no = l_tilec->numresolutions;
l_res = l_tilec->resolutions;
l_step_size = l_tccp->stepsizes;
if (l_tccp->qmfbid == 0) {
l_gain_ptr = &opj_dwt_getgain_real;
}
else {
l_gain_ptr = &opj_dwt_getgain;
}
/*fprintf(stderr, "\tlevel_no=%d\n",l_level_no);*/
for (resno = 0; resno < l_tilec->numresolutions; ++resno) {
/*fprintf(stderr, "\t\tresno = %d/%d\n", resno, l_tilec->numresolutions);*/
OPJ_INT32 tlcbgxstart, tlcbgystart /*, brcbgxend, brcbgyend*/;
OPJ_UINT32 cbgwidthexpn, cbgheightexpn;
OPJ_UINT32 cblkwidthexpn, cblkheightexpn;
--l_level_no;
/* border for each resolution level (global) */
l_res->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
l_res->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
l_res->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
l_res->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
/*fprintf(stderr, "\t\t\tres_x0= %d, res_y0 =%d, res_x1=%d, res_y1=%d\n", l_res->x0, l_res->y0, l_res->x1, l_res->y1);*/
/* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */
l_pdx = l_tccp->prcw[resno];
l_pdy = l_tccp->prch[resno];
/*fprintf(stderr, "\t\t\tpdx=%d, pdy=%d\n", l_pdx, l_pdy);*/
/* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */
l_tl_prc_x_start = opj_int_floordivpow2(l_res->x0, (OPJ_INT32)l_pdx) << l_pdx;
l_tl_prc_y_start = opj_int_floordivpow2(l_res->y0, (OPJ_INT32)l_pdy) << l_pdy;
l_br_prc_x_end = opj_int_ceildivpow2(l_res->x1, (OPJ_INT32)l_pdx) << l_pdx;
l_br_prc_y_end = opj_int_ceildivpow2(l_res->y1, (OPJ_INT32)l_pdy) << l_pdy;
/*fprintf(stderr, "\t\t\tprc_x_start=%d, prc_y_start=%d, br_prc_x_end=%d, br_prc_y_end=%d \n", l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end ,l_br_prc_y_end );*/
l_res->pw = (l_res->x0 == l_res->x1) ? 0U : (OPJ_UINT32)((l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx);
l_res->ph = (l_res->y0 == l_res->y1) ? 0U : (OPJ_UINT32)((l_br_prc_y_end - l_tl_prc_y_start) >> l_pdy);
/*fprintf(stderr, "\t\t\tres_pw=%d, res_ph=%d\n", l_res->pw, l_res->ph );*/
if ((l_res->pw != 0U) && ((((OPJ_UINT32)-1) / l_res->pw) < l_res->ph)) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_nb_precincts = l_res->pw * l_res->ph;
if ((((OPJ_UINT32)-1) / (OPJ_UINT32)sizeof(opj_tcd_precinct_t)) < l_nb_precincts) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_nb_precinct_size = l_nb_precincts * (OPJ_UINT32)sizeof(opj_tcd_precinct_t);
if (resno == 0) {
tlcbgxstart = l_tl_prc_x_start;
tlcbgystart = l_tl_prc_y_start;
/*brcbgxend = l_br_prc_x_end;*/
/* brcbgyend = l_br_prc_y_end;*/
cbgwidthexpn = l_pdx;
cbgheightexpn = l_pdy;
l_res->numbands = 1;
}
else {
tlcbgxstart = opj_int_ceildivpow2(l_tl_prc_x_start, 1);
tlcbgystart = opj_int_ceildivpow2(l_tl_prc_y_start, 1);
/*brcbgxend = opj_int_ceildivpow2(l_br_prc_x_end, 1);*/
/*brcbgyend = opj_int_ceildivpow2(l_br_prc_y_end, 1);*/
cbgwidthexpn = l_pdx - 1;
cbgheightexpn = l_pdy - 1;
l_res->numbands = 3;
}
cblkwidthexpn = opj_uint_min(l_tccp->cblkw, cbgwidthexpn);
cblkheightexpn = opj_uint_min(l_tccp->cblkh, cbgheightexpn);
l_band = l_res->bands;
for (bandno = 0; bandno < l_res->numbands; ++bandno) {
OPJ_INT32 numbps;
/*fprintf(stderr, "\t\t\tband_no=%d/%d\n", bandno, l_res->numbands );*/
if (resno == 0) {
l_band->bandno = 0 ;
l_band->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
l_band->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
l_band->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
l_band->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
}
else {
l_band->bandno = bandno + 1;
/* x0b = 1 if bandno = 1 or 3 */
l_x0b = l_band->bandno&1;
/* y0b = 1 if bandno = 2 or 3 */
l_y0b = (OPJ_INT32)((l_band->bandno)>>1);
/* l_band border (global) */
l_band->x0 = opj_int64_ceildivpow2(l_tilec->x0 - ((OPJ_INT64)l_x0b << l_level_no), (OPJ_INT32)(l_level_no + 1));
l_band->y0 = opj_int64_ceildivpow2(l_tilec->y0 - ((OPJ_INT64)l_y0b << l_level_no), (OPJ_INT32)(l_level_no + 1));
l_band->x1 = opj_int64_ceildivpow2(l_tilec->x1 - ((OPJ_INT64)l_x0b << l_level_no), (OPJ_INT32)(l_level_no + 1));
l_band->y1 = opj_int64_ceildivpow2(l_tilec->y1 - ((OPJ_INT64)l_y0b << l_level_no), (OPJ_INT32)(l_level_no + 1));
}
/** avoid an if with storing function pointer */
l_gain = (*l_gain_ptr) (l_band->bandno);
numbps = (OPJ_INT32)(l_image_comp->prec + l_gain);
l_band->stepsize = (OPJ_FLOAT32)(((1.0 + l_step_size->mant / 2048.0) * pow(2.0, (OPJ_INT32) (numbps - l_step_size->expn)))) * fraction;
l_band->numbps = l_step_size->expn + (OPJ_INT32)l_tccp->numgbits - 1; /* WHY -1 ? */
if (!l_band->precincts && (l_nb_precincts > 0U)) {
l_band->precincts = (opj_tcd_precinct_t *) opj_malloc( /*3 * */ l_nb_precinct_size);
if (! l_band->precincts) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory to handle band precints\n");
return OPJ_FALSE;
}
/*fprintf(stderr, "\t\t\t\tAllocate precincts of a band (opj_tcd_precinct_t): %d\n",l_nb_precinct_size); */
memset(l_band->precincts,0,l_nb_precinct_size);
l_band->precincts_data_size = l_nb_precinct_size;
}
else if (l_band->precincts_data_size < l_nb_precinct_size) {
opj_tcd_precinct_t * new_precincts = (opj_tcd_precinct_t *) opj_realloc(l_band->precincts,/*3 * */ l_nb_precinct_size);
if (! new_precincts) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory to handle band precints\n");
opj_free(l_band->precincts);
l_band->precincts = NULL;
l_band->precincts_data_size = 0;
return OPJ_FALSE;
}
l_band->precincts = new_precincts;
/*fprintf(stderr, "\t\t\t\tReallocate precincts of a band (opj_tcd_precinct_t): from %d to %d\n",l_band->precincts_data_size, l_nb_precinct_size);*/
memset(((OPJ_BYTE *) l_band->precincts) + l_band->precincts_data_size,0,l_nb_precinct_size - l_band->precincts_data_size);
l_band->precincts_data_size = l_nb_precinct_size;
}
l_current_precinct = l_band->precincts;
for (precno = 0; precno < l_nb_precincts; ++precno) {
OPJ_INT32 tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend;
OPJ_INT32 cbgxstart = tlcbgxstart + (OPJ_INT32)(precno % l_res->pw) * (1 << cbgwidthexpn);
OPJ_INT32 cbgystart = tlcbgystart + (OPJ_INT32)(precno / l_res->pw) * (1 << cbgheightexpn);
OPJ_INT32 cbgxend = cbgxstart + (1 << cbgwidthexpn);
OPJ_INT32 cbgyend = cbgystart + (1 << cbgheightexpn);
/*fprintf(stderr, "\t precno=%d; bandno=%d, resno=%d; compno=%d\n", precno, bandno , resno, compno);*/
/*fprintf(stderr, "\t tlcbgxstart(=%d) + (precno(=%d) percent res->pw(=%d)) * (1 << cbgwidthexpn(=%d)) \n",tlcbgxstart,precno,l_res->pw,cbgwidthexpn);*/
/* precinct size (global) */
/*fprintf(stderr, "\t cbgxstart=%d, l_band->x0 = %d \n",cbgxstart, l_band->x0);*/
l_current_precinct->x0 = opj_int_max(cbgxstart, l_band->x0);
l_current_precinct->y0 = opj_int_max(cbgystart, l_band->y0);
l_current_precinct->x1 = opj_int_min(cbgxend, l_band->x1);
l_current_precinct->y1 = opj_int_min(cbgyend, l_band->y1);
/*fprintf(stderr, "\t prc_x0=%d; prc_y0=%d, prc_x1=%d; prc_y1=%d\n",l_current_precinct->x0, l_current_precinct->y0 ,l_current_precinct->x1, l_current_precinct->y1);*/
tlcblkxstart = opj_int_floordivpow2(l_current_precinct->x0, (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
/*fprintf(stderr, "\t tlcblkxstart =%d\n",tlcblkxstart );*/
tlcblkystart = opj_int_floordivpow2(l_current_precinct->y0, (OPJ_INT32)cblkheightexpn) << cblkheightexpn;
/*fprintf(stderr, "\t tlcblkystart =%d\n",tlcblkystart );*/
brcblkxend = opj_int_ceildivpow2(l_current_precinct->x1, (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
/*fprintf(stderr, "\t brcblkxend =%d\n",brcblkxend );*/
brcblkyend = opj_int_ceildivpow2(l_current_precinct->y1, (OPJ_INT32)cblkheightexpn) << cblkheightexpn;
/*fprintf(stderr, "\t brcblkyend =%d\n",brcblkyend );*/
l_current_precinct->cw = (OPJ_UINT32)((brcblkxend - tlcblkxstart) >> cblkwidthexpn);
l_current_precinct->ch = (OPJ_UINT32)((brcblkyend - tlcblkystart) >> cblkheightexpn);
l_nb_code_blocks = l_current_precinct->cw * l_current_precinct->ch;
/*fprintf(stderr, "\t\t\t\t precinct_cw = %d x recinct_ch = %d\n",l_current_precinct->cw, l_current_precinct->ch); */
l_nb_code_blocks_size = l_nb_code_blocks * (OPJ_UINT32)sizeof_block;
if (!l_current_precinct->cblks.blocks && (l_nb_code_blocks > 0U)) {
l_current_precinct->cblks.blocks = opj_malloc(l_nb_code_blocks_size);
if (! l_current_precinct->cblks.blocks ) {
return OPJ_FALSE;
}
/*fprintf(stderr, "\t\t\t\tAllocate cblks of a precinct (opj_tcd_cblk_dec_t): %d\n",l_nb_code_blocks_size);*/
memset(l_current_precinct->cblks.blocks,0,l_nb_code_blocks_size);
l_current_precinct->block_size = l_nb_code_blocks_size;
}
else if (l_nb_code_blocks_size > l_current_precinct->block_size) {
void *new_blocks = opj_realloc(l_current_precinct->cblks.blocks, l_nb_code_blocks_size);
if (! new_blocks) {
opj_free(l_current_precinct->cblks.blocks);
l_current_precinct->cblks.blocks = NULL;
l_current_precinct->block_size = 0;
opj_event_msg(manager, EVT_ERROR, "Not enough memory for current precinct codeblock element\n");
return OPJ_FALSE;
}
l_current_precinct->cblks.blocks = new_blocks;
/*fprintf(stderr, "\t\t\t\tReallocate cblks of a precinct (opj_tcd_cblk_dec_t): from %d to %d\n",l_current_precinct->block_size, l_nb_code_blocks_size); */
memset(((OPJ_BYTE *) l_current_precinct->cblks.blocks) + l_current_precinct->block_size
,0
,l_nb_code_blocks_size - l_current_precinct->block_size);
l_current_precinct->block_size = l_nb_code_blocks_size;
}
if (! l_current_precinct->incltree) {
l_current_precinct->incltree = opj_tgt_create(l_current_precinct->cw, l_current_precinct->ch, manager);
}
else{
l_current_precinct->incltree = opj_tgt_init(l_current_precinct->incltree, l_current_precinct->cw, l_current_precinct->ch, manager);
}
if (! l_current_precinct->incltree) {
opj_event_msg(manager, EVT_WARNING, "No incltree created.\n");
/*return OPJ_FALSE;*/
}
if (! l_current_precinct->imsbtree) {
l_current_precinct->imsbtree = opj_tgt_create(l_current_precinct->cw, l_current_precinct->ch, manager);
}
else {
l_current_precinct->imsbtree = opj_tgt_init(l_current_precinct->imsbtree, l_current_precinct->cw, l_current_precinct->ch, manager);
}
if (! l_current_precinct->imsbtree) {
opj_event_msg(manager, EVT_WARNING, "No imsbtree created.\n");
/*return OPJ_FALSE;*/
}
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
OPJ_INT32 cblkxstart = tlcblkxstart + (OPJ_INT32)(cblkno % l_current_precinct->cw) * (1 << cblkwidthexpn);
OPJ_INT32 cblkystart = tlcblkystart + (OPJ_INT32)(cblkno / l_current_precinct->cw) * (1 << cblkheightexpn);
OPJ_INT32 cblkxend = cblkxstart + (1 << cblkwidthexpn);
OPJ_INT32 cblkyend = cblkystart + (1 << cblkheightexpn);
if (isEncoder) {
opj_tcd_cblk_enc_t* l_code_block = l_current_precinct->cblks.enc + cblkno;
if (! opj_tcd_code_block_enc_allocate(l_code_block)) {
return OPJ_FALSE;
}
/* code-block size (global) */
l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
if (! opj_tcd_code_block_enc_allocate_data(l_code_block)) {
return OPJ_FALSE;
}
} else {
opj_tcd_cblk_dec_t* l_code_block = l_current_precinct->cblks.dec + cblkno;
if (! opj_tcd_code_block_dec_allocate(l_code_block)) {
return OPJ_FALSE;
}
/* code-block size (global) */
l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
}
}
++l_current_precinct;
} /* precno */
++l_band;
++l_step_size;
} /* bandno */
++l_res;
} /* resno */
++l_tccp;
++l_tilec;
++l_image_comp;
} /* compno */
return OPJ_TRUE;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-310'], 'message': 'Add sanity check for tile coordinates (#823)
Coordinates are casted from OPJ_UINT32 to OPJ_INT32
Add sanity check for negative values and upper bound becoming lower
than lower bound.
See also
https://pdfium.googlesource.com/pdfium/+/b6befb2ed2485a3805cddea86dc7574510178ea9'</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: local int decode(struct state *s, struct huffman *h)
{
int len; /* current number of bits in code */
int code; /* len bits being decoded */
int first; /* first code of length len */
int count; /* number of codes of length len */
int index; /* index of first code of length len in symbol table */
code = first = index = 0;
for (len = 1; len <= MAXBITS; len++) {
code |= bits(s, 1); /* get next bit */
count = h->count[len];
if (code < first + count) /* if length len, return symbol */
return h->symbol[index + (code - first)];
index += count; /* else update for next length */
first += count;
first <<= 1;
code <<= 1;
}
return -9; /* ran out of codes */
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'update puff.c for gzip inflation (#1022)
update puff.c for gzip inflation'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: int main(int argc, char **argv)
{
int ret;
unsigned char *source;
boost::uint32_t len, sourcelen, destlen;
if (argc < 2) return 2;
source = yank(argv[1], &len);
if (source == NULL) return 2;
sourcelen = len;
ret = puff(NIL, &destlen, source, &sourcelen);
if (ret)
printf("puff() failed with return code %d\n", ret);
else {
printf("puff() succeeded uncompressing %lu bytes\n", destlen);
if (sourcelen < len) printf("%lu compressed bytes unused\n",
len - sourcelen);
}
free(source);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'update puff.c for gzip inflation (#1022)
update puff.c for gzip inflation'</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: local int decode(struct state *s, struct huffman *h)
{
int len; /* current number of bits in code */
int code; /* len bits being decoded */
int first; /* first code of length len */
int count; /* number of codes of length len */
int index; /* index of first code of length len in symbol table */
int bitbuf; /* bits from stream */
int left; /* bits left in next or left to process */
boost::int16_t *next; /* next number of codes */
bitbuf = s->bitbuf;
left = s->bitcnt;
code = first = index = 0;
len = 1;
next = h->count + 1;
while (1) {
while (left--) {
code |= bitbuf & 1;
bitbuf >>= 1;
count = *next++;
if (code < first + count) { /* if length len, return symbol */
s->bitbuf = bitbuf;
s->bitcnt = (s->bitcnt - len) & 7;
return h->symbol[index + (code - first)];
}
index += count; /* else update for next length */
first += count;
first <<= 1;
code <<= 1;
len++;
}
left = (MAXBITS+1) - len;
if (left == 0) break;
if (s->incnt == s->inlen) longjmp(s->env, 1); /* out of input */
bitbuf = s->in[s->incnt++];
if (left > 8) left = 8;
}
return -9; /* ran out of codes */
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'update puff.c for gzip inflation (#1022)
update puff.c for gzip inflation'</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 puff(unsigned char *dest, /* pointer to destination pointer */
boost::uint32_t *destlen, /* amount of output space */
const unsigned char *source, /* pointer to source data pointer */
boost::uint32_t *sourcelen) /* amount of input available */
{
struct state s; /* input/output state */
int last, type; /* block information */
int err; /* return value */
/* initialize output state */
s.out = dest;
s.outlen = *destlen; /* ignored if dest is NIL */
s.outcnt = 0;
/* initialize input state */
s.in = source;
s.inlen = *sourcelen;
s.incnt = 0;
s.bitbuf = 0;
s.bitcnt = 0;
/* return if bits() or decode() tries to read past available input */
if (setjmp(s.env) != 0) /* if came back here via longjmp() */
err = 2; /* then skip do-loop, return error */
else {
/* process blocks until last block or error */
do {
last = bits(&s, 1); /* one if last block */
type = bits(&s, 2); /* block type 0..3 */
err = type == 0 ? stored(&s) :
(type == 1 ? fixed(&s) :
(type == 2 ? dynamic(&s) :
-1)); /* type == 3, invalid */
if (err != 0) break; /* return with error */
} while (!last);
}
/* update the lengths and return */
if (err <= 0) {
*destlen = s.outcnt;
*sourcelen = s.incnt;
}
return err;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'update puff.c for gzip inflation (#1022)
update puff.c for gzip inflation'</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: local int stored(struct state *s)
{
unsigned len; /* length of stored block */
/* discard leftover bits from current byte (assumes s->bitcnt < 8) */
s->bitbuf = 0;
s->bitcnt = 0;
/* get length and check against its one's complement */
if (s->incnt + 4 > s->inlen) return 2; /* not enough input */
len = s->in[s->incnt++];
len |= s->in[s->incnt++] << 8;
if (s->in[s->incnt++] != (~len & 0xff) ||
s->in[s->incnt++] != ((~len >> 8) & 0xff))
return -2; /* didn't match complement! */
/* copy len bytes from in to out */
if (s->incnt + len > s->inlen) return 2; /* not enough input */
if (s->out != NIL) {
if (s->outcnt + len > s->outlen)
return 1; /* not enough output space */
while (len--)
s->out[s->outcnt++] = s->in[s->incnt++];
}
else { /* just scanning */
s->outcnt += len;
s->incnt += len;
}
/* done with a valid stored block */
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'update puff.c for gzip inflation (#1022)
update puff.c for gzip inflation'</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: TORRENT_TEST(gzip)
{
std::vector<char> zipped;
error_code ec;
load_file(combine_path("..", "zeroes.gz"), zipped, ec, 1000000);
if (ec) fprintf(stderr, "failed to open file: (%d) %s\n", ec.value()
, ec.message().c_str());
TEST_CHECK(!ec);
std::vector<char> inflated;
inflate_gzip(&zipped[0], zipped.size(), inflated, 1000000, ec);
if (ec) {
fprintf(stderr, "failed to unzip: %s\n", ec.message().c_str());
}
TEST_CHECK(!ec);
TEST_CHECK(inflated.size() > 0);
for (int i = 0; i < int(inflated.size()); ++i)
TEST_EQUAL(inflated[i], 0);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'update puff.c for gzip inflation (#1022)
update puff.c for gzip inflation'</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: local int codes(struct state *s,
struct huffman *lencode,
struct huffman *distcode)
{
int symbol; /* decoded symbol */
int len; /* length for copy */
unsigned dist; /* distance for copy */
static const boost::int16_t lens[29] = { /* Size base for length codes 257..285 */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
static const boost::int16_t lext[29] = { /* Extra bits for length codes 257..285 */
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
static const boost::int16_t dists[30] = { /* Offset base for distance codes 0..29 */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577};
static const boost::int16_t dext[30] = { /* Extra bits for distance codes 0..29 */
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
12, 12, 13, 13};
/* decode literals and length/distance pairs */
do {
symbol = decode(s, lencode);
if (symbol < 0) return symbol; /* invalid symbol */
if (symbol < 256) { /* literal: symbol is the byte */
/* write out the literal */
if (s->out != NIL) {
if (s->outcnt == s->outlen) return 1;
s->out[s->outcnt] = symbol;
}
s->outcnt++;
}
else if (symbol > 256) { /* length */
/* get and compute length */
symbol -= 257;
if (symbol >= 29) return -9; /* invalid fixed code */
len = lens[symbol] + bits(s, lext[symbol]);
/* get and check distance */
symbol = decode(s, distcode);
if (symbol < 0) return symbol; /* invalid symbol */
dist = dists[symbol] + bits(s, dext[symbol]);
if (dist > s->outcnt)
return -10; /* distance too far back */
/* copy length bytes from distance bytes back */
if (s->out != NIL) {
if (s->outcnt + len > s->outlen) return 1;
while (len--) {
s->out[s->outcnt] = s->out[s->outcnt - dist];
s->outcnt++;
}
}
else
s->outcnt += len;
}
} while (symbol != 256); /* end of block symbol */
/* done with a valid fixed or dynamic block */
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'update puff.c for gzip inflation (#1022)
update puff.c for gzip inflation'</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 PacketReader::getLabelFromContent(const vector<uint8_t>& content, uint16_t& frompos, string& ret, int recurs)
{
if(recurs > 100) // the forward reference-check below should make this test 100% obsolete
throw MOADNSException("Loop");
int pos = frompos;
// it is tempting to call reserve on ret, but it turns out it creates a malloc/free storm in the loop
for(;;) {
unsigned char labellen=content.at(frompos++);
if(!labellen) {
if(ret.empty())
ret.append(1,'.');
break;
}
else if((labellen & 0xc0) == 0xc0) {
uint16_t offset=256*(labellen & ~0xc0) + (unsigned int)content.at(frompos++) - sizeof(dnsheader);
// cout<<"This is an offset, need to go to: "<<offset<<endl;
if(offset >= pos)
throw MOADNSException("forward reference during label decompression");
return getLabelFromContent(content, offset, ret, ++recurs);
}
else if(labellen > 63)
throw MOADNSException("Overly long label during label decompression ("+lexical_cast<string>((unsigned int)labellen)+")");
else {
// XXX FIXME THIS MIGHT BE VERY SLOW!
for(string::size_type n = 0 ; n < labellen; ++n, frompos++) {
if(content.at(frompos)=='.' || content.at(frompos)=='\\') {
ret.append(1, '\\');
ret.append(1, content[frompos]);
}
else if(content.at(frompos)==' ') {
ret+="\\032";
}
else
ret.append(1, content[frompos]);
}
ret.append(1,'.');
}
if (ret.length() > 1024)
throw MOADNSException("Total name too long");
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'Reject qname's wirelength > 255, `chopOff()` handle dot inside labels'</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: string PacketReader::getLabel(unsigned int recurs)
{
string ret;
ret.reserve(40);
getLabelFromContent(d_content, d_pos, ret, recurs++);
return ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-399'], 'message': 'Reject qname's wirelength > 255, `chopOff()` handle dot inside labels'</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 MYSQL_LOG::open(
#ifdef HAVE_PSI_INTERFACE
PSI_file_key log_file_key,
#endif
const char *log_name, enum_log_type log_type_arg,
const char *new_name, enum cache_type io_cache_type_arg)
{
char buff[FN_REFLEN];
MY_STAT f_stat;
File file= -1;
int open_flags= O_CREAT | O_BINARY;
DBUG_ENTER("MYSQL_LOG::open");
DBUG_PRINT("enter", ("log_type: %d", (int) log_type_arg));
write_error= 0;
if (!(name= my_strdup(log_name, MYF(MY_WME))))
{
name= (char *)log_name; // for the error message
goto err;
}
if (init_and_set_log_file_name(name, new_name,
log_type_arg, io_cache_type_arg))
goto err;
/* File is regular writable file */
if (my_stat(log_file_name, &f_stat, MYF(0)) && !MY_S_ISREG(f_stat.st_mode))
goto err;
if (io_cache_type == SEQ_READ_APPEND)
open_flags |= O_RDWR | O_APPEND;
else
open_flags |= O_WRONLY | (log_type == LOG_BIN ? 0 : O_APPEND);
db[0]= 0;
#ifdef HAVE_PSI_INTERFACE
/* Keep the key for reopen */
m_log_file_key= log_file_key;
#endif
if ((file= mysql_file_open(log_file_key,
log_file_name, open_flags,
MYF(MY_WME | ME_WAITTANG))) < 0 ||
init_io_cache(&log_file, file, IO_SIZE, io_cache_type,
mysql_file_tell(file, MYF(MY_WME)), 0,
MYF(MY_WME | MY_NABP |
((log_type == LOG_BIN) ? MY_WAIT_IF_FULL : 0))))
goto err;
if (log_type == LOG_NORMAL)
{
char *end;
int len=my_snprintf(buff, sizeof(buff), "%s, Version: %s (%s). "
#ifdef EMBEDDED_LIBRARY
"embedded library\n",
my_progname, server_version, MYSQL_COMPILATION_COMMENT
#elif _WIN32
"started with:\nTCP Port: %d, Named Pipe: %s\n",
my_progname, server_version, MYSQL_COMPILATION_COMMENT,
mysqld_port, mysqld_unix_port
#else
"started with:\nTcp port: %d Unix socket: %s\n",
my_progname, server_version, MYSQL_COMPILATION_COMMENT,
mysqld_port, mysqld_unix_port
#endif
);
end= strnmov(buff + len, "Time Id Command Argument\n",
sizeof(buff) - len);
if (my_b_write(&log_file, (uchar*) buff, (uint) (end-buff)) ||
flush_io_cache(&log_file))
goto err;
}
log_state= LOG_OPENED;
DBUG_RETURN(0);
err:
sql_print_error("Could not use %s for logging (error %d). \
Turning logging off for the whole duration of the MySQL server process. \
To turn it on again: fix the cause, \
shutdown the MySQL server and restart it.", name, errno);
if (file >= 0)
mysql_file_close(file, MYF(0));
end_io_cache(&log_file);
my_free(name);
name= NULL;
log_state= LOG_CLOSED;
DBUG_RETURN(1);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'Bug#24388753: PRIVILEGE ESCALATION USING MYSQLD_SAFE
[This is the 5.5/5.6 version of the bugfix].
The problem was that it was possible to write log files ending
in .ini/.cnf that later could be parsed as an options file.
This made it possible for users to specify startup options
without the permissions to do so.
This patch fixes the problem by disallowing general query log
and slow query log to be written to files ending in .ini and .cnf.'</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 fix_log(char** logname, const char* default_logname,
const char*ext, bool enabled, void (*reopen)(char*))
{
if (!*logname) // SET ... = DEFAULT
{
char buff[FN_REFLEN];
*logname= my_strdup(make_log_name(buff, default_logname, ext),
MYF(MY_FAE+MY_WME));
if (!*logname)
return true;
}
logger.lock_exclusive();
mysql_mutex_unlock(&LOCK_global_system_variables);
if (enabled)
reopen(*logname);
logger.unlock();
mysql_mutex_lock(&LOCK_global_system_variables);
return false;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'Bug#24388753: PRIVILEGE ESCALATION USING MYSQLD_SAFE
[This is the 5.5/5.6 version of the bugfix].
The problem was that it was possible to write log files ending
in .ini/.cnf that later could be parsed as an options file.
This made it possible for users to specify startup options
without the permissions to do so.
This patch fixes the problem by disallowing general query log
and slow query log to be written to files ending in .ini and .cnf.'</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 reopen_general_log(char* name)
{
logger.get_log_file_handler()->close(0);
logger.get_log_file_handler()->open_query_log(name);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'Bug#24388753: PRIVILEGE ESCALATION USING MYSQLD_SAFE
[This is the 5.5/5.6 version of the bugfix].
The problem was that it was possible to write log files ending
in .ini/.cnf that later could be parsed as an options file.
This made it possible for users to specify startup options
without the permissions to do so.
This patch fixes the problem by disallowing general query log
and slow query log to be written to files ending in .ini and .cnf.'</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 fix_paths(void)
{
char buff[FN_REFLEN],*pos;
convert_dirname(mysql_home,mysql_home,NullS);
/* Resolve symlinks to allow 'mysql_home' to be a relative symlink */
my_realpath(mysql_home,mysql_home,MYF(0));
/* Ensure that mysql_home ends in FN_LIBCHAR */
pos=strend(mysql_home);
if (pos[-1] != FN_LIBCHAR)
{
pos[0]= FN_LIBCHAR;
pos[1]= 0;
}
convert_dirname(lc_messages_dir, lc_messages_dir, NullS);
convert_dirname(mysql_real_data_home,mysql_real_data_home,NullS);
(void) my_load_path(mysql_home,mysql_home,""); // Resolve current dir
(void) my_load_path(mysql_real_data_home,mysql_real_data_home,mysql_home);
(void) my_load_path(pidfile_name, pidfile_name_ptr, mysql_real_data_home);
convert_dirname(opt_plugin_dir, opt_plugin_dir_ptr ? opt_plugin_dir_ptr :
get_relative_path(PLUGINDIR), NullS);
(void) my_load_path(opt_plugin_dir, opt_plugin_dir, mysql_home);
opt_plugin_dir_ptr= opt_plugin_dir;
my_realpath(mysql_unpacked_real_data_home, mysql_real_data_home, MYF(0));
mysql_unpacked_real_data_home_len=
(int) strlen(mysql_unpacked_real_data_home);
if (mysql_unpacked_real_data_home[mysql_unpacked_real_data_home_len-1] == FN_LIBCHAR)
--mysql_unpacked_real_data_home_len;
char *sharedir=get_relative_path(SHAREDIR);
if (test_if_hard_path(sharedir))
strmake(buff,sharedir,sizeof(buff)-1); /* purecov: tested */
else
strxnmov(buff,sizeof(buff)-1,mysql_home,sharedir,NullS);
convert_dirname(buff,buff,NullS);
(void) my_load_path(lc_messages_dir, lc_messages_dir, buff);
/* If --character-sets-dir isn't given, use shared library dir */
if (charsets_dir)
strmake(mysql_charsets_dir, charsets_dir, sizeof(mysql_charsets_dir)-1);
else
strxnmov(mysql_charsets_dir, sizeof(mysql_charsets_dir)-1, buff,
CHARSET_DIR, NullS);
(void) my_load_path(mysql_charsets_dir, mysql_charsets_dir, buff);
convert_dirname(mysql_charsets_dir, mysql_charsets_dir, NullS);
charsets_dir=mysql_charsets_dir;
if (init_tmpdir(&mysql_tmpdir_list, opt_mysql_tmpdir))
return 1;
if (!opt_mysql_tmpdir)
opt_mysql_tmpdir= mysql_tmpdir;
#ifdef HAVE_REPLICATION
if (!slave_load_tmpdir)
slave_load_tmpdir= mysql_tmpdir;
#endif /* HAVE_REPLICATION */
/*
Convert the secure-file-priv option to system format, allowing
a quick strcmp to check if read or write is in an allowed dir
*/
if (opt_secure_file_priv)
{
if (*opt_secure_file_priv == 0)
{
my_free(opt_secure_file_priv);
opt_secure_file_priv= 0;
}
else
{
if (strlen(opt_secure_file_priv) >= FN_REFLEN)
opt_secure_file_priv[FN_REFLEN-1]= '\0';
if (my_realpath(buff, opt_secure_file_priv, 0))
{
sql_print_warning("Failed to normalize the argument for --secure-file-priv.");
return 1;
}
char *secure_file_real_path= (char *)my_malloc(FN_REFLEN, MYF(MY_FAE));
convert_dirname(secure_file_real_path, buff, NullS);
my_free(opt_secure_file_priv);
opt_secure_file_priv= secure_file_real_path;
}
}
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'Bug#24707666: DEFAULT SETTING FOR SECURE-FILE-PRIV SHOULD BE
RESTRICTED IN ALL GA RELEASES
Back port of WL#6782 to 5.5 and 5.6. This also includes
back port of Bug#20771331, Bug#20741572 and Bug#20770671.
Bug#24695274 and Bug#24679907 are also handled along with
this.'</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 arcmsr_iop_message_xfer(struct AdapterControlBlock *acb,
struct scsi_cmnd *cmd)
{
char *buffer;
unsigned short use_sg;
int retvalue = 0, transfer_len = 0;
unsigned long flags;
struct CMD_MESSAGE_FIELD *pcmdmessagefld;
uint32_t controlcode = (uint32_t)cmd->cmnd[5] << 24 |
(uint32_t)cmd->cmnd[6] << 16 |
(uint32_t)cmd->cmnd[7] << 8 |
(uint32_t)cmd->cmnd[8];
struct scatterlist *sg;
use_sg = scsi_sg_count(cmd);
sg = scsi_sglist(cmd);
buffer = kmap_atomic(sg_page(sg)) + sg->offset;
if (use_sg > 1) {
retvalue = ARCMSR_MESSAGE_FAIL;
goto message_out;
}
transfer_len += sg->length;
if (transfer_len > sizeof(struct CMD_MESSAGE_FIELD)) {
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: ARCMSR_MESSAGE_FAIL!\n", __func__);
goto message_out;
}
pcmdmessagefld = (struct CMD_MESSAGE_FIELD *)buffer;
switch (controlcode) {
case ARCMSR_MESSAGE_READ_RQBUFFER: {
unsigned char *ver_addr;
uint8_t *ptmpQbuffer;
uint32_t allxfer_len = 0;
ver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);
if (!ver_addr) {
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: memory not enough!\n", __func__);
goto message_out;
}
ptmpQbuffer = ver_addr;
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
if (acb->rqbuf_getIndex != acb->rqbuf_putIndex) {
unsigned int tail = acb->rqbuf_getIndex;
unsigned int head = acb->rqbuf_putIndex;
unsigned int cnt_to_end = CIRC_CNT_TO_END(head, tail, ARCMSR_MAX_QBUFFER);
allxfer_len = CIRC_CNT(head, tail, ARCMSR_MAX_QBUFFER);
if (allxfer_len > ARCMSR_API_DATA_BUFLEN)
allxfer_len = ARCMSR_API_DATA_BUFLEN;
if (allxfer_len <= cnt_to_end)
memcpy(ptmpQbuffer, acb->rqbuffer + tail, allxfer_len);
else {
memcpy(ptmpQbuffer, acb->rqbuffer + tail, cnt_to_end);
memcpy(ptmpQbuffer + cnt_to_end, acb->rqbuffer, allxfer_len - cnt_to_end);
}
acb->rqbuf_getIndex = (acb->rqbuf_getIndex + allxfer_len) % ARCMSR_MAX_QBUFFER;
}
memcpy(pcmdmessagefld->messagedatabuffer, ver_addr,
allxfer_len);
if (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) {
struct QBUFFER __iomem *prbuffer;
acb->acb_flags &= ~ACB_F_IOPDATA_OVERFLOW;
prbuffer = arcmsr_get_iop_rqbuffer(acb);
if (arcmsr_Read_iop_rqbuffer_data(acb, prbuffer) == 0)
acb->acb_flags |= ACB_F_IOPDATA_OVERFLOW;
}
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
kfree(ver_addr);
pcmdmessagefld->cmdmessage.Length = allxfer_len;
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_WRITE_WQBUFFER: {
unsigned char *ver_addr;
uint32_t user_len;
int32_t cnt2end;
uint8_t *pQbuffer, *ptmpuserbuffer;
ver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC);
if (!ver_addr) {
retvalue = ARCMSR_MESSAGE_FAIL;
goto message_out;
}
ptmpuserbuffer = ver_addr;
user_len = pcmdmessagefld->cmdmessage.Length;
if (user_len > ARCMSR_API_DATA_BUFLEN) {
retvalue = ARCMSR_MESSAGE_FAIL;
kfree(ver_addr);
goto message_out;
}
memcpy(ptmpuserbuffer,
pcmdmessagefld->messagedatabuffer, user_len);
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
if (acb->wqbuf_putIndex != acb->wqbuf_getIndex) {
struct SENSE_DATA *sensebuffer =
(struct SENSE_DATA *)cmd->sense_buffer;
arcmsr_write_ioctldata2iop(acb);
/* has error report sensedata */
sensebuffer->ErrorCode = SCSI_SENSE_CURRENT_ERRORS;
sensebuffer->SenseKey = ILLEGAL_REQUEST;
sensebuffer->AdditionalSenseLength = 0x0A;
sensebuffer->AdditionalSenseCode = 0x20;
sensebuffer->Valid = 1;
retvalue = ARCMSR_MESSAGE_FAIL;
} else {
pQbuffer = &acb->wqbuffer[acb->wqbuf_putIndex];
cnt2end = ARCMSR_MAX_QBUFFER - acb->wqbuf_putIndex;
if (user_len > cnt2end) {
memcpy(pQbuffer, ptmpuserbuffer, cnt2end);
ptmpuserbuffer += cnt2end;
user_len -= cnt2end;
acb->wqbuf_putIndex = 0;
pQbuffer = acb->wqbuffer;
}
memcpy(pQbuffer, ptmpuserbuffer, user_len);
acb->wqbuf_putIndex += user_len;
acb->wqbuf_putIndex %= ARCMSR_MAX_QBUFFER;
if (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_CLEARED) {
acb->acb_flags &=
~ACB_F_MESSAGE_WQBUFFER_CLEARED;
arcmsr_write_ioctldata2iop(acb);
}
}
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
kfree(ver_addr);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_RQBUFFER: {
uint8_t *pQbuffer = acb->rqbuffer;
arcmsr_clear_iop2drv_rqueue_buffer(acb);
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
acb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
memset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_WQBUFFER: {
uint8_t *pQbuffer = acb->wqbuffer;
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |
ACB_F_MESSAGE_WQBUFFER_READED);
acb->wqbuf_getIndex = 0;
acb->wqbuf_putIndex = 0;
memset(pQbuffer, 0, ARCMSR_MAX_QBUFFER);
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_CLEAR_ALLQBUFFER: {
uint8_t *pQbuffer;
arcmsr_clear_iop2drv_rqueue_buffer(acb);
spin_lock_irqsave(&acb->rqbuffer_lock, flags);
acb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED;
acb->rqbuf_getIndex = 0;
acb->rqbuf_putIndex = 0;
pQbuffer = acb->rqbuffer;
memset(pQbuffer, 0, sizeof(struct QBUFFER));
spin_unlock_irqrestore(&acb->rqbuffer_lock, flags);
spin_lock_irqsave(&acb->wqbuffer_lock, flags);
acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED |
ACB_F_MESSAGE_WQBUFFER_READED);
acb->wqbuf_getIndex = 0;
acb->wqbuf_putIndex = 0;
pQbuffer = acb->wqbuffer;
memset(pQbuffer, 0, sizeof(struct QBUFFER));
spin_unlock_irqrestore(&acb->wqbuffer_lock, flags);
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
break;
}
case ARCMSR_MESSAGE_RETURN_CODE_3F: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_3F;
break;
}
case ARCMSR_MESSAGE_SAY_HELLO: {
int8_t *hello_string = "Hello! I am ARCMSR";
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
memcpy(pcmdmessagefld->messagedatabuffer,
hello_string, (int16_t)strlen(hello_string));
break;
}
case ARCMSR_MESSAGE_SAY_GOODBYE: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
arcmsr_iop_parking(acb);
break;
}
case ARCMSR_MESSAGE_FLUSH_ADAPTER_CACHE: {
if (acb->fw_flag == FW_DEADLOCK)
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON;
else
pcmdmessagefld->cmdmessage.ReturnCode =
ARCMSR_MESSAGE_RETURNCODE_OK;
arcmsr_flush_adapter_cache(acb);
break;
}
default:
retvalue = ARCMSR_MESSAGE_FAIL;
pr_info("%s: unknown controlcode!\n", __func__);
}
message_out:
if (use_sg) {
struct scatterlist *sg = scsi_sglist(cmd);
kunmap_atomic(buffer - sg->offset);
}
return retvalue;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'scsi: arcmsr: Simplify user_len checking
Do the user_len check first and then the ver_addr allocation so that we
can save us the kfree() on the error path when user_len is >
ARCMSR_API_DATA_BUFLEN.
Signed-off-by: Borislav Petkov <[email protected]>
Cc: Marco Grassi <[email protected]>
Cc: Dan Carpenter <[email protected]>
Cc: Tomas Henzl <[email protected]>
Cc: Martin K. Petersen <[email protected]>
Cc: <[email protected]>
Reviewed-by: Johannes Thumshirn <[email protected]>
Reviewed-by: Tomas Henzl <[email protected]>
Signed-off-by: Martin K. Petersen <[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 *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define RMT_EQUAL_RGB 1
#define RMT_NONE 0
#define RMT_RAW 2
#define RT_STANDARD 1
#define RT_ENCODED 2
#define RT_FORMAT_RGB 3
typedef struct _SUNInfo
{
unsigned int
magic,
width,
height,
depth,
length,
type,
maptype,
maplength;
} SUNInfo;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bytes_per_line,
extent,
length;
ssize_t
count,
y;
SUNInfo
sun_info;
unsigned char
*sun_data,
*sun_pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SUN raster header.
*/
(void) ResetMagickMemory(&sun_info,0,sizeof(sun_info));
sun_info.magic=ReadBlobMSBLong(image);
do
{
/*
Verify SUN identifier.
*/
if (sun_info.magic != 0x59a66a95)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
sun_info.width=ReadBlobMSBLong(image);
sun_info.height=ReadBlobMSBLong(image);
sun_info.depth=ReadBlobMSBLong(image);
sun_info.length=ReadBlobMSBLong(image);
sun_info.type=ReadBlobMSBLong(image);
sun_info.maptype=ReadBlobMSBLong(image);
sun_info.maplength=ReadBlobMSBLong(image);
extent=sun_info.height*sun_info.width;
if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) &&
(sun_info.type != RT_FORMAT_RGB))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.depth == 0) || (sun_info.depth > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) &&
(sun_info.maptype != RMT_RAW))
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
image->columns=sun_info.width;
image->rows=sun_info.height;
image->depth=sun_info.depth <= 8 ? sun_info.depth :
MAGICKCORE_QUANTUM_DEPTH;
if (sun_info.depth < 24)
{
size_t
one;
image->storage_class=PseudoClass;
image->colors=sun_info.maplength;
one=1;
if (sun_info.maptype == RMT_NONE)
image->colors=one << sun_info.depth;
if (sun_info.maptype == RMT_EQUAL_RGB)
image->colors=sun_info.maplength/3;
}
switch (sun_info.maptype)
{
case RMT_NONE:
{
if (sun_info.depth < 24)
{
/*
Create linear color ramp.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
break;
}
case RMT_EQUAL_RGB:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
case RMT_RAW:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,sun_info.maplength,sun_colormap);
if (count != (ssize_t) sun_info.maplength)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=sun_info.width;
image->rows=sun_info.height;
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));
if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) !=
sun_info.length || !sun_info.length)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((sun_info.type != RT_ENCODED) && (sun_info.depth >= 8) &&
((number_pixels*((sun_info.depth+7)/8)) > sun_info.length))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bytes_per_line=sun_info.width*sun_info.depth;
sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(
sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data));
if (sun_data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=(ssize_t) ReadBlob(image,sun_info.length,sun_data);
if (count != (ssize_t) sun_info.length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
sun_pixels=sun_data;
bytes_per_line=0;
if (sun_info.type == RT_ENCODED)
{
size_t
height;
/*
Read run-length encoded raster pixels.
*/
height=sun_info.height;
if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) ||
((bytes_per_line/sun_info.depth) != sun_info.width))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bytes_per_line+=15;
bytes_per_line<<=1;
if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bytes_per_line>>=4;
sun_pixels=(unsigned char *) AcquireQuantumMemory(height,
bytes_per_line*sizeof(*sun_pixels));
if (sun_pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line*
height);
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
}
/*
Convert SUN raster image to pixel packets.
*/
p=sun_pixels;
if (sun_info.depth == 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=7; bit >= 0; bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),
q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 :
0x01),q);
q+=GetPixelChannels(image);
}
p++;
}
if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image->storage_class == PseudoClass)
{
if (bytes_per_line == 0)
bytes_per_line=image->columns;
length=image->rows*(image->columns+image->columns % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
size_t
bytes_per_pixel;
bytes_per_pixel=3;
if (image->alpha_trait != UndefinedPixelTrait)
bytes_per_pixel++;
if (bytes_per_line == 0)
bytes_per_line=bytes_per_pixel*image->columns;
length=image->rows*(bytes_per_line+image->columns % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
if (sun_info.type == RT_STANDARD)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
}
else
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
}
if (image->colors != 0)
{
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelRed(image,q)].red),q);
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelGreen(image,q)].green),q);
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelBlue(image,q)].blue),q);
}
q+=GetPixelChannels(image);
}
if (((bytes_per_pixel*image->columns) % 2) != 0)
p++;
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);
sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
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;
sun_info.magic=ReadBlobMSBLong(image);
if (sun_info.magic == 0x59a66a95)
{
/*
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 (sun_info.magic == 0x59a66a95);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=26848'</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 *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define RMT_EQUAL_RGB 1
#define RMT_NONE 0
#define RMT_RAW 2
#define RT_STANDARD 1
#define RT_ENCODED 2
#define RT_FORMAT_RGB 3
typedef struct _SUNInfo
{
unsigned int
magic,
width,
height,
depth,
length,
type,
maptype,
maplength;
} SUNInfo;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bytes_per_line,
extent,
length;
ssize_t
count,
y;
SUNInfo
sun_info;
unsigned char
*sun_data,
*sun_pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SUN raster header.
*/
(void) ResetMagickMemory(&sun_info,0,sizeof(sun_info));
sun_info.magic=ReadBlobMSBLong(image);
do
{
/*
Verify SUN identifier.
*/
if (sun_info.magic != 0x59a66a95)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
sun_info.width=ReadBlobMSBLong(image);
sun_info.height=ReadBlobMSBLong(image);
sun_info.depth=ReadBlobMSBLong(image);
sun_info.length=ReadBlobMSBLong(image);
sun_info.type=ReadBlobMSBLong(image);
sun_info.maptype=ReadBlobMSBLong(image);
sun_info.maplength=ReadBlobMSBLong(image);
extent=sun_info.height*sun_info.width;
if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) &&
(sun_info.type != RT_FORMAT_RGB))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.depth == 0) || (sun_info.depth > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) &&
(sun_info.maptype != RMT_RAW))
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
image->columns=sun_info.width;
image->rows=sun_info.height;
image->depth=sun_info.depth <= 8 ? sun_info.depth :
MAGICKCORE_QUANTUM_DEPTH;
if (sun_info.depth < 24)
{
size_t
one;
image->colors=sun_info.maplength;
one=1;
if (sun_info.maptype == RMT_NONE)
image->colors=one << sun_info.depth;
if (sun_info.maptype == RMT_EQUAL_RGB)
image->colors=sun_info.maplength/3;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
switch (sun_info.maptype)
{
case RMT_EQUAL_RGB:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
case RMT_RAW:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,sun_info.maplength,sun_colormap);
if (count != (ssize_t) sun_info.maplength)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=sun_info.width;
image->rows=sun_info.height;
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));
if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) !=
sun_info.length || !sun_info.length)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((sun_info.type != RT_ENCODED) && (sun_info.depth >= 8) &&
((number_pixels*((sun_info.depth+7)/8)) > sun_info.length))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bytes_per_line=sun_info.width*sun_info.depth;
sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(
sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data));
if (sun_data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=(ssize_t) ReadBlob(image,sun_info.length,sun_data);
if (count != (ssize_t) sun_info.length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
sun_pixels=sun_data;
bytes_per_line=0;
if (sun_info.type == RT_ENCODED)
{
size_t
height;
/*
Read run-length encoded raster pixels.
*/
height=sun_info.height;
if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) ||
((bytes_per_line/sun_info.depth) != sun_info.width))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bytes_per_line+=15;
bytes_per_line<<=1;
if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bytes_per_line>>=4;
sun_pixels=(unsigned char *) AcquireQuantumMemory(height,
bytes_per_line*sizeof(*sun_pixels));
if (sun_pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line*
height);
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
}
/*
Convert SUN raster image to pixel packets.
*/
p=sun_pixels;
if (sun_info.depth == 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=7; bit >= 0; bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),
q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 :
0x01),q);
q+=GetPixelChannels(image);
}
p++;
}
if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image->storage_class == PseudoClass)
{
if (bytes_per_line == 0)
bytes_per_line=image->columns;
length=image->rows*(image->columns+image->columns % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
size_t
bytes_per_pixel;
bytes_per_pixel=3;
if (image->alpha_trait != UndefinedPixelTrait)
bytes_per_pixel++;
if (bytes_per_line == 0)
bytes_per_line=bytes_per_pixel*image->columns;
length=image->rows*(bytes_per_line+image->columns % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
if (sun_info.type == RT_STANDARD)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
}
else
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
}
if (image->colors != 0)
{
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelRed(image,q)].red),q);
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelGreen(image,q)].green),q);
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelBlue(image,q)].blue),q);
}
q+=GetPixelChannels(image);
}
if (((bytes_per_pixel*image->columns) % 2) != 0)
p++;
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);
sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
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;
sun_info.magic=ReadBlobMSBLong(image);
if (sun_info.magic == 0x59a66a95)
{
/*
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 (sun_info.magic == 0x59a66a95);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], '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: static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define RMT_EQUAL_RGB 1
#define RMT_NONE 0
#define RMT_RAW 2
#define RT_STANDARD 1
#define RT_ENCODED 2
#define RT_FORMAT_RGB 3
typedef struct _SUNInfo
{
unsigned int
magic,
width,
height,
depth,
length,
type,
maptype,
maplength;
} SUNInfo;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bytes_per_line,
extent,
length;
ssize_t
count,
y;
SUNInfo
sun_info;
unsigned char
*sun_data,
*sun_pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SUN raster header.
*/
(void) ResetMagickMemory(&sun_info,0,sizeof(sun_info));
sun_info.magic=ReadBlobMSBLong(image);
do
{
/*
Verify SUN identifier.
*/
if (sun_info.magic != 0x59a66a95)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
sun_info.width=ReadBlobMSBLong(image);
sun_info.height=ReadBlobMSBLong(image);
sun_info.depth=ReadBlobMSBLong(image);
sun_info.length=ReadBlobMSBLong(image);
sun_info.type=ReadBlobMSBLong(image);
sun_info.maptype=ReadBlobMSBLong(image);
sun_info.maplength=ReadBlobMSBLong(image);
extent=sun_info.height*sun_info.width;
if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) &&
(sun_info.type != RT_FORMAT_RGB))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.depth == 0) || (sun_info.depth > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) &&
(sun_info.maptype != RMT_RAW))
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
image->columns=sun_info.width;
image->rows=sun_info.height;
image->depth=sun_info.depth <= 8 ? sun_info.depth :
MAGICKCORE_QUANTUM_DEPTH;
if (sun_info.depth < 24)
{
size_t
one;
image->colors=sun_info.maplength;
one=1;
if (sun_info.maptype == RMT_NONE)
image->colors=one << sun_info.depth;
if (sun_info.maptype == RMT_EQUAL_RGB)
image->colors=sun_info.maplength/3;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
switch (sun_info.maptype)
{
case RMT_NONE:
break;
case RMT_EQUAL_RGB:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
case RMT_RAW:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,sun_info.maplength,sun_colormap);
if (count != (ssize_t) sun_info.maplength)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=sun_info.width;
image->rows=sun_info.height;
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));
if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) !=
sun_info.length || !sun_info.length)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((sun_info.type != RT_ENCODED) &&
((number_pixels*sun_info.depth) > (8*sun_info.length)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bytes_per_line=sun_info.width*sun_info.depth;
sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(
sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data));
if (sun_data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=(ssize_t) ReadBlob(image,sun_info.length,sun_data);
if (count != (ssize_t) sun_info.length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
sun_pixels=sun_data;
bytes_per_line=0;
if (sun_info.type == RT_ENCODED)
{
size_t
height;
/*
Read run-length encoded raster pixels.
*/
height=sun_info.height;
if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) ||
((bytes_per_line/sun_info.depth) != sun_info.width))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bytes_per_line+=15;
bytes_per_line<<=1;
if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
bytes_per_line>>=4;
sun_pixels=(unsigned char *) AcquireQuantumMemory(height,
bytes_per_line*sizeof(*sun_pixels));
if (sun_pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line*
height);
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
}
/*
Convert SUN raster image to pixel packets.
*/
p=sun_pixels;
if (sun_info.depth == 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=7; bit >= 0; bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),
q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 :
0x01),q);
q+=GetPixelChannels(image);
}
p++;
}
if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image->storage_class == PseudoClass)
{
if (bytes_per_line == 0)
bytes_per_line=image->columns;
length=image->rows*(image->columns+image->columns % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
size_t
bytes_per_pixel;
bytes_per_pixel=3;
if (image->alpha_trait != UndefinedPixelTrait)
bytes_per_pixel++;
if (bytes_per_line == 0)
bytes_per_line=bytes_per_pixel*image->columns;
length=image->rows*(bytes_per_line+bytes_per_line % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
if (sun_info.type == RT_STANDARD)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
}
else
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
}
if (image->colors != 0)
{
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelRed(image,q)].red),q);
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelGreen(image,q)].green),q);
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelBlue(image,q)].blue),q);
}
q+=GetPixelChannels(image);
}
if (((bytes_per_pixel*image->columns) % 2) != 0)
p++;
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);
sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
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;
sun_info.magic=ReadBlobMSBLong(image);
if (sun_info.magic == 0x59a66a95)
{
/*
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 (sun_info.magic == 0x59a66a95);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], '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: static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define RMT_EQUAL_RGB 1
#define RMT_NONE 0
#define RMT_RAW 2
#define RT_STANDARD 1
#define RT_ENCODED 2
#define RT_FORMAT_RGB 3
typedef struct _SUNInfo
{
unsigned int
magic,
width,
height,
depth,
length,
type,
maptype,
maplength;
} SUNInfo;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bytes_per_line,
extent,
height,
length;
ssize_t
count,
y;
SUNInfo
sun_info;
unsigned char
*sun_data,
*sun_pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SUN raster header.
*/
(void) ResetMagickMemory(&sun_info,0,sizeof(sun_info));
sun_info.magic=ReadBlobMSBLong(image);
do
{
/*
Verify SUN identifier.
*/
if (sun_info.magic != 0x59a66a95)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
sun_info.width=ReadBlobMSBLong(image);
sun_info.height=ReadBlobMSBLong(image);
sun_info.depth=ReadBlobMSBLong(image);
sun_info.length=ReadBlobMSBLong(image);
sun_info.type=ReadBlobMSBLong(image);
sun_info.maptype=ReadBlobMSBLong(image);
sun_info.maplength=ReadBlobMSBLong(image);
extent=sun_info.height*sun_info.width;
if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) &&
(sun_info.type != RT_FORMAT_RGB))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.depth == 0) || (sun_info.depth > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) &&
(sun_info.maptype != RMT_RAW))
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
image->columns=sun_info.width;
image->rows=sun_info.height;
image->depth=sun_info.depth <= 8 ? sun_info.depth :
MAGICKCORE_QUANTUM_DEPTH;
if (sun_info.depth < 24)
{
size_t
one;
image->colors=sun_info.maplength;
one=1;
if (sun_info.maptype == RMT_NONE)
image->colors=one << sun_info.depth;
if (sun_info.maptype == RMT_EQUAL_RGB)
image->colors=sun_info.maplength/3;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
switch (sun_info.maptype)
{
case RMT_NONE:
break;
case RMT_EQUAL_RGB:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
case RMT_RAW:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,sun_info.maplength,sun_colormap);
if (count != (ssize_t) sun_info.maplength)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=sun_info.width;
image->rows=sun_info.height;
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));
if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) !=
sun_info.length || !sun_info.length)
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((sun_info.type != RT_ENCODED) &&
((number_pixels*sun_info.depth) > (8*sun_info.length)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bytes_per_line=sun_info.width*sun_info.depth;
sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(
sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data));
if (sun_data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=(ssize_t) ReadBlob(image,sun_info.length,sun_data);
if (count != (ssize_t) sun_info.length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
height=sun_info.height;
if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) ||
((bytes_per_line/sun_info.depth) != sun_info.width))
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
bytes_per_line+=15;
bytes_per_line<<=1;
if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15))
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
bytes_per_line>>=4;
sun_pixels=(unsigned char *) AcquireQuantumMemory(height,
bytes_per_line*sizeof(*sun_pixels));
if (sun_pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (sun_info.type == RT_ENCODED)
(void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line*
height);
else
{
if (sun_info.length > (height*bytes_per_line))
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
(void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length);
}
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
/*
Convert SUN raster image to pixel packets.
*/
p=sun_pixels;
if (sun_info.depth == 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=7; bit >= 0; bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),
q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 :
0x01),q);
q+=GetPixelChannels(image);
}
p++;
}
if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image->storage_class == PseudoClass)
{
if (bytes_per_line == 0)
bytes_per_line=image->columns;
length=image->rows*(image->columns+image->columns % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
size_t
bytes_per_pixel;
bytes_per_pixel=3;
if (image->alpha_trait != UndefinedPixelTrait)
bytes_per_pixel++;
if (bytes_per_line == 0)
bytes_per_line=bytes_per_pixel*image->columns;
length=image->rows*(bytes_per_line+bytes_per_line % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
if (sun_info.type == RT_STANDARD)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
}
else
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
}
if (image->colors != 0)
{
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelRed(image,q)].red),q);
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelGreen(image,q)].green),q);
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelBlue(image,q)].blue),q);
}
q+=GetPixelChannels(image);
}
if (((bytes_per_pixel*image->columns) % 2) != 0)
p++;
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);
sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
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;
sun_info.magic=ReadBlobMSBLong(image);
if (sun_info.magic == 0x59a66a95)
{
/*
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 (sun_info.magic == 0x59a66a95);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], '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: static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const MagickBooleanType separate,ExceptionInfo *exception)
{
size_t
channels,
packet_size;
unsigned char
*compact_pixels;
/*
Write uncompressed pixels as separate planes.
*/
channels=1;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=(unsigned char *) AcquireQuantumMemory(2*channels*
next_image->columns,packet_size*sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
if (IsImageGray(next_image) != MagickFalse)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GrayQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GrayQuantum,MagickTrue,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
if (next_image->storage_class == PseudoClass)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,IndexQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
IndexQuantum,MagickTrue,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,RedQuantum,exception);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GreenQuantum,exception);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlueQuantum,exception);
if (next_image->colorspace == CMYKColorspace)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlackQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
(void) SetImageProgress(image,SaveImagesTag,0,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
RedQuantum,MagickTrue,exception);
(void) SetImageProgress(image,SaveImagesTag,1,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GreenQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,2,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlueQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,3,6);
if (next_image->colorspace == CMYKColorspace)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlackQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,4,6);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,5,6);
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
}
if (next_image->compression == RLECompression)
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fixed overflow.'</s> |
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array.
Code: static MagickBooleanType ReadPSDChannelPixels(Image *image,
const size_t channels,const size_t row,const ssize_t type,
const unsigned char *pixels,ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register Quantum
*q;
register ssize_t
x;
size_t
packet_size;
unsigned short
nibble;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
{
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
switch (type)
{
case -1:
{
SetPixelAlpha(image,pixel,q);
break;
}
case -2:
case 0:
{
SetPixelRed(image,pixel,q);
if (channels == 1 || type == -2)
SetPixelGray(image,pixel,q);
if (image->storage_class == PseudoClass)
{
if (packet_size == 1)
SetPixelIndex(image,ScaleQuantumToChar(pixel),q);
else
SetPixelIndex(image,ScaleQuantumToShort(pixel),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);
if (image->depth == 1)
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit=0; bit < number_bits; bit++)
{
SetPixelIndex(image,(((unsigned char) pixel) &
(0x01 << (7-bit))) != 0 ? 0 : 255,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),
exception),q);
q+=GetPixelChannels(image);
x++;
}
x--;
continue;
}
}
break;
}
case 1:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelGreen(image,pixel,q);
break;
}
case 2:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelBlue(image,pixel,q);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,pixel,q);
else
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
default:
break;
}
q+=GetPixelChannels(image);
}
return(SyncAuthenticPixels(image,exception));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Rewrite reading pixel values.'</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 *ReadVIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define VFF_CM_genericRGB 15
#define VFF_CM_ntscRGB 1
#define VFF_CM_NONE 0
#define VFF_DEP_DECORDER 0x4
#define VFF_DEP_NSORDER 0x8
#define VFF_DES_RAW 0
#define VFF_LOC_IMPLICIT 1
#define VFF_MAPTYP_NONE 0
#define VFF_MAPTYP_1_BYTE 1
#define VFF_MAPTYP_2_BYTE 2
#define VFF_MAPTYP_4_BYTE 4
#define VFF_MAPTYP_FLOAT 5
#define VFF_MAPTYP_DOUBLE 7
#define VFF_MS_NONE 0
#define VFF_MS_ONEPERBAND 1
#define VFF_MS_SHARED 3
#define VFF_TYP_BIT 0
#define VFF_TYP_1_BYTE 1
#define VFF_TYP_2_BYTE 2
#define VFF_TYP_4_BYTE 4
#define VFF_TYP_FLOAT 5
#define VFF_TYP_DOUBLE 9
typedef struct _ViffInfo
{
unsigned char
identifier,
file_type,
release,
version,
machine_dependency,
reserve[3];
char
comment[512];
unsigned int
rows,
columns,
subrows;
int
x_offset,
y_offset;
float
x_bits_per_pixel,
y_bits_per_pixel;
unsigned int
location_type,
location_dimension,
number_of_images,
number_data_bands,
data_storage_type,
data_encode_scheme,
map_scheme,
map_storage_type,
map_rows,
map_columns,
map_subrows,
map_enable,
maps_per_cycle,
color_space_model;
} ViffInfo;
double
min_value,
scale_factor,
value;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register ssize_t
x;
register Quantum
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bytes_per_pixel,
max_packets,
quantum;
ssize_t
count,
y;
unsigned char
*pixels;
unsigned long
lsb_first;
ViffInfo
viff_info;
/*
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 VIFF header (1024 bytes).
*/
count=ReadBlob(image,1,&viff_info.identifier);
do
{
/*
Verify VIFF identifier.
*/
if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab))
ThrowReaderException(CorruptImageError,"NotAVIFFImage");
/*
Initialize VIFF image.
*/
(void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type);
(void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release);
(void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version);
(void) ReadBlob(image,sizeof(viff_info.machine_dependency),
&viff_info.machine_dependency);
(void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve);
count=ReadBlob(image,512,(unsigned char *) viff_info.comment);
viff_info.comment[511]='\0';
if (strlen(viff_info.comment) > 4)
(void) SetImageProperty(image,"comment",viff_info.comment,exception);
if ((viff_info.machine_dependency == VFF_DEP_DECORDER) ||
(viff_info.machine_dependency == VFF_DEP_NSORDER))
image->endian=LSBEndian;
else
image->endian=MSBEndian;
viff_info.rows=ReadBlobLong(image);
viff_info.columns=ReadBlobLong(image);
viff_info.subrows=ReadBlobLong(image);
viff_info.x_offset=(int) ReadBlobLong(image);
viff_info.y_offset=(int) ReadBlobLong(image);
viff_info.x_bits_per_pixel=(float) ReadBlobLong(image);
viff_info.y_bits_per_pixel=(float) ReadBlobLong(image);
viff_info.location_type=ReadBlobLong(image);
viff_info.location_dimension=ReadBlobLong(image);
viff_info.number_of_images=ReadBlobLong(image);
viff_info.number_data_bands=ReadBlobLong(image);
viff_info.data_storage_type=ReadBlobLong(image);
viff_info.data_encode_scheme=ReadBlobLong(image);
viff_info.map_scheme=ReadBlobLong(image);
viff_info.map_storage_type=ReadBlobLong(image);
viff_info.map_rows=ReadBlobLong(image);
viff_info.map_columns=ReadBlobLong(image);
viff_info.map_subrows=ReadBlobLong(image);
viff_info.map_enable=ReadBlobLong(image);
viff_info.maps_per_cycle=ReadBlobLong(image);
viff_info.color_space_model=ReadBlobLong(image);
for (i=0; i < 420; i++)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
image->columns=viff_info.rows;
image->rows=viff_info.columns;
image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL :
MAGICKCORE_QUANTUM_DEPTH;
/*
Verify that we can read this VIFF image.
*/
number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows;
if (number_pixels != (size_t) number_pixels)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (number_pixels == 0)
ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported");
if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((viff_info.data_storage_type != VFF_TYP_BIT) &&
(viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_2_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_4_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_FLOAT) &&
(viff_info.data_storage_type != VFF_TYP_DOUBLE))
ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported");
if (viff_info.data_encode_scheme != VFF_DES_RAW)
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) &&
(viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_FLOAT) &&
(viff_info.map_storage_type != VFF_MAPTYP_DOUBLE))
ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported");
if ((viff_info.color_space_model != VFF_CM_NONE) &&
(viff_info.color_space_model != VFF_CM_ntscRGB) &&
(viff_info.color_space_model != VFF_CM_genericRGB))
ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported");
if (viff_info.location_type != VFF_LOC_IMPLICIT)
ThrowReaderException(CoderError,"LocationTypeIsNotSupported");
if (viff_info.number_of_images != 1)
ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported");
if (viff_info.map_rows == 0)
viff_info.map_scheme=VFF_MS_NONE;
switch ((int) viff_info.map_scheme)
{
case VFF_MS_NONE:
{
if (viff_info.number_data_bands < 3)
{
/*
Create linear color ramp.
*/
if (viff_info.data_storage_type == VFF_TYP_BIT)
image->colors=2;
else
if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE)
image->colors=256UL;
else
image->colors=image->depth <= 8 ? 256UL : 65536UL;
status=AcquireImageColormap(image,image->colors,exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
break;
}
case VFF_MS_ONEPERBAND:
case VFF_MS_SHARED:
{
unsigned char
*viff_colormap;
/*
Allocate VIFF colormap.
*/
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break;
case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break;
case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break;
case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break;
case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break;
default: bytes_per_pixel=1; break;
}
image->colors=viff_info.map_columns;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (viff_info.map_rows <
(viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap));
if (viff_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Read VIFF raster colormap.
*/
count=ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows,
viff_colormap);
lsb_first=1;
if (*(char *) &lsb_first &&
((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
(viff_info.machine_dependency != VFF_DEP_NSORDER)))
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_2_BYTE:
{
MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors*
viff_info.map_rows));
break;
}
case VFF_MAPTYP_4_BYTE:
case VFF_MAPTYP_FLOAT:
{
MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors*
viff_info.map_rows));
break;
}
default: break;
}
for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++)
{
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break;
case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break;
case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break;
case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break;
default: value=1.0*viff_colormap[i]; break;
}
if (i < (ssize_t) image->colors)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) value);
image->colormap[i].green=
ScaleCharToQuantum((unsigned char) value);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value);
}
else
if (i < (ssize_t) (2*image->colors))
image->colormap[i % image->colors].green=
ScaleCharToQuantum((unsigned char) value);
else
if (i < (ssize_t) (3*image->colors))
image->colormap[i % image->colors].blue=
ScaleCharToQuantum((unsigned char) value);
}
viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
/*
Initialize image structure.
*/
image->alpha_trait=viff_info.number_data_bands == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
image->storage_class=(viff_info.number_data_bands < 3 ? PseudoClass :
DirectClass);
image->columns=viff_info.rows;
image->rows=viff_info.columns;
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 VIFF pixels.
*/
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: bytes_per_pixel=2; break;
case VFF_TYP_4_BYTE: bytes_per_pixel=4; break;
case VFF_TYP_FLOAT: bytes_per_pixel=4; break;
case VFF_TYP_DOUBLE: bytes_per_pixel=8; break;
default: bytes_per_pixel=1; break;
}
if (viff_info.data_storage_type == VFF_TYP_BIT)
max_packets=((image->columns+7UL) >> 3UL)*image->rows;
else
max_packets=(size_t) (number_pixels*viff_info.number_data_bands);
pixels=(unsigned char *) AcquireQuantumMemory(max_packets,
bytes_per_pixel*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,bytes_per_pixel*max_packets,pixels);
lsb_first=1;
if (*(char *) &lsb_first &&
((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
(viff_info.machine_dependency != VFF_DEP_NSORDER)))
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE:
{
MSBOrderShort(pixels,bytes_per_pixel*max_packets);
break;
}
case VFF_TYP_4_BYTE:
case VFF_TYP_FLOAT:
{
MSBOrderLong(pixels,bytes_per_pixel*max_packets);
break;
}
default: break;
}
min_value=0.0;
scale_factor=1.0;
if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
(viff_info.map_scheme == VFF_MS_NONE))
{
double
max_value;
/*
Determine scale factor.
*/
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break;
default: value=1.0*pixels[0]; break;
}
max_value=value;
min_value=value;
for (i=0; i < (ssize_t) max_packets; i++)
{
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
default: value=1.0*pixels[i]; break;
}
if (value > max_value)
max_value=value;
else
if (value < min_value)
min_value=value;
}
if ((min_value == 0) && (max_value == 0))
scale_factor=0;
else
if (min_value == max_value)
{
scale_factor=(double) QuantumRange/min_value;
min_value=0;
}
else
scale_factor=(double) QuantumRange/(max_value-min_value);
}
/*
Convert pixels to Quantum size.
*/
p=(unsigned char *) pixels;
for (i=0; i < (ssize_t) max_packets; i++)
{
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
default: value=1.0*pixels[i]; break;
}
if (viff_info.map_scheme == VFF_MS_NONE)
{
value=(value-min_value)*scale_factor;
if (value > QuantumRange)
value=QuantumRange;
else
if (value < 0)
value=0;
}
*p=(unsigned char) ((Quantum) value);
p++;
}
/*
Convert VIFF raster image to pixel packets.
*/
p=(unsigned char *) pixels;
if (viff_info.data_storage_type == VFF_TYP_BIT)
{
/*
Convert bitmap scanline.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) (image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q);
SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q);
SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q);
if (image->storage_class == PseudoClass)
SetPixelIndex(image,(Quantum) quantum,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (int) (image->columns % 8); bit++)
{
quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q);
SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q);
SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q);
if (image->storage_class == PseudoClass)
SetPixelIndex(image,(Quantum) quantum,q);
q+=GetPixelChannels(image);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
if (image->storage_class == PseudoClass)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
{
/*
Convert DirectColor scanline.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+number_pixels)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2*number_pixels)),q);
if (image->colors != 0)
{
ssize_t
index;
index=(ssize_t) GetPixelRed(image,q);
SetPixelRed(image,image->colormap[
ConstrainColormapIndex(image,index,exception)].red,q);
index=(ssize_t) GetPixelGreen(image,q);
SetPixelGreen(image,image->colormap[
ConstrainColormapIndex(image,index,exception)].green,q);
index=(ssize_t) GetPixelBlue(image,q);
SetPixelBlue(image,image->colormap[
ConstrainColormapIndex(image,index,exception)].blue,q);
}
SetPixelAlpha(image,image->alpha_trait != UndefinedPixelTrait ?
ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueAlpha,q);
p++;
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;
}
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
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;
count=ReadBlob(image,1,&viff_info.identifier);
if ((count != 0) && (viff_info.identifier == 0xab))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (viff_info.identifier == 0xab));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fixed check.'</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 *ResizeQuantumMemory(void *memory,const size_t count,
const size_t quantum)
{
size_t
size;
size=count*quantum;
if ((count == 0) || (quantum != (size/count)))
{
memory=RelinquishMagickMemory(memory);
errno=ENOMEM;
return((void *) NULL);
}
return(ResizeMagickMemory(memory,size));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/82
https://github.com/ImageMagick/ImageMagick/issues/81
https://github.com/ImageMagick/ImageMagick/issues/80
https://github.com/ImageMagick/ImageMagick/issues/77'</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 *AcquireQuantumMemory(const size_t count,const size_t quantum)
{
size_t
size;
size=count*quantum;
if ((count == 0) || (quantum != (size/count)))
{
errno=ENOMEM;
return((void *) NULL);
}
return(AcquireMagickMemory(size));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/82
https://github.com/ImageMagick/ImageMagick/issues/81
https://github.com/ImageMagick/ImageMagick/issues/80
https://github.com/ImageMagick/ImageMagick/issues/77'</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 *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define RMT_EQUAL_RGB 1
#define RMT_NONE 0
#define RMT_RAW 2
#define RT_STANDARD 1
#define RT_ENCODED 2
#define RT_FORMAT_RGB 3
typedef struct _SUNInfo
{
unsigned int
magic,
width,
height,
depth,
length,
type,
maptype,
maplength;
} SUNInfo;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bytes_per_line,
extent,
height;
ssize_t
count,
y;
SUNInfo
sun_info;
unsigned char
*sun_data,
*sun_pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SUN raster header.
*/
(void) ResetMagickMemory(&sun_info,0,sizeof(sun_info));
sun_info.magic=ReadBlobMSBLong(image);
do
{
/*
Verify SUN identifier.
*/
if (sun_info.magic != 0x59a66a95)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
sun_info.width=ReadBlobMSBLong(image);
sun_info.height=ReadBlobMSBLong(image);
sun_info.depth=ReadBlobMSBLong(image);
sun_info.length=ReadBlobMSBLong(image);
sun_info.type=ReadBlobMSBLong(image);
sun_info.maptype=ReadBlobMSBLong(image);
sun_info.maplength=ReadBlobMSBLong(image);
extent=sun_info.height*sun_info.width;
if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) &&
(sun_info.type != RT_FORMAT_RGB))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.depth == 0) || (sun_info.depth > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) &&
(sun_info.maptype != RMT_RAW))
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
image->columns=sun_info.width;
image->rows=sun_info.height;
image->depth=sun_info.depth <= 8 ? sun_info.depth :
MAGICKCORE_QUANTUM_DEPTH;
if (sun_info.depth < 24)
{
size_t
one;
image->colors=sun_info.maplength;
one=1;
if (sun_info.maptype == RMT_NONE)
image->colors=one << sun_info.depth;
if (sun_info.maptype == RMT_EQUAL_RGB)
image->colors=sun_info.maplength/3;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
switch (sun_info.maptype)
{
case RMT_NONE:
break;
case RMT_EQUAL_RGB:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
case RMT_RAW:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,sun_info.maplength,sun_colormap);
if (count != (ssize_t) sun_info.maplength)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=sun_info.width;
image->rows=sun_info.height;
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));
if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) !=
sun_info.length || !sun_info.length)
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
number_pixels=(MagickSizeType) (image->columns*image->rows);
if ((sun_info.type != RT_ENCODED) &&
((number_pixels*sun_info.depth) > (8UL*sun_info.length)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bytes_per_line=sun_info.width*sun_info.depth;
sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(
sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data));
if (sun_data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=(ssize_t) ReadBlob(image,sun_info.length,sun_data);
if (count != (ssize_t) sun_info.length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
height=sun_info.height;
if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) ||
((bytes_per_line/sun_info.depth) != sun_info.width))
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
bytes_per_line+=15;
bytes_per_line<<=1;
if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15))
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
bytes_per_line>>=4;
sun_pixels=(unsigned char *) AcquireQuantumMemory(height,
bytes_per_line*sizeof(*sun_pixels));
if (sun_pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (sun_info.type == RT_ENCODED)
(void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line*
height);
else
{
if (sun_info.length > (height*bytes_per_line))
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
(void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length);
}
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
/*
Convert SUN raster image to pixel packets.
*/
p=sun_pixels;
if (sun_info.depth == 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=7; bit >= 0; bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),
q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 :
0x01),q);
q+=GetPixelChannels(image);
}
p++;
}
if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image->storage_class == PseudoClass)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,ConstrainColormapIndex(image,*p,exception),q);
p++;
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
size_t
bytes_per_pixel;
bytes_per_pixel=3;
if (image->alpha_trait != UndefinedPixelTrait)
bytes_per_pixel++;
if (bytes_per_line == 0)
bytes_per_line=bytes_per_pixel*image->columns;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
if (sun_info.type == RT_STANDARD)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
}
else
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
}
if (image->colors != 0)
{
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelRed(image,q)].red),q);
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelGreen(image,q)].green),q);
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelBlue(image,q)].blue),q);
}
q+=GetPixelChannels(image);
}
if (((bytes_per_pixel*image->columns) % 2) != 0)
p++;
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);
sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
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;
sun_info.magic=ReadBlobMSBLong(image);
if (sun_info.magic == 0x59a66a95)
{
/*
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 (sun_info.magic == 0x59a66a95);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/82
https://github.com/ImageMagick/ImageMagick/issues/81
https://github.com/ImageMagick/ImageMagick/issues/80
https://github.com/ImageMagick/ImageMagick/issues/77'</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 *ReadVIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define VFF_CM_genericRGB 15
#define VFF_CM_ntscRGB 1
#define VFF_CM_NONE 0
#define VFF_DEP_DECORDER 0x4
#define VFF_DEP_NSORDER 0x8
#define VFF_DES_RAW 0
#define VFF_LOC_IMPLICIT 1
#define VFF_MAPTYP_NONE 0
#define VFF_MAPTYP_1_BYTE 1
#define VFF_MAPTYP_2_BYTE 2
#define VFF_MAPTYP_4_BYTE 4
#define VFF_MAPTYP_FLOAT 5
#define VFF_MAPTYP_DOUBLE 7
#define VFF_MS_NONE 0
#define VFF_MS_ONEPERBAND 1
#define VFF_MS_SHARED 3
#define VFF_TYP_BIT 0
#define VFF_TYP_1_BYTE 1
#define VFF_TYP_2_BYTE 2
#define VFF_TYP_4_BYTE 4
#define VFF_TYP_FLOAT 5
#define VFF_TYP_DOUBLE 9
typedef struct _ViffInfo
{
unsigned char
identifier,
file_type,
release,
version,
machine_dependency,
reserve[3];
char
comment[512];
unsigned int
rows,
columns,
subrows;
int
x_offset,
y_offset;
float
x_bits_per_pixel,
y_bits_per_pixel;
unsigned int
location_type,
location_dimension,
number_of_images,
number_data_bands,
data_storage_type,
data_encode_scheme,
map_scheme,
map_storage_type,
map_rows,
map_columns,
map_subrows,
map_enable,
maps_per_cycle,
color_space_model;
} ViffInfo;
double
min_value,
scale_factor,
value;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register ssize_t
x;
register Quantum
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bytes_per_pixel,
max_packets,
quantum;
ssize_t
count,
y;
unsigned char
*pixels;
unsigned long
lsb_first;
ViffInfo
viff_info;
/*
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 VIFF header (1024 bytes).
*/
count=ReadBlob(image,1,&viff_info.identifier);
do
{
/*
Verify VIFF identifier.
*/
if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab))
ThrowReaderException(CorruptImageError,"NotAVIFFImage");
/*
Initialize VIFF image.
*/
(void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type);
(void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release);
(void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version);
(void) ReadBlob(image,sizeof(viff_info.machine_dependency),
&viff_info.machine_dependency);
(void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve);
count=ReadBlob(image,512,(unsigned char *) viff_info.comment);
viff_info.comment[511]='\0';
if (strlen(viff_info.comment) > 4)
(void) SetImageProperty(image,"comment",viff_info.comment,exception);
if ((viff_info.machine_dependency == VFF_DEP_DECORDER) ||
(viff_info.machine_dependency == VFF_DEP_NSORDER))
image->endian=LSBEndian;
else
image->endian=MSBEndian;
viff_info.rows=ReadBlobLong(image);
viff_info.columns=ReadBlobLong(image);
viff_info.subrows=ReadBlobLong(image);
viff_info.x_offset=(int) ReadBlobLong(image);
viff_info.y_offset=(int) ReadBlobLong(image);
viff_info.x_bits_per_pixel=(float) ReadBlobLong(image);
viff_info.y_bits_per_pixel=(float) ReadBlobLong(image);
viff_info.location_type=ReadBlobLong(image);
viff_info.location_dimension=ReadBlobLong(image);
viff_info.number_of_images=ReadBlobLong(image);
viff_info.number_data_bands=ReadBlobLong(image);
viff_info.data_storage_type=ReadBlobLong(image);
viff_info.data_encode_scheme=ReadBlobLong(image);
viff_info.map_scheme=ReadBlobLong(image);
viff_info.map_storage_type=ReadBlobLong(image);
viff_info.map_rows=ReadBlobLong(image);
viff_info.map_columns=ReadBlobLong(image);
viff_info.map_subrows=ReadBlobLong(image);
viff_info.map_enable=ReadBlobLong(image);
viff_info.maps_per_cycle=ReadBlobLong(image);
viff_info.color_space_model=ReadBlobLong(image);
for (i=0; i < 420; i++)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
image->columns=viff_info.rows;
image->rows=viff_info.columns;
image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL :
MAGICKCORE_QUANTUM_DEPTH;
/*
Verify that we can read this VIFF image.
*/
number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows;
if (number_pixels != (size_t) number_pixels)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (number_pixels == 0)
ThrowReaderException(CoderError,"ImageColumnOrRowSizeIsNotSupported");
if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((viff_info.data_storage_type != VFF_TYP_BIT) &&
(viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_2_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_4_BYTE) &&
(viff_info.data_storage_type != VFF_TYP_FLOAT) &&
(viff_info.data_storage_type != VFF_TYP_DOUBLE))
ThrowReaderException(CoderError,"DataStorageTypeIsNotSupported");
if (viff_info.data_encode_scheme != VFF_DES_RAW)
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) &&
(viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) &&
(viff_info.map_storage_type != VFF_MAPTYP_FLOAT) &&
(viff_info.map_storage_type != VFF_MAPTYP_DOUBLE))
ThrowReaderException(CoderError,"MapStorageTypeIsNotSupported");
if ((viff_info.color_space_model != VFF_CM_NONE) &&
(viff_info.color_space_model != VFF_CM_ntscRGB) &&
(viff_info.color_space_model != VFF_CM_genericRGB))
ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported");
if (viff_info.location_type != VFF_LOC_IMPLICIT)
ThrowReaderException(CoderError,"LocationTypeIsNotSupported");
if (viff_info.number_of_images != 1)
ThrowReaderException(CoderError,"NumberOfImagesIsNotSupported");
if (viff_info.map_rows == 0)
viff_info.map_scheme=VFF_MS_NONE;
switch ((int) viff_info.map_scheme)
{
case VFF_MS_NONE:
{
if (viff_info.number_data_bands < 3)
{
/*
Create linear color ramp.
*/
if (viff_info.data_storage_type == VFF_TYP_BIT)
image->colors=2;
else
if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE)
image->colors=256UL;
else
image->colors=image->depth <= 8 ? 256UL : 65536UL;
status=AcquireImageColormap(image,image->colors,exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
break;
}
case VFF_MS_ONEPERBAND:
case VFF_MS_SHARED:
{
unsigned char
*viff_colormap;
/*
Allocate VIFF colormap.
*/
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break;
case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break;
case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break;
case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break;
case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break;
default: bytes_per_pixel=1; break;
}
image->colors=viff_info.map_columns;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap));
if (viff_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Read VIFF raster colormap.
*/
count=ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows,
viff_colormap);
lsb_first=1;
if (*(char *) &lsb_first &&
((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
(viff_info.machine_dependency != VFF_DEP_NSORDER)))
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_2_BYTE:
{
MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors*
viff_info.map_rows));
break;
}
case VFF_MAPTYP_4_BYTE:
case VFF_MAPTYP_FLOAT:
{
MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors*
viff_info.map_rows));
break;
}
default: break;
}
for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++)
{
switch ((int) viff_info.map_storage_type)
{
case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break;
case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break;
case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break;
case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break;
default: value=1.0*viff_colormap[i]; break;
}
if (i < (ssize_t) image->colors)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) value);
image->colormap[i].green=
ScaleCharToQuantum((unsigned char) value);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value);
}
else
if (i < (ssize_t) (2*image->colors))
image->colormap[i % image->colors].green=
ScaleCharToQuantum((unsigned char) value);
else
if (i < (ssize_t) (3*image->colors))
image->colormap[i % image->colors].blue=
ScaleCharToQuantum((unsigned char) value);
}
viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
/*
Initialize image structure.
*/
image->alpha_trait=viff_info.number_data_bands == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
image->storage_class=(viff_info.number_data_bands < 3 ? PseudoClass :
DirectClass);
image->columns=viff_info.rows;
image->rows=viff_info.columns;
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 VIFF pixels.
*/
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: bytes_per_pixel=2; break;
case VFF_TYP_4_BYTE: bytes_per_pixel=4; break;
case VFF_TYP_FLOAT: bytes_per_pixel=4; break;
case VFF_TYP_DOUBLE: bytes_per_pixel=8; break;
default: bytes_per_pixel=1; break;
}
if (viff_info.data_storage_type == VFF_TYP_BIT)
max_packets=((image->columns+7UL) >> 3UL)*image->rows;
else
max_packets=(size_t) (number_pixels*viff_info.number_data_bands);
pixels=(unsigned char *) AcquireQuantumMemory(max_packets,
bytes_per_pixel*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,bytes_per_pixel*max_packets,pixels);
lsb_first=1;
if (*(char *) &lsb_first &&
((viff_info.machine_dependency != VFF_DEP_DECORDER) &&
(viff_info.machine_dependency != VFF_DEP_NSORDER)))
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE:
{
MSBOrderShort(pixels,bytes_per_pixel*max_packets);
break;
}
case VFF_TYP_4_BYTE:
case VFF_TYP_FLOAT:
{
MSBOrderLong(pixels,bytes_per_pixel*max_packets);
break;
}
default: break;
}
min_value=0.0;
scale_factor=1.0;
if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) &&
(viff_info.map_scheme == VFF_MS_NONE))
{
double
max_value;
/*
Determine scale factor.
*/
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break;
default: value=1.0*pixels[0]; break;
}
max_value=value;
min_value=value;
for (i=0; i < (ssize_t) max_packets; i++)
{
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
default: value=1.0*pixels[i]; break;
}
if (value > max_value)
max_value=value;
else
if (value < min_value)
min_value=value;
}
if ((min_value == 0) && (max_value == 0))
scale_factor=0;
else
if (min_value == max_value)
{
scale_factor=(double) QuantumRange/min_value;
min_value=0;
}
else
scale_factor=(double) QuantumRange/(max_value-min_value);
}
/*
Convert pixels to Quantum size.
*/
p=(unsigned char *) pixels;
for (i=0; i < (ssize_t) max_packets; i++)
{
switch ((int) viff_info.data_storage_type)
{
case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break;
case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break;
case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break;
case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break;
default: value=1.0*pixels[i]; break;
}
if (viff_info.map_scheme == VFF_MS_NONE)
{
value=(value-min_value)*scale_factor;
if (value > QuantumRange)
value=QuantumRange;
else
if (value < 0)
value=0;
}
*p=(unsigned char) ((Quantum) value);
p++;
}
/*
Convert VIFF raster image to pixel packets.
*/
p=(unsigned char *) pixels;
if (viff_info.data_storage_type == VFF_TYP_BIT)
{
/*
Convert bitmap scanline.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) (image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q);
SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q);
SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q);
if (image->storage_class == PseudoClass)
SetPixelIndex(image,(Quantum) quantum,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (int) (image->columns % 8); bit++)
{
quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1);
SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q);
SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q);
SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q);
if (image->storage_class == PseudoClass)
SetPixelIndex(image,(Quantum) quantum,q);
q+=GetPixelChannels(image);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
if (image->storage_class == PseudoClass)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
{
/*
Convert DirectColor scanline.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+number_pixels)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2*number_pixels)),q);
if (image->colors != 0)
{
ssize_t
index;
index=(ssize_t) GetPixelRed(image,q);
SetPixelRed(image,image->colormap[
ConstrainColormapIndex(image,index,exception)].red,q);
index=(ssize_t) GetPixelGreen(image,q);
SetPixelGreen(image,image->colormap[
ConstrainColormapIndex(image,index,exception)].green,q);
index=(ssize_t) GetPixelBlue(image,q);
SetPixelBlue(image,image->colormap[
ConstrainColormapIndex(image,index,exception)].blue,q);
}
SetPixelAlpha(image,image->alpha_trait != UndefinedPixelTrait ?
ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueAlpha,q);
p++;
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;
}
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
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;
count=ReadBlob(image,1,&viff_info.identifier);
if ((count != 0) && (viff_info.identifier == 0xab))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (viff_info.identifier == 0xab));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/82
https://github.com/ImageMagick/ImageMagick/issues/81
https://github.com/ImageMagick/ImageMagick/issues/80
https://github.com/ImageMagick/ImageMagick/issues/77'</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 ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
CheckNumberCompactPixels;
compact_pixels++;
}
}
return(i);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Moved check for https://github.com/ImageMagick/ImageMagick/issues/92.'</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 size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return((image->columns+7)/8);
else
return(image->columns*GetPSDPacketSize(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Fixed head buffer overflow reported in: https://github.com/ImageMagick/ImageMagick/issues/98'</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 size_t GetQuantumExtent(const Image *image,
const QuantumInfo *quantum_info,const QuantumType quantum_type)
{
size_t
packet_size;
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
packet_size=1;
switch (quantum_type)
{
case GrayAlphaQuantum: packet_size=2; break;
case IndexAlphaQuantum: packet_size=2; break;
case RGBQuantum: packet_size=3; break;
case BGRQuantum: packet_size=3; break;
case RGBAQuantum: packet_size=4; break;
case RGBOQuantum: packet_size=4; break;
case BGRAQuantum: packet_size=4; break;
case CMYKQuantum: packet_size=4; break;
case CMYKAQuantum: packet_size=5; break;
default: break;
}
if (quantum_info->pack == MagickFalse)
return((size_t) (packet_size*image->columns*((quantum_info->depth+7)/8)));
return((size_t) ((packet_size*image->columns*quantum_info->depth+7)/8));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/105'</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 WritePDBImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
const char
*comment;
int
bits;
MagickBooleanType
status;
PDBImage
pdb_image;
PDBInfo
pdb_info;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
x;
register unsigned char
*q;
size_t
bits_per_pixel,
literal,
packets,
packet_size,
repeat;
ssize_t
y;
unsigned char
*buffer,
*runlength,
*scanline;
/*
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) TransformImageColorspace(image,sRGBColorspace,exception);
if (SetImageMonochrome(image,exception) != MagickFalse) {
bits_per_pixel=1;
} else if (image->colors <= 4) {
bits_per_pixel=2;
} else if (image->colors <= 8) {
bits_per_pixel=3;
} else {
bits_per_pixel=4;
}
(void) ResetMagickMemory(&pdb_info,0,sizeof(pdb_info));
(void) CopyMagickString(pdb_info.name,image_info->filename,
sizeof(pdb_info.name));
pdb_info.attributes=0;
pdb_info.version=0;
pdb_info.create_time=time(NULL);
pdb_info.modify_time=pdb_info.create_time;
pdb_info.archive_time=0;
pdb_info.modify_number=0;
pdb_info.application_info=0;
pdb_info.sort_info=0;
(void) CopyMagickMemory(pdb_info.type,"vIMG",4);
(void) CopyMagickMemory(pdb_info.id,"View",4);
pdb_info.seed=0;
pdb_info.next_record=0;
comment=GetImageProperty(image,"comment",exception);
pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2);
(void) WriteBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info);
(void) WriteBlob(image,4,(unsigned char *) pdb_info.type);
(void) WriteBlob(image,4,(unsigned char *) pdb_info.id);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records);
(void) CopyMagickString(pdb_image.name,pdb_info.name,sizeof(pdb_image.name));
pdb_image.version=1; /* RLE Compressed */
switch (bits_per_pixel)
{
case 1: pdb_image.type=(unsigned char) 0xff; break; /* monochrome */
case 2: pdb_image.type=(unsigned char) 0x00; break; /* 2 bit gray */
default: pdb_image.type=(unsigned char) 0x02; /* 4 bit gray */
}
pdb_image.reserved_1=0;
pdb_image.note=0;
pdb_image.x_last=0;
pdb_image.y_last=0;
pdb_image.reserved_2=0;
pdb_image.x_anchor=(unsigned short) 0xffff;
pdb_image.y_anchor=(unsigned short) 0xffff;
pdb_image.width=(short) image->columns;
if (image->columns % 16)
pdb_image.width=(short) (16*(image->columns/16+1));
pdb_image.height=(short) image->rows;
packets=((bits_per_pixel*image->columns+7)/8);
runlength=(unsigned char *) AcquireQuantumMemory(4UL*packets,
image->rows*sizeof(*runlength));
if (runlength == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
buffer=(unsigned char *) AcquireQuantumMemory(2*256,sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
packet_size=(size_t) (image->depth > 8 ? 2: 1);
scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Convert to GRAY raster scanline.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
bits=8/(int) bits_per_pixel-1; /* start at most significant bits */
literal=0;
repeat=0;
q=runlength;
buffer[0]=0x00;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
(void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,scanline,exception);
for (x=0; x < (ssize_t) pdb_image.width; x++)
{
if (x < (ssize_t) image->columns)
buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >>
(8-bits_per_pixel) << bits*bits_per_pixel;
bits--;
if (bits < 0)
{
if (((literal+repeat) > 0) &&
(buffer[literal+repeat] == buffer[literal+repeat-1]))
{
if (repeat == 0)
{
literal--;
repeat++;
}
repeat++;
if (0x7f < repeat)
{
q=EncodeRLE(q,buffer,literal,repeat);
literal=0;
repeat=0;
}
}
else
{
if (repeat >= 2)
literal+=repeat;
else
{
q=EncodeRLE(q,buffer,literal,repeat);
buffer[0]=buffer[literal+repeat];
literal=0;
}
literal++;
repeat=0;
if (0x7f < literal)
{
q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0);
(void) CopyMagickMemory(buffer,buffer+literal+repeat,0x80);
literal-=0x80;
}
}
bits=8/(int) bits_per_pixel-1;
buffer[literal+repeat]=0x00;
}
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
q=EncodeRLE(q,buffer,literal,repeat);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
quantum_info=DestroyQuantumInfo(quantum_info);
/*
Write the Image record header.
*/
(void) WriteBlobMSBLong(image,(unsigned int)
(TellBlob(image)+8*pdb_info.number_records));
(void) WriteBlobByte(image,0x40);
(void) WriteBlobByte(image,0x6f);
(void) WriteBlobByte(image,0x80);
(void) WriteBlobByte(image,0);
if (pdb_info.number_records > 1)
{
/*
Write the comment record header.
*/
(void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q-
runlength));
(void) WriteBlobByte(image,0x40);
(void) WriteBlobByte(image,0x6f);
(void) WriteBlobByte(image,0x80);
(void) WriteBlobByte(image,1);
}
/*
Write the Image data.
*/
(void) WriteBlob(image,sizeof(pdb_image.name),(unsigned char *)
pdb_image.name);
(void) WriteBlobByte(image,(unsigned char) pdb_image.version);
(void) WriteBlobByte(image,pdb_image.type);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last);
(void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2);
(void) WriteBlobMSBShort(image,pdb_image.x_anchor);
(void) WriteBlobMSBShort(image,pdb_image.y_anchor);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width);
(void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height);
(void) WriteBlob(image,(size_t) (q-runlength),runlength);
runlength=(unsigned char *) RelinquishMagickMemory(runlength);
if (pdb_info.number_records > 1)
(void) WriteBlobString(image,comment);
(void) CloseBlob(image);
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/121'</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 RemoveResolutionFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if ((id == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12)))
{
(void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-
(PSDQuantum(count)+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'Added check for out of bounds read (https://github.com/ImageMagick/ImageMagick/issues/108).'</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 ImportCbYCrYQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 10:
{
Quantum
cbcr[4];
pixel=0;
if (quantum_info->pack == MagickFalse)
{
register ssize_t
i;
size_t
quantum;
ssize_t
n;
n=0;
quantum=0;
for (x=0; x < (ssize_t) number_pixels; x+=2)
{
for (i=0; i < 4; i++)
{
switch (n % 3)
{
case 0:
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 22) & 0x3ff) << 6)));
break;
}
case 1:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 12) & 0x3ff) << 6)));
break;
}
case 2:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 2) & 0x3ff) << 6)));
break;
}
}
cbcr[i]=(Quantum) (quantum);
n++;
}
p+=quantum_info->pad;
SetPixelRed(image,cbcr[1],q);
SetPixelGreen(image,cbcr[0],q);
SetPixelBlue(image,cbcr[2],q);
q+=GetPixelChannels(image);
SetPixelRed(image,cbcr[3],q);
SetPixelGreen(image,cbcr[0],q);
SetPixelBlue(image,cbcr[2],q);
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
}
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/126'</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 WriteImageChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const MagickBooleanType separate,ExceptionInfo *exception)
{
size_t
channels,
packet_size;
unsigned char
*compact_pixels;
/*
Write uncompressed pixels as separate planes.
*/
channels=1;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels*
next_image->columns)+1,packet_size*sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
if (IsImageGray(next_image) != MagickFalse)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GrayQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GrayQuantum,MagickTrue,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
if (next_image->storage_class == PseudoClass)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,IndexQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
IndexQuantum,MagickTrue,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,RedQuantum,exception);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GreenQuantum,exception);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlueQuantum,exception);
if (next_image->colorspace == CMYKColorspace)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlackQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
(void) SetImageProgress(image,SaveImagesTag,0,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
RedQuantum,MagickTrue,exception);
(void) SetImageProgress(image,SaveImagesTag,1,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GreenQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,2,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlueQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,3,6);
if (next_image->colorspace == CMYKColorspace)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlackQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,4,6);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,5,6);
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
}
if (next_image->compression == RLECompression)
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
return(MagickTrue);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/128'</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 mi_sort_index(MI_CHECK *param, register MI_INFO *info, char * name)
{
reg2 uint key;
reg1 MI_KEYDEF *keyinfo;
File new_file;
my_off_t index_pos[HA_MAX_POSSIBLE_KEY];
uint r_locks,w_locks;
int old_lock;
MYISAM_SHARE *share=info->s;
MI_STATE_INFO old_state;
DBUG_ENTER("mi_sort_index");
/* cannot sort index files with R-tree indexes */
for (key= 0,keyinfo= &share->keyinfo[0]; key < share->base.keys ;
key++,keyinfo++)
if (keyinfo->key_alg == HA_KEY_ALG_RTREE)
DBUG_RETURN(0);
if (!(param->testflag & T_SILENT))
printf("- Sorting index for MyISAM-table '%s'\n",name);
/* Get real path for index file */
fn_format(param->temp_filename,name,"", MI_NAME_IEXT,2+4+32);
if ((new_file= mysql_file_create(mi_key_file_datatmp,
fn_format(param->temp_filename,
param->temp_filename,
"", INDEX_TMP_EXT, 2+4),
0, param->tmpfile_createflag, MYF(0))) <= 0)
{
mi_check_print_error(param,"Can't create new tempfile: '%s'",
param->temp_filename);
DBUG_RETURN(-1);
}
if (filecopy(param, new_file,share->kfile,0L,
(ulong) share->base.keystart, "headerblock"))
goto err;
param->new_file_pos=share->base.keystart;
for (key= 0,keyinfo= &share->keyinfo[0]; key < share->base.keys ;
key++,keyinfo++)
{
if (! mi_is_key_active(info->s->state.key_map, key))
continue;
if (share->state.key_root[key] != HA_OFFSET_ERROR)
{
index_pos[key]=param->new_file_pos; /* Write first block here */
if (sort_one_index(param,info,keyinfo,share->state.key_root[key],
new_file))
goto err;
}
else
index_pos[key]= HA_OFFSET_ERROR; /* No blocks */
}
/* Flush key cache for this file if we are calling this outside myisamchk */
flush_key_blocks(share->key_cache,share->kfile, FLUSH_IGNORE_CHANGED);
share->state.version=(ulong) time((time_t*) 0);
old_state= share->state; /* save state if not stored */
r_locks= share->r_locks;
w_locks= share->w_locks;
old_lock= info->lock_type;
/* Put same locks as old file */
share->r_locks= share->w_locks= share->tot_locks= 0;
(void) _mi_writeinfo(info,WRITEINFO_UPDATE_KEYFILE);
(void) mysql_file_close(share->kfile, MYF(MY_WME));
share->kfile = -1;
(void) mysql_file_close(new_file, MYF(MY_WME));
if (change_to_newfile(share->index_file_name, MI_NAME_IEXT, INDEX_TMP_EXT,
MYF(0)) ||
mi_open_keyfile(share))
goto err2;
info->lock_type= F_UNLCK; /* Force mi_readinfo to lock */
_mi_readinfo(info,F_WRLCK,0); /* Will lock the table */
info->lock_type= old_lock;
share->r_locks= r_locks;
share->w_locks= w_locks;
share->tot_locks= r_locks+w_locks;
share->state= old_state; /* Restore old state */
info->state->key_file_length=param->new_file_pos;
info->update= (short) (HA_STATE_CHANGED | HA_STATE_ROW_CHANGED);
for (key=0 ; key < info->s->base.keys ; key++)
info->s->state.key_root[key]=index_pos[key];
for (key=0 ; key < info->s->state.header.max_block_size_index ; key++)
info->s->state.key_del[key]= HA_OFFSET_ERROR;
info->s->state.changed&= ~STATE_NOT_SORTED_PAGES;
DBUG_RETURN(0);
err:
(void) mysql_file_close(new_file, MYF(MY_WME));
err2:
(void) mysql_file_delete(mi_key_file_datatmp,
param->temp_filename, MYF(MY_WME));
DBUG_RETURN(-1);
} /* mi_sort_index */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'Bug#24388746: PRIVILEGE ESCALATION AND RACE CONDITION USING CREATE TABLE
During REPAIR TABLE of a MyISAM table, a temporary data file (.TMD)
is created. When repair finishes, this file is renamed to the original
.MYD file. The problem was that during this rename, we copied the
stats from the old file to the new file with chmod/chown. If a user
managed to replace the temporary file before chmod/chown was executed,
it was possible to get an arbitrary file with the privileges of the
mysql user.
This patch fixes the problem by not copying stats from the old
file to the new file. This is not needed as the new file was
created with the correct stats. This fix only changes server
behavior - external utilities such as myisamchk still does
chmod/chown.
No test case provided since the problem involves synchronization
with file system operations.'</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 ha_myisam::repair(THD *thd, MI_CHECK ¶m, bool do_optimize)
{
int error=0;
uint local_testflag=param.testflag;
bool optimize_done= !do_optimize, statistics_done=0;
const char *old_proc_info=thd->proc_info;
char fixed_name[FN_REFLEN];
MYISAM_SHARE* share = file->s;
ha_rows rows= file->state->records;
DBUG_ENTER("ha_myisam::repair");
param.db_name= table->s->db.str;
param.table_name= table->alias;
param.using_global_keycache = 1;
param.thd= thd;
param.tmpdir= &mysql_tmpdir_list;
param.out_flag= 0;
strmov(fixed_name,file->filename);
// Release latches since this can take a long time
ha_release_temporary_latches(thd);
// Don't lock tables if we have used LOCK TABLE
if (! thd->locked_tables_mode &&
mi_lock_database(file, table->s->tmp_table ? F_EXTRA_LCK : F_WRLCK))
{
mi_check_print_error(¶m,ER(ER_CANT_LOCK),my_errno);
DBUG_RETURN(HA_ADMIN_FAILED);
}
if (!do_optimize ||
((file->state->del || share->state.split != file->state->records) &&
(!(param.testflag & T_QUICK) ||
!(share->state.changed & STATE_NOT_OPTIMIZED_KEYS))))
{
ulonglong key_map= ((local_testflag & T_CREATE_MISSING_KEYS) ?
mi_get_mask_all_keys_active(share->base.keys) :
share->state.key_map);
uint testflag=param.testflag;
#ifdef HAVE_MMAP
bool remap= test(share->file_map);
/*
mi_repair*() functions family use file I/O even if memory
mapping is available.
Since mixing mmap I/O and file I/O may cause various artifacts,
memory mapping must be disabled.
*/
if (remap)
mi_munmap_file(file);
#endif
if (mi_test_if_sort_rep(file,file->state->records,key_map,0) &&
(local_testflag & T_REP_BY_SORT))
{
local_testflag|= T_STATISTICS;
param.testflag|= T_STATISTICS; // We get this for free
statistics_done=1;
if (THDVAR(thd, repair_threads)>1)
{
char buf[40];
/* TODO: respect myisam_repair_threads variable */
my_snprintf(buf, 40, "Repair with %d threads", my_count_bits(key_map));
thd_proc_info(thd, buf);
error = mi_repair_parallel(¶m, file, fixed_name,
param.testflag & T_QUICK);
thd_proc_info(thd, "Repair done"); // to reset proc_info, as
// it was pointing to local buffer
}
else
{
thd_proc_info(thd, "Repair by sorting");
error = mi_repair_by_sort(¶m, file, fixed_name,
param.testflag & T_QUICK);
}
}
else
{
thd_proc_info(thd, "Repair with keycache");
param.testflag &= ~T_REP_BY_SORT;
error= mi_repair(¶m, file, fixed_name,
param.testflag & T_QUICK);
}
#ifdef HAVE_MMAP
if (remap)
mi_dynmap_file(file, file->state->data_file_length);
#endif
param.testflag=testflag;
optimize_done=1;
}
if (!error)
{
if ((local_testflag & T_SORT_INDEX) &&
(share->state.changed & STATE_NOT_SORTED_PAGES))
{
optimize_done=1;
thd_proc_info(thd, "Sorting index");
error=mi_sort_index(¶m,file,fixed_name);
}
if (!statistics_done && (local_testflag & T_STATISTICS))
{
if (share->state.changed & STATE_NOT_ANALYZED)
{
optimize_done=1;
thd_proc_info(thd, "Analyzing");
error = chk_key(¶m, file);
}
else
local_testflag&= ~T_STATISTICS; // Don't update statistics
}
}
thd_proc_info(thd, "Saving state");
if (!error)
{
if ((share->state.changed & STATE_CHANGED) || mi_is_crashed(file))
{
share->state.changed&= ~(STATE_CHANGED | STATE_CRASHED |
STATE_CRASHED_ON_REPAIR);
file->update|=HA_STATE_CHANGED | HA_STATE_ROW_CHANGED;
}
/*
the following 'if', thought conceptually wrong,
is a useful optimization nevertheless.
*/
if (file->state != &file->s->state.state)
file->s->state.state = *file->state;
if (file->s->base.auto_key)
update_auto_increment_key(¶m, file, 1);
if (optimize_done)
error = update_state_info(¶m, file,
UPDATE_TIME | UPDATE_OPEN_COUNT |
(local_testflag &
T_STATISTICS ? UPDATE_STAT : 0));
info(HA_STATUS_NO_LOCK | HA_STATUS_TIME | HA_STATUS_VARIABLE |
HA_STATUS_CONST);
if (rows != file->state->records && ! (param.testflag & T_VERY_SILENT))
{
char llbuff[22],llbuff2[22];
mi_check_print_warning(¶m,"Number of rows changed from %s to %s",
llstr(rows,llbuff),
llstr(file->state->records,llbuff2));
}
}
else
{
mi_mark_crashed_on_repair(file);
file->update |= HA_STATE_CHANGED | HA_STATE_ROW_CHANGED;
update_state_info(¶m, file, 0);
}
thd_proc_info(thd, old_proc_info);
if (! thd->locked_tables_mode)
mi_lock_database(file,F_UNLCK);
DBUG_RETURN(error ? HA_ADMIN_FAILED :
!optimize_done ? HA_ADMIN_ALREADY_DONE : HA_ADMIN_OK);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'Bug#24388746: PRIVILEGE ESCALATION AND RACE CONDITION USING CREATE TABLE
During REPAIR TABLE of a MyISAM table, a temporary data file (.TMD)
is created. When repair finishes, this file is renamed to the original
.MYD file. The problem was that during this rename, we copied the
stats from the old file to the new file with chmod/chown. If a user
managed to replace the temporary file before chmod/chown was executed,
it was possible to get an arbitrary file with the privileges of the
mysql user.
This patch fixes the problem by not copying stats from the old
file to the new file. This is not needed as the new file was
created with the correct stats. This fix only changes server
behavior - external utilities such as myisamchk still does
chmod/chown.
No test case provided since the problem involves synchronization
with file system operations.'</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 mi_repair_by_sort(MI_CHECK *param, register MI_INFO *info,
const char * name, int rep_quick)
{
int got_error;
uint i;
ulong length;
ha_rows start_records;
my_off_t new_header_length,del;
File new_file;
MI_SORT_PARAM sort_param;
MYISAM_SHARE *share=info->s;
HA_KEYSEG *keyseg;
ulong *rec_per_key_part;
char llbuff[22];
SORT_INFO sort_info;
ulonglong UNINIT_VAR(key_map);
DBUG_ENTER("mi_repair_by_sort");
start_records=info->state->records;
got_error=1;
new_file= -1;
new_header_length=(param->testflag & T_UNPACK) ? 0 :
share->pack.header_length;
if (!(param->testflag & T_SILENT))
{
printf("- recovering (with sort) MyISAM-table '%s'\n",name);
printf("Data records: %s\n", llstr(start_records,llbuff));
}
param->testflag|=T_REP; /* for easy checking */
if (info->s->options & (HA_OPTION_CHECKSUM | HA_OPTION_COMPRESS_RECORD))
param->testflag|=T_CALC_CHECKSUM;
bzero((char*)&sort_info,sizeof(sort_info));
bzero((char *)&sort_param, sizeof(sort_param));
if (!(sort_info.key_block=
alloc_key_blocks(param,
(uint) param->sort_key_blocks,
share->base.max_key_block_length))
|| init_io_cache(¶m->read_cache,info->dfile,
(uint) param->read_buffer_length,
READ_CACHE,share->pack.header_length,1,MYF(MY_WME)) ||
(! rep_quick &&
init_io_cache(&info->rec_cache,info->dfile,
(uint) param->write_buffer_length,
WRITE_CACHE,new_header_length,1,
MYF(MY_WME | MY_WAIT_IF_FULL) & param->myf_rw)))
goto err;
sort_info.key_block_end=sort_info.key_block+param->sort_key_blocks;
info->opt_flag|=WRITE_CACHE_USED;
info->rec_cache.file=info->dfile; /* for sort_delete_record */
if (!mi_alloc_rec_buff(info, -1, &sort_param.record) ||
!mi_alloc_rec_buff(info, -1, &sort_param.rec_buff))
{
mi_check_print_error(param, "Not enough memory for extra record");
goto err;
}
if (!rep_quick)
{
/* Get real path for data file */
if ((new_file= mysql_file_create(mi_key_file_datatmp,
fn_format(param->temp_filename,
share->data_file_name, "",
DATA_TMP_EXT, 2+4),
0, param->tmpfile_createflag,
MYF(0))) < 0)
{
mi_check_print_error(param,"Can't create new tempfile: '%s'",
param->temp_filename);
goto err;
}
if (new_header_length &&
filecopy(param, new_file,info->dfile,0L,new_header_length,
"datafile-header"))
goto err;
if (param->testflag & T_UNPACK)
{
share->options&= ~HA_OPTION_COMPRESS_RECORD;
mi_int2store(share->state.header.options,share->options);
}
share->state.dellink= HA_OFFSET_ERROR;
info->rec_cache.file=new_file;
}
info->update= (short) (HA_STATE_CHANGED | HA_STATE_ROW_CHANGED);
/* Optionally drop indexes and optionally modify the key_map. */
mi_drop_all_indexes(param, info, FALSE);
key_map= share->state.key_map;
if (param->testflag & T_CREATE_MISSING_KEYS)
{
/* Invert the copied key_map to recreate all disabled indexes. */
key_map= ~key_map;
}
sort_info.info=info;
sort_info.param = param;
set_data_file_type(&sort_info, share);
sort_param.filepos=new_header_length;
sort_info.dupp=0;
sort_info.buff=0;
param->read_cache.end_of_file=sort_info.filelength=
mysql_file_seek(param->read_cache.file, 0L, MY_SEEK_END, MYF(0));
sort_param.wordlist=NULL;
init_alloc_root(&sort_param.wordroot, FTPARSER_MEMROOT_ALLOC_SIZE, 0);
if (share->data_file_type == DYNAMIC_RECORD)
length=max(share->base.min_pack_length+1,share->base.min_block_length);
else if (share->data_file_type == COMPRESSED_RECORD)
length=share->base.min_block_length;
else
length=share->base.pack_reclength;
sort_info.max_records=
((param->testflag & T_CREATE_MISSING_KEYS) ? info->state->records :
(ha_rows) (sort_info.filelength/length+1));
sort_param.key_cmp=sort_key_cmp;
sort_param.lock_in_memory=lock_memory;
sort_param.tmpdir=param->tmpdir;
sort_param.sort_info=&sort_info;
sort_param.fix_datafile= (my_bool) (! rep_quick);
sort_param.master =1;
del=info->state->del;
param->glob_crc=0;
if (param->testflag & T_CALC_CHECKSUM)
sort_param.calc_checksum= 1;
rec_per_key_part= param->rec_per_key_part;
for (sort_param.key=0 ; sort_param.key < share->base.keys ;
rec_per_key_part+=sort_param.keyinfo->keysegs, sort_param.key++)
{
sort_param.read_cache=param->read_cache;
sort_param.keyinfo=share->keyinfo+sort_param.key;
sort_param.seg=sort_param.keyinfo->seg;
/*
Skip this index if it is marked disabled in the copied
(and possibly inverted) key_map.
*/
if (! mi_is_key_active(key_map, sort_param.key))
{
/* Remember old statistics for key */
memcpy((char*) rec_per_key_part,
(char*) (share->state.rec_per_key_part +
(uint) (rec_per_key_part - param->rec_per_key_part)),
sort_param.keyinfo->keysegs*sizeof(*rec_per_key_part));
DBUG_PRINT("repair", ("skipping seemingly disabled index #: %u",
sort_param.key));
continue;
}
if ((!(param->testflag & T_SILENT)))
printf ("- Fixing index %d\n",sort_param.key+1);
sort_param.max_pos=sort_param.pos=share->pack.header_length;
keyseg=sort_param.seg;
bzero((char*) sort_param.unique,sizeof(sort_param.unique));
sort_param.key_length=share->rec_reflength;
for (i=0 ; keyseg[i].type != HA_KEYTYPE_END; i++)
{
sort_param.key_length+=keyseg[i].length;
if (keyseg[i].flag & HA_SPACE_PACK)
sort_param.key_length+=get_pack_length(keyseg[i].length);
if (keyseg[i].flag & (HA_BLOB_PART | HA_VAR_LENGTH_PART))
sort_param.key_length+=2 + test(keyseg[i].length >= 127);
if (keyseg[i].flag & HA_NULL_PART)
sort_param.key_length++;
}
info->state->records=info->state->del=share->state.split=0;
info->state->empty=0;
if (sort_param.keyinfo->flag & HA_FULLTEXT)
{
uint ft_max_word_len_for_sort=FT_MAX_WORD_LEN_FOR_SORT*
sort_param.keyinfo->seg->charset->mbmaxlen;
sort_param.key_length+=ft_max_word_len_for_sort-HA_FT_MAXBYTELEN;
/*
fulltext indexes may have much more entries than the
number of rows in the table. We estimate the number here.
*/
if (sort_param.keyinfo->parser == &ft_default_parser)
{
/*
for built-in parser the number of generated index entries
cannot be larger than the size of the data file divided
by the minimal word's length
*/
sort_info.max_records=
(ha_rows) (sort_info.filelength/ft_min_word_len+1);
}
else
{
/*
for external plugin parser we cannot tell anything at all :(
so, we'll use all the sort memory and start from ~10 buffpeks.
(see _create_index_by_sort)
*/
sort_info.max_records= 10 *
max(param->sort_buffer_length, MIN_SORT_BUFFER) /
sort_param.key_length;
}
sort_param.key_read=sort_ft_key_read;
sort_param.key_write=sort_ft_key_write;
}
else
{
sort_param.key_read=sort_key_read;
sort_param.key_write=sort_key_write;
}
if (_create_index_by_sort(&sort_param,
(my_bool) (!(param->testflag & T_VERBOSE)),
param->sort_buffer_length))
{
param->retry_repair=1;
goto err;
}
/* No need to calculate checksum again. */
sort_param.calc_checksum= 0;
free_root(&sort_param.wordroot, MYF(0));
/* Set for next loop */
sort_info.max_records= (ha_rows) info->state->records;
if (param->testflag & T_STATISTICS)
update_key_parts(sort_param.keyinfo, rec_per_key_part, sort_param.unique,
param->stats_method == MI_STATS_METHOD_IGNORE_NULLS?
sort_param.notnull: NULL,
(ulonglong) info->state->records);
/* Enable this index in the permanent (not the copied) key_map. */
mi_set_key_active(share->state.key_map, sort_param.key);
DBUG_PRINT("repair", ("set enabled index #: %u", sort_param.key));
if (sort_param.fix_datafile)
{
param->read_cache.end_of_file=sort_param.filepos;
if (write_data_suffix(&sort_info,1) || end_io_cache(&info->rec_cache))
goto err;
if (param->testflag & T_SAFE_REPAIR)
{
/* Don't repair if we loosed more than one row */
if (info->state->records+1 < start_records)
{
info->state->records=start_records;
goto err;
}
}
share->state.state.data_file_length = info->state->data_file_length=
sort_param.filepos;
/* Only whole records */
share->state.version=(ulong) time((time_t*) 0);
mysql_file_close(info->dfile, MYF(0));
info->dfile=new_file;
share->data_file_type=sort_info.new_data_file_type;
share->pack.header_length=(ulong) new_header_length;
sort_param.fix_datafile=0;
}
else
info->state->data_file_length=sort_param.max_pos;
param->read_cache.file=info->dfile; /* re-init read cache */
reinit_io_cache(¶m->read_cache,READ_CACHE,share->pack.header_length,
1,1);
}
if (param->testflag & T_WRITE_LOOP)
{
(void) fputs(" \r",stdout); (void) fflush(stdout);
}
if (rep_quick && del+sort_info.dupp != info->state->del)
{
mi_check_print_error(param,"Couldn't fix table with quick recovery: Found wrong number of deleted records");
mi_check_print_error(param,"Run recovery again without -q");
got_error=1;
param->retry_repair=1;
param->testflag|=T_RETRY_WITHOUT_QUICK;
goto err;
}
if (rep_quick & T_FORCE_UNIQUENESS)
{
my_off_t skr=info->state->data_file_length+
(share->options & HA_OPTION_COMPRESS_RECORD ?
MEMMAP_EXTRA_MARGIN : 0);
#ifdef USE_RELOC
if (share->data_file_type == STATIC_RECORD &&
skr < share->base.reloc*share->base.min_pack_length)
skr=share->base.reloc*share->base.min_pack_length;
#endif
if (skr != sort_info.filelength)
if (mysql_file_chsize(info->dfile, skr, 0, MYF(0)))
mi_check_print_warning(param,
"Can't change size of datafile, error: %d",
my_errno);
}
if (param->testflag & T_CALC_CHECKSUM)
info->state->checksum=param->glob_crc;
if (mysql_file_chsize(share->kfile, info->state->key_file_length, 0, MYF(0)))
mi_check_print_warning(param,
"Can't change size of indexfile, error: %d",
my_errno);
if (!(param->testflag & T_SILENT))
{
if (start_records != info->state->records)
printf("Data records: %s\n", llstr(info->state->records,llbuff));
if (sort_info.dupp)
mi_check_print_warning(param,
"%s records have been removed",
llstr(sort_info.dupp,llbuff));
}
got_error=0;
if (&share->state.state != info->state)
memcpy( &share->state.state, info->state, sizeof(*info->state));
err:
got_error|= flush_blocks(param, share->key_cache, share->kfile);
(void) end_io_cache(&info->rec_cache);
if (!got_error)
{
/* Replace the actual file with the temporary file */
if (new_file >= 0)
{
mysql_file_close(new_file, MYF(0));
info->dfile=new_file= -1;
if (change_to_newfile(share->data_file_name,MI_NAME_DEXT, DATA_TMP_EXT,
(param->testflag & T_BACKUP_DATA ?
MYF(MY_REDEL_MAKE_BACKUP): MYF(0))) ||
mi_open_datafile(info,share,name,-1))
got_error=1;
}
}
if (got_error)
{
if (! param->error_printed)
mi_check_print_error(param,"%d when fixing table",my_errno);
if (new_file >= 0)
{
(void) mysql_file_close(new_file, MYF(0));
(void) mysql_file_delete(mi_key_file_datatmp,
param->temp_filename, MYF(MY_WME));
if (info->dfile == new_file) /* Retry with key cache */
if (unlikely(mi_open_datafile(info, share, name, -1)))
param->retry_repair= 0; /* Safety */
}
mi_mark_crashed_on_repair(info);
}
else if (key_map == share->state.key_map)
share->state.changed&= ~STATE_NOT_OPTIMIZED_KEYS;
share->state.changed|=STATE_NOT_SORTED_PAGES;
my_free(mi_get_rec_buff_ptr(info, sort_param.rec_buff));
my_free(mi_get_rec_buff_ptr(info, sort_param.record));
my_free(sort_info.key_block);
my_free(sort_info.ft_buf);
my_free(sort_info.buff);
(void) end_io_cache(¶m->read_cache);
info->opt_flag&= ~(READ_CACHE_USED | WRITE_CACHE_USED);
if (!got_error && (param->testflag & T_UNPACK))
{
share->state.header.options[0]&= (uchar) ~HA_OPTION_COMPRESS_RECORD;
share->pack.header_length=0;
}
DBUG_RETURN(got_error);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-362'], 'message': 'Bug#24388746: PRIVILEGE ESCALATION AND RACE CONDITION USING CREATE TABLE
During REPAIR TABLE of a MyISAM table, a temporary data file (.TMD)
is created. When repair finishes, this file is renamed to the original
.MYD file. The problem was that during this rename, we copied the
stats from the old file to the new file with chmod/chown. If a user
managed to replace the temporary file before chmod/chown was executed,
it was possible to get an arbitrary file with the privileges of the
mysql user.
This patch fixes the problem by not copying stats from the old
file to the new file. This is not needed as the new file was
created with the correct stats. This fix only changes server
behavior - external utilities such as myisamchk still does
chmod/chown.
No test case provided since the problem involves synchronization
with file system operations.'</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 ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size)
{
struct xlx_ethlite *s = qemu_get_nic_opaque(nc);
unsigned int rxbase = s->rxbuf * (0x800 / 4);
/* DA filter. */
if (!(buf[0] & 0x80) && memcmp(&s->conf.macaddr.a[0], buf, 6))
return size;
if (s->regs[rxbase + R_RX_CTRL0] & CTRL_S) {
D(qemu_log("ethlite lost packet %x\n", s->regs[R_RX_CTRL0]));
return -1;
}
D(qemu_log("%s %zd rxbase=%x\n", __func__, size, rxbase));
memcpy(&s->regs[rxbase + R_RX_BUF0], buf, size);
s->regs[rxbase + R_RX_CTRL0] |= CTRL_S;
if (s->regs[R_RX_CTRL0] & CTRL_I) {
eth_pulse_irq(s);
}
/* If c_rx_pingpong was set flip buffers. */
s->rxbuf ^= s->c_rx_pingpong;
return size;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'hw/net: Fix a heap overflow in xlnx.xps-ethernetlite
The .receive callback of xlnx.xps-ethernetlite doesn't check the length
of data before calling memcpy. As a result, the NetClientState object in
heap will be overflowed. All versions of qemu with xlnx.xps-ethernetlite
will be affected.
Reported-by: chaojianhu <[email protected]>
Signed-off-by: chaojianhu <[email protected]>
Signed-off-by: Jason Wang <[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 *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
SGIInfo
iris_info;
size_t
bytes_per_pixel,
quantum;
ssize_t
count,
y,
z;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SGI raster header.
*/
iris_info.magic=ReadBlobMSBShort(image);
do
{
/*
Verify SGI identifier.
*/
if (iris_info.magic != 0x01DA)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.storage=(unsigned char) ReadBlobByte(image);
switch (iris_info.storage)
{
case 0x00: image->compression=NoCompression; break;
case 0x01: image->compression=RLECompression; break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image);
if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.dimension=ReadBlobMSBShort(image);
iris_info.columns=ReadBlobMSBShort(image);
iris_info.rows=ReadBlobMSBShort(image);
iris_info.depth=ReadBlobMSBShort(image);
if ((iris_info.depth == 0) || (iris_info.depth > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.minimum_value=ReadBlobMSBLong(image);
iris_info.maximum_value=ReadBlobMSBLong(image);
iris_info.sans=ReadBlobMSBLong(image);
(void) ReadBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
iris_info.name[sizeof(iris_info.name)-1]='\0';
if (*iris_info.name != '\0')
(void) SetImageProperty(image,"label",iris_info.name,exception);
iris_info.pixel_format=ReadBlobMSBLong(image);
if (iris_info.pixel_format != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler);
(void) count;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.pixel_format == 0)
image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,
MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.depth < 3)
{
image->storage_class=PseudoClass;
image->colors=iris_info.bytes_per_pixel > 1 ? 65535 : 256;
}
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
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 SGI pixels.
*/
bytes_per_pixel=(size_t) iris_info.bytes_per_pixel;
number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows;
if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t)
(4*bytes_per_pixel*number_pixels)))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((int) iris_info.storage != 0x01)
{
unsigned char
*scanline;
/*
Read standard image format.
*/
scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns,
bytes_per_pixel*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels+bytes_per_pixel*z;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline);
if (EOFBlob(image) != MagickFalse)
break;
if (bytes_per_pixel == 2)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[2*x];
*(p+1)=scanline[2*x+1];
p+=8;
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[x];
p+=4;
}
}
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
}
else
{
MemoryInfo
*packet_info;
size_t
*runlength;
ssize_t
offset,
*offsets;
unsigned char
*packets;
unsigned int
data_order;
/*
Read runlength-encoded image format.
*/
offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL*
sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets == (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength == (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info == (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
offsets[i]=ReadBlobMSBSignedLong(image);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
{
runlength[i]=ReadBlobMSBLong(image);
if (runlength[i] > (4*(size_t) iris_info.columns+10))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Check data order.
*/
offset=0;
data_order=0;
for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++)
for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++)
{
if (offsets[y+z*iris_info.rows] < offset)
data_order=1;
offset=offsets[y+z*iris_info.rows];
}
offset=(ssize_t) TellBlob(image);
if (data_order == 1)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
p+=(iris_info.columns*4*bytes_per_pixel);
}
}
}
else
{
MagickOffsetType
position;
position=TellBlob(image);
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
p+=(iris_info.columns*4*bytes_per_pixel);
}
offset=(ssize_t) SeekBlob(image,position,SEEK_SET);
}
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
}
/*
Initialize image structure.
*/
image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
/*
Convert SGI raster image to pixel packets.
*/
if (image->storage_class == DirectClass)
{
/*
Convert SGI image to DirectClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleShortToQuantum((unsigned short)
((*(p+0) << 8) | (*(p+1)))),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short)
((*(p+2) << 8) | (*(p+3)))),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short)
((*(p+4) << 8) | (*(p+5)))),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleShortToQuantum((unsigned short)
((*(p+6) << 8) | (*(p+7)))),q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create grayscale map.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert SGI image to PseudoClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=(*p << 8);
quantum|=(*(p+1));
SetPixelIndex(image,(Quantum) quantum,q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p,q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
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;
iris_info.magic=ReadBlobMSBShort(image);
if (iris_info.magic == 0x01DA)
{
/*
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 (iris_info.magic == 0x01DA);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-125'], '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: static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
format;
double
quantum_scale;
Image
*image;
MagickBooleanType
status;
QuantumAny
max_value;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
depth,
extent,
packet_size;
ssize_t
count,
row,
y;
/*
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 PNM image.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
do
{
/*
Initialize image structure.
*/
if ((count != 1) || (format != 'P'))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=1;
quantum_type=RGBQuantum;
quantum_scale=1.0;
format=(char) ReadBlobByte(image);
if (format != '7')
{
/*
PBM, PGM, PPM, and PNM.
*/
image->columns=(size_t) PNMInteger(image,10,exception);
image->rows=(size_t) PNMInteger(image,10,exception);
if ((format == 'f') || (format == 'F'))
{
char
scale[MagickPathExtent];
(void) ReadBlobString(image,scale);
quantum_scale=StringToDouble(scale,(char **) NULL);
}
else
{
if ((format == '1') || (format == '4'))
max_value=1; /* bitmap */
else
max_value=(QuantumAny) PNMInteger(image,10,exception);
}
}
else
{
char
keyword[MagickPathExtent],
value[MagickPathExtent];
int
c;
register char
*p;
/*
PAM.
*/
for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
{
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
if (c == '#')
{
/*
Comment.
*/
c=PNMComment(image,exception);
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
p=keyword;
do
{
if ((size_t) (p-keyword) < (MagickPathExtent-1))
*p++=c;
c=ReadBlobByte(image);
} while (isalnum(c));
*p='\0';
if (LocaleCompare(keyword,"endhdr") == 0)
break;
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
p=value;
while (isalnum(c) || (c == '_'))
{
if ((size_t) (p-value) < (MagickPathExtent-1))
*p++=c;
c=ReadBlobByte(image);
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
if (LocaleCompare(keyword,"depth") == 0)
packet_size=StringToUnsignedLong(value);
(void) packet_size;
if (LocaleCompare(keyword,"height") == 0)
image->rows=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"maxval") == 0)
max_value=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"TUPLTYPE") == 0)
{
if (LocaleCompare(value,"BLACKANDWHITE") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=GrayQuantum;
}
if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=BlendPixelTrait;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"GRAYSCALE") == 0)
{
quantum_type=GrayQuantum;
(void) SetImageColorspace(image,GRAYColorspace,exception);
}
if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0)
{
(void) SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=BlendPixelTrait;
quantum_type=GrayAlphaQuantum;
}
if (LocaleCompare(value,"RGB_ALPHA") == 0)
{
image->alpha_trait=BlendPixelTrait;
quantum_type=RGBAQuantum;
}
if (LocaleCompare(value,"CMYK") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace,exception);
quantum_type=CMYKQuantum;
}
if (LocaleCompare(value,"CMYK_ALPHA") == 0)
{
(void) SetImageColorspace(image,CMYKColorspace,exception);
image->alpha_trait=BlendPixelTrait;
quantum_type=CMYKAQuantum;
}
}
if (LocaleCompare(keyword,"width") == 0)
image->columns=StringToUnsignedLong(value);
}
}
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
if ((max_value == 0) || (max_value > 4294967295))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
for (depth=1; GetQuantumRange(depth) < max_value; depth++) ;
image->depth=depth;
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));
/*
Convert PNM pixels to runextent-encoded MIFF packets.
*/
row=0;
switch (format)
{
case '1':
{
/*
Convert PBM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelGray(image,PNMInteger(image,2,exception) == 0 ?
QuantumRange : 0,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;
}
}
image->type=BilevelType;
break;
}
case '2':
{
Quantum
intensity;
/*
Convert PGM image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
intensity=ScaleAnyToQuantum(PNMInteger(image,10,exception),
max_value);
SetPixelGray(image,intensity,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;
}
}
image->type=GrayscaleType;
break;
}
case '3':
{
/*
Convert PNM image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
Quantum
pixel;
pixel=ScaleAnyToQuantum(PNMInteger(image,10,exception),max_value);
SetPixelRed(image,pixel,q);
pixel=ScaleAnyToQuantum(PNMInteger(image,10,exception),max_value);
SetPixelGreen(image,pixel,q);
pixel=ScaleAnyToQuantum(PNMInteger(image,10,exception),max_value);
SetPixelBlue(image,pixel,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;
}
}
break;
}
case '4':
{
/*
Convert PBM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=GrayQuantum;
if (image->storage_class == PseudoClass)
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumMinIsWhite(quantum_info,MagickTrue);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
ssize_t
count,
offset;
size_t
length;
if (status == MagickFalse)
continue;
pixels=(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);
if (length != extent)
status=MagickFalse;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
SetQuantumImageType(image,quantum_type);
break;
}
case '5':
{
/*
Convert PGM raw image to pixel packets.
*/
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=GrayQuantum;
if (image->depth <= 8)
extent=image->columns;
else
if (image->depth <= 16)
extent=2*image->columns;
else
extent=4*image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
count,
offset;
if (status == MagickFalse)
continue;
pixels=(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;
}
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
q+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
q+=GetPixelChannels(image);
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
SetQuantumImageType(image,quantum_type);
break;
}
case '6':
{
/*
Convert PNM raster image to pixel packets.
*/
quantum_type=RGBQuantum;
extent=3*(image->depth <= 8 ? 1 : 2)*image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
count,
offset;
if (status == MagickFalse)
continue;
pixels=(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;
}
p=pixels;
switch (image->depth)
{
case 8:
{
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
break;
}
case '7':
{
size_t
channels;
/*
Convert PAM raster image to pixel packets.
*/
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
channels=1;
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
channels=4;
break;
}
default:
{
channels=3;
break;
}
}
if (image->alpha_trait != UndefinedPixelTrait)
channels++;
if (image->depth <= 8)
extent=channels*image->columns;
else
if (image->depth <= 16)
extent=2*channels*image->columns;
else
extent=4*channels*image->columns;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
count,
offset;
if (status == MagickFalse)
continue;
pixels=(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;
}
p=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushCharPixel(p,&pixel);
if (image->depth != 1)
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
else
SetPixelAlpha(image,QuantumRange-
ScaleAnyToQuantum(pixel,max_value),q);
}
q+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,max_value),
q);
}
q+=GetPixelChannels(image);
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushCharPixel(p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,max_value),
q);
}
q+=GetPixelChannels(image);
}
break;
}
default:
{
unsigned int
pixel;
if (image->depth <= 8)
{
unsigned char
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),
q);
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),
q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushShortPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,
max_value),q);
}
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q);
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
p=PushLongPixel(MSBEndian,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,max_value),
q);
}
q+=GetPixelChannels(image);
}
break;
}
}
}
}
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
SetQuantumImageType(image,quantum_type);
break;
}
case 'F':
case 'f':
{
/*
Convert PFM raster image to pixel packets.
*/
if (format == 'f')
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian;
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumDepth(image,quantum_info,32);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumScale(quantum_info,(double) QuantumRange*fabs(quantum_scale));
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
const unsigned char
*pixels;
MagickBooleanType
sync;
register Quantum
*magick_restrict q;
ssize_t
count,
offset;
size_t
length;
if (status == MagickFalse)
continue;
pixels=(unsigned char *) ReadBlobStream(image,extent,
GetQuantumPixels(quantum_info),&count);
if ((size_t) count != 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,(ssize_t) (image->rows-offset-1),
image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (length != extent)
status=MagickFalse;
sync=SyncAuthenticPixels(image,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
SetQuantumImageType(image,quantum_type);
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (EOFBlob(image) != MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"UnexpectedEndOfFile","`%s'",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 ((format == '1') || (format == '2') || (format == '3'))
do
{
/*
Skip to end of line.
*/
count=ReadBlob(image,1,(unsigned char *) &format);
if (count != 1)
break;
if (format == 'P')
break;
} while (format != '\n');
count=ReadBlob(image,1,(unsigned char *) &format);
if ((count == 1) && (format == 'P'))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count == 1) && (format == 'P'));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-190'], 'message': 'Earlier check for EOF'</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 manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
_cleanup_fdset_free_ FDSet *fds = NULL;
Manager *m = userdata;
char buf[NOTIFY_BUFFER_MAX+1];
struct iovec iovec = {
.iov_base = buf,
.iov_len = sizeof(buf)-1,
};
union {
struct cmsghdr cmsghdr;
uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
CMSG_SPACE(sizeof(int) * NOTIFY_FD_MAX)];
} control = {};
struct msghdr msghdr = {
.msg_iov = &iovec,
.msg_iovlen = 1,
.msg_control = &control,
.msg_controllen = sizeof(control),
};
struct cmsghdr *cmsg;
struct ucred *ucred = NULL;
bool found = false;
Unit *u1, *u2, *u3;
int r, *fd_array = NULL;
unsigned n_fds = 0;
ssize_t n;
assert(m);
assert(m->notify_fd == fd);
if (revents != EPOLLIN) {
log_warning("Got unexpected poll event for notify fd.");
return 0;
}
n = recvmsg(m->notify_fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
if (n < 0) {
if (errno == EAGAIN || errno == EINTR)
return 0;
return -errno;
}
if (n == 0) {
log_debug("Got zero-length notification message. Ignoring.");
return 0;
}
CMSG_FOREACH(cmsg, &msghdr) {
if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
fd_array = (int*) CMSG_DATA(cmsg);
n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
} else if (cmsg->cmsg_level == SOL_SOCKET &&
cmsg->cmsg_type == SCM_CREDENTIALS &&
cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
ucred = (struct ucred*) CMSG_DATA(cmsg);
}
}
if (n_fds > 0) {
assert(fd_array);
r = fdset_new_array(&fds, fd_array, n_fds);
if (r < 0) {
close_many(fd_array, n_fds);
return log_oom();
}
}
if (!ucred || ucred->pid <= 0) {
log_warning("Received notify message without valid credentials. Ignoring.");
return 0;
}
if ((size_t) n >= sizeof(buf)) {
log_warning("Received notify message exceeded maximum size. Ignoring.");
return 0;
}
buf[n] = 0;
/* Notify every unit that might be interested, but try
* to avoid notifying the same one multiple times. */
u1 = manager_get_unit_by_pid_cgroup(m, ucred->pid);
if (u1) {
manager_invoke_notify_message(m, u1, ucred->pid, buf, n, fds);
found = true;
}
u2 = hashmap_get(m->watch_pids1, PID_TO_PTR(ucred->pid));
if (u2 && u2 != u1) {
manager_invoke_notify_message(m, u2, ucred->pid, buf, n, fds);
found = true;
}
u3 = hashmap_get(m->watch_pids2, PID_TO_PTR(ucred->pid));
if (u3 && u3 != u2 && u3 != u1) {
manager_invoke_notify_message(m, u3, ucred->pid, buf, n, fds);
found = true;
}
if (!found)
log_warning("Cannot find unit for notify message of PID "PID_FMT".", ucred->pid);
if (fdset_size(fds) > 0)
log_warning("Got auxiliary fds with notification message, closing all.");
return 0;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'pid1: don't return any error in manager_dispatch_notify_fd() (#4240)
If manager_dispatch_notify_fd() fails and returns an error then the handling of
service notifications will be disabled entirely leading to a compromised system.
For example pid1 won't be able to receive the WATCHDOG messages anymore and
will kill all services supposed to send such messages.'</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 manager_invoke_notify_message(Manager *m, Unit *u, pid_t pid, const char *buf, size_t n, FDSet *fds) {
_cleanup_strv_free_ char **tags = NULL;
assert(m);
assert(u);
assert(buf);
assert(n > 0);
tags = strv_split(buf, "\n\r");
if (!tags) {
log_oom();
return;
}
if (UNIT_VTABLE(u)->notify_message)
UNIT_VTABLE(u)->notify_message(u, pid, tags, fds);
else
log_unit_debug(u, "Got notification message for unit. Ignoring.");
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-20'], 'message': 'pid1: process zero-length notification messages again
This undoes 531ac2b234. I acked that patch without looking at the code
carefully enough. There are two problems:
- we want to process the fds anyway
- in principle empty notification messages are valid, and we should
process them as usual, including logging using log_unit_debug().'</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 dbd_bind_ph(SV *sth, imp_sth_t *imp_sth, SV *param, SV *value,
IV sql_type, SV *attribs, int is_inout, IV maxlen) {
dTHX;
int rc;
int param_num= SvIV(param);
int idx= param_num - 1;
char err_msg[64];
D_imp_xxh(sth);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
STRLEN slen;
char *buffer= NULL;
int buffer_is_null= 0;
int buffer_length= slen;
unsigned int buffer_type= 0;
IV tmp;
#endif
D_imp_dbh_from_sth;
ASYNC_CHECK_RETURN(sth, FALSE);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" Called: dbd_bind_ph\n");
attribs= attribs;
maxlen= maxlen;
if (param_num <= 0 || param_num > DBIc_NUM_PARAMS(imp_sth))
{
do_error(sth, JW_ERR_ILLEGAL_PARAM_NUM, "Illegal parameter number", NULL);
return FALSE;
}
/*
This fixes the bug whereby no warning was issued upon binding a
defined non-numeric as numeric
*/
if (SvOK(value) &&
(sql_type == SQL_NUMERIC ||
sql_type == SQL_DECIMAL ||
sql_type == SQL_INTEGER ||
sql_type == SQL_SMALLINT ||
sql_type == SQL_FLOAT ||
sql_type == SQL_REAL ||
sql_type == SQL_DOUBLE) )
{
if (! looks_like_number(value))
{
sprintf(err_msg,
"Binding non-numeric field %d, value %s as a numeric!",
param_num, neatsvpv(value,0));
do_error(sth, JW_ERR_ILLEGAL_PARAM_NUM, err_msg, NULL);
}
}
if (is_inout)
{
do_error(sth, JW_ERR_NOT_IMPLEMENTED, "Output parameters not implemented", NULL);
return FALSE;
}
rc = bind_param(&imp_sth->params[idx], value, sql_type);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare)
{
switch(sql_type) {
case SQL_NUMERIC:
case SQL_INTEGER:
case SQL_SMALLINT:
case SQL_BIGINT:
case SQL_TINYINT:
buffer_type= MYSQL_TYPE_LONG;
break;
case SQL_DOUBLE:
case SQL_DECIMAL:
case SQL_FLOAT:
case SQL_REAL:
buffer_type= MYSQL_TYPE_DOUBLE;
break;
case SQL_CHAR:
case SQL_VARCHAR:
case SQL_DATE:
case SQL_TIME:
case SQL_TIMESTAMP:
case SQL_LONGVARCHAR:
case SQL_BINARY:
case SQL_VARBINARY:
case SQL_LONGVARBINARY:
buffer_type= MYSQL_TYPE_BLOB;
break;
default:
buffer_type= MYSQL_TYPE_STRING;
}
buffer_is_null = !(SvOK(imp_sth->params[idx].value) && imp_sth->params[idx].value);
if (! buffer_is_null) {
switch(buffer_type) {
case MYSQL_TYPE_LONG:
/* INT */
if (!SvIOK(imp_sth->params[idx].value) && DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tTRY TO BIND AN INT NUMBER\n");
buffer_length = sizeof imp_sth->fbind[idx].numeric_val.lval;
tmp = SvIV(imp_sth->params[idx].value);
if (tmp > INT32_MAX)
croak("Could not bind %ld: Integer too large for MYSQL_TYPE_LONG", tmp);
imp_sth->fbind[idx].numeric_val.lval= tmp;
buffer=(void*)&(imp_sth->fbind[idx].numeric_val.lval);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type %d ->%"PRId32"<- IS A INT NUMBER\n",
(int) sql_type, *(int32_t *)buffer);
break;
case MYSQL_TYPE_DOUBLE:
if (!SvNOK(imp_sth->params[idx].value) && DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tTRY TO BIND A FLOAT NUMBER\n");
buffer_length = sizeof imp_sth->fbind[idx].numeric_val.dval;
imp_sth->fbind[idx].numeric_val.dval= SvNV(imp_sth->params[idx].value);
buffer=(char*)&(imp_sth->fbind[idx].numeric_val.dval);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type %d ->%f<- IS A FLOAT NUMBER\n",
(int) sql_type, (double)(*buffer));
break;
case MYSQL_TYPE_BLOB:
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type BLOB\n");
break;
case MYSQL_TYPE_STRING:
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type STRING %d, buffertype=%d\n", (int) sql_type, buffer_type);
break;
default:
croak("Bug in DBD::Mysql file dbdimp.c#dbd_bind_ph: do not know how to handle unknown buffer type.");
}
if (buffer_type == MYSQL_TYPE_STRING || buffer_type == MYSQL_TYPE_BLOB)
{
buffer= SvPV(imp_sth->params[idx].value, slen);
buffer_length= slen;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type %d ->length %d<- IS A STRING or BLOB\n",
(int) sql_type, buffer_length);
}
}
else
{
/*case: buffer_is_null != 0*/
buffer= NULL;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR NULL VALUE: buffer type is: %d\n", buffer_type);
}
/* Type of column was changed. Force to rebind */
if (imp_sth->bind[idx].buffer_type != buffer_type) {
/* Note: this looks like being another bug:
* if type of parameter N changes, then a bind is triggered
* with an only partially filled bind structure ??
*/
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" FORCE REBIND: buffer type changed from %d to %d, sql-type=%d\n",
(int) imp_sth->bind[idx].buffer_type, buffer_type, (int) sql_type);
imp_sth->has_been_bound = 0;
}
/* prepare has not been called */
if (imp_sth->has_been_bound == 0)
{
imp_sth->bind[idx].buffer_type= buffer_type;
imp_sth->bind[idx].buffer= buffer;
imp_sth->bind[idx].buffer_length= buffer_length;
}
else /* prepare has been called */
{
imp_sth->stmt->params[idx].buffer= buffer;
imp_sth->stmt->params[idx].buffer_length= buffer_length;
}
imp_sth->fbind[idx].length= buffer_length;
imp_sth->fbind[idx].is_null= buffer_is_null;
}
#endif
return rc;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119'], 'message': 'Do not use unsafe sprintf w/variable length input
This can cause a buffer overflow to occur when reporting error
message about validation of (untrusted) user input parameters.'</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 startApp(QCommandLineParser& p)
{
// Stop daemon and exit?
if (p.isSet("s"))
{
KDEsuClient client;
if (client.ping() == -1)
{
qCCritical(category) << "Daemon not running -- nothing to stop\n";
p.showHelp(1);
}
if (client.stopServer() != -1)
{
qCDebug(category) << "Daemon stopped\n";
exit(0);
}
qCCritical(category) << "Could not stop daemon\n";
p.showHelp(1);
}
QString icon;
if ( p.isSet("i"))
icon = p.value("i");
bool prompt = true;
if ( p.isSet("d"))
prompt = false;
// Get target uid
QByteArray user = p.value("u").toLocal8Bit();
QByteArray auth_user = user;
struct passwd *pw = getpwnam(user);
if (pw == 0L)
{
qCCritical(category) << "User " << user << " does not exist\n";
p.showHelp(1);
}
bool other_uid = (getuid() != pw->pw_uid);
bool change_uid = other_uid;
if (!change_uid) {
char *cur_user = getenv("USER");
if (!cur_user)
cur_user = getenv("LOGNAME");
change_uid = (!cur_user || user != cur_user);
}
// If file is writeable, do not change uid
QString file = p.value("f");
if (other_uid && !file.isEmpty())
{
if (file.startsWith('/'))
{
file = QStandardPaths::locate(QStandardPaths::GenericConfigLocation, file);
if (file.isEmpty())
{
qCCritical(category) << "Config file not found: " << file;
p.showHelp(1);
}
}
QFileInfo fi(file);
if (!fi.exists())
{
qCCritical(category) << "File does not exist: " << file;
p.showHelp(1);
}
change_uid = !fi.isWritable();
}
// Get priority/scheduler
QString tmp = p.value("p");
bool ok;
int priority = tmp.toInt(&ok);
if (!ok || (priority < 0) || (priority > 100))
{
qCCritical(category) << i18n("Illegal priority: %1", tmp);
p.showHelp(1);
}
int scheduler = SuProcess::SchedNormal;
if (p.isSet("r"))
scheduler = SuProcess::SchedRealtime;
if ((priority > 50) || (scheduler != SuProcess::SchedNormal))
{
change_uid = true;
auth_user = "root";
}
// Get command
if (p.isSet("c"))
{
command = p.value("c").toLocal8Bit();
// Accepting additional arguments here is somewhat weird,
// but one can conceive use cases: have a complex command with
// redirections and additional file names which need to be quoted
// safely.
}
else
{
if( p.positionalArguments().count() == 0 )
{
qCCritical(category) << i18n("No command specified.");
p.showHelp(1);
}
}
foreach(const QString& arg, p.positionalArguments())
{
command += ' ';
command += QFile::encodeName(KShell::quoteArg(arg));
}
// Don't change uid if we're don't need to.
if (!change_uid)
{
int result = system(command);
result = WEXITSTATUS(result);
return result;
}
// Check for daemon and start if necessary
bool just_started = false;
bool have_daemon = true;
KDEsuClient client;
if (!client.isServerSGID())
{
qCWarning(category) << "Daemon not safe (not sgid), not using it.\n";
have_daemon = false;
}
else if (client.ping() == -1)
{
if (client.startServer() == -1)
{
qCWarning(category) << "Could not start daemon, reduced functionality.\n";
have_daemon = false;
}
just_started = true;
}
// Try to exec the command with kdesud.
bool keep = !p.isSet("n") && have_daemon;
bool terminal = p.isSet("t");
bool withIgnoreButton = !p.isSet("noignorebutton");
int winid = -1;
bool attach = p.isSet("attach");
if(attach) {
winid = p.value("attach").toInt(&attach, 0); //C style parsing. If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.
if(!attach)
qCWarning(category) << "Specified winid to attach to is not a valid number";
} else if(p.isSet("embed")) {
/* KDialog originally used --embed for attaching the dialog box. However this is misleading and so we changed to --attach.
* For consistancy, we silently map --embed to --attach */
attach = true;
winid = p.value("embed").toInt(&attach, 0); //C style parsing. If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.
if(!attach)
qCWarning(category) << "Specified winid to attach to is not a valid number";
}
QList<QByteArray> env;
QByteArray options;
env << ( "DESKTOP_STARTUP_ID=" + KStartupInfo::startupId());
// TODO: Maybe should port this to XDG_*, somehow?
// if (pw->pw_uid)
// {
// // Only propagate KDEHOME for non-root users,
// // root uses KDEROOTHOME
//
// // Translate the KDEHOME of this user to the new user.
// QString kdeHome = KGlobal::dirs()->relativeLocation("home", KGlobal::dirs()->localkdedir());
// if (kdeHome[0] != '/')
// kdeHome.prepend("~/");
// else
// kdeHome.clear(); // Use default
//
// env << ("KDEHOME="+ QFile::encodeName(kdeHome));
// }
KUser u;
env << (QByteArray) ("KDESU_USER=" + u.loginName().toLocal8Bit());
if (keep && !terminal && !just_started)
{
client.setPriority(priority);
client.setScheduler(scheduler);
int result = client.exec(command, user, options, env);
if (result == 0)
{
result = client.exitCode();
return result;
}
}
// Set core dump size to 0 because we will have
// root's password in memory.
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = 0;
if (setrlimit(RLIMIT_CORE, &rlim))
{
qCCritical(category) << "rlimit(): " << ERR;
p.showHelp(1);
}
// Read configuration
KConfigGroup config(KSharedConfig::openConfig(), "Passwords");
int timeout = config.readEntry("Timeout", defTimeout);
// Check if we need a password
SuProcess proc;
proc.setUser(auth_user);
int needpw = proc.checkNeedPassword();
if (needpw < 0)
{
QString err = i18n("Su returned with an error.\n");
KMessageBox::error(0L, err);
p.showHelp(1);
}
if (needpw == 0)
{
keep = 0;
qDebug() << "Don't need password!!\n";
}
// Start the dialog
QString password;
if (needpw)
{
#ifdef HAVE_X11
KStartupInfoId id;
id.initId();
KStartupInfoData data;
data.setSilent( KStartupInfoData::Yes );
KStartupInfo::sendChange( id, data );
#endif
KDEsuDialog dlg(user, auth_user, keep && !terminal, icon, withIgnoreButton);
if (prompt)
dlg.addCommentLine(i18n("Command:"), QFile::decodeName(command));
if (defKeep)
dlg.setKeepPassword(true);
if ((priority != 50) || (scheduler != SuProcess::SchedNormal))
{
QString prio;
if (scheduler == SuProcess::SchedRealtime)
prio += i18n("realtime: ");
prio += QString("%1/100").arg(priority);
if (prompt)
dlg.addCommentLine(i18n("Priority:"), prio);
}
//Attach dialog
#ifdef HAVE_X11
if(attach)
KWindowSystem::setMainWindow(&dlg, (WId)winid);
#endif
int ret = dlg.exec();
if (ret == KDEsuDialog::Rejected)
{
#ifdef HAVE_X11
KStartupInfo::sendFinish( id );
#endif
p.showHelp(1);
}
if (ret == KDEsuDialog::AsUser)
change_uid = false;
password = dlg.password();
keep = dlg.keepPassword();
#ifdef HAVE_X11
data.setSilent( KStartupInfoData::No );
KStartupInfo::sendChange( id, data );
#endif
}
// Some events may need to be handled (like a button animation)
qApp->processEvents();
// Run command
if (!change_uid)
{
int result = system(command);
result = WEXITSTATUS(result);
return result;
}
else if (keep && have_daemon)
{
client.setPass(password.toLocal8Bit(), timeout);
client.setPriority(priority);
client.setScheduler(scheduler);
int result = client.exec(command, user, options, env);
if (result == 0)
{
result = client.exitCode();
return result;
}
} else
{
SuProcess proc;
proc.setTerminal(terminal);
proc.setErase(true);
proc.setUser(user);
proc.setEnvironment(env);
proc.setPriority(priority);
proc.setScheduler(scheduler);
proc.setCommand(command);
int result = proc.exec(password.toLocal8Bit());
return result;
}
return -1;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-94'], 'message': 'Make sure people are not trying to sneak invisible characters on the kdesu label
i18n: Sorry for the new string
CCMAIL: [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: asmlinkage long sys_oabi_epoll_wait(int epfd,
struct oabi_epoll_event __user *events,
int maxevents, int timeout)
{
struct epoll_event *kbuf;
mm_segment_t fs;
long ret, err, i;
if (maxevents <= 0 || maxevents > (INT_MAX/sizeof(struct epoll_event)))
return -EINVAL;
kbuf = kmalloc(sizeof(*kbuf) * maxevents, GFP_KERNEL);
if (!kbuf)
return -ENOMEM;
fs = get_fs();
set_fs(KERNEL_DS);
ret = sys_epoll_wait(epfd, kbuf, maxevents, timeout);
set_fs(fs);
err = 0;
for (i = 0; i < ret; i++) {
__put_user_error(kbuf[i].events, &events->events, err);
__put_user_error(kbuf[i].data, &events->data, err);
events++;
}
kfree(kbuf);
return err ? -EFAULT : ret;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-264'], 'message': 'arm: oabi compat: add missing access checks
Add access checks to sys_oabi_epoll_wait() and sys_oabi_semtimedop().
This fixes CVE-2016-3857, a local privilege escalation under
CONFIG_OABI_COMPAT.
Cc: [email protected]
Reported-by: Chiachih Wu <[email protected]>
Reviewed-by: Kees Cook <[email protected]>
Reviewed-by: Nicolas Pitre <[email protected]>
Signed-off-by: Dave Weinstein <[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: void loadServerConfigFromString(char *config) {
char *err = NULL;
int linenum = 0, totlines, i;
int slaveof_linenum = 0;
sds *lines;
lines = sdssplitlen(config,strlen(config),"\n",1,&totlines);
for (i = 0; i < totlines; i++) {
sds *argv;
int argc;
linenum = i+1;
lines[i] = sdstrim(lines[i]," \t\r\n");
/* Skip comments and blank lines */
if (lines[i][0] == '#' || lines[i][0] == '\0') continue;
/* Split into arguments */
argv = sdssplitargs(lines[i],&argc);
if (argv == NULL) {
err = "Unbalanced quotes in configuration line";
goto loaderr;
}
/* Skip this line if the resulting command vector is empty. */
if (argc == 0) {
sdsfreesplitres(argv,argc);
continue;
}
sdstolower(argv[0]);
/* Execute config directives */
if (!strcasecmp(argv[0],"timeout") && argc == 2) {
server.maxidletime = atoi(argv[1]);
if (server.maxidletime < 0) {
err = "Invalid timeout value"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"tcp-keepalive") && argc == 2) {
server.tcpkeepalive = atoi(argv[1]);
if (server.tcpkeepalive < 0) {
err = "Invalid tcp-keepalive value"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"protected-mode") && argc == 2) {
if ((server.protected_mode = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"port") && argc == 2) {
server.port = atoi(argv[1]);
if (server.port < 0 || server.port > 65535) {
err = "Invalid port"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"tcp-backlog") && argc == 2) {
server.tcp_backlog = atoi(argv[1]);
if (server.tcp_backlog < 0) {
err = "Invalid backlog value"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"bind") && argc >= 2) {
int j, addresses = argc-1;
if (addresses > CONFIG_BINDADDR_MAX) {
err = "Too many bind addresses specified"; goto loaderr;
}
for (j = 0; j < addresses; j++)
server.bindaddr[j] = zstrdup(argv[j+1]);
server.bindaddr_count = addresses;
} else if (!strcasecmp(argv[0],"unixsocket") && argc == 2) {
server.unixsocket = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"unixsocketperm") && argc == 2) {
errno = 0;
server.unixsocketperm = (mode_t)strtol(argv[1], NULL, 8);
if (errno || server.unixsocketperm > 0777) {
err = "Invalid socket file permissions"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"save")) {
if (argc == 3) {
int seconds = atoi(argv[1]);
int changes = atoi(argv[2]);
if (seconds < 1 || changes < 0) {
err = "Invalid save parameters"; goto loaderr;
}
appendServerSaveParams(seconds,changes);
} else if (argc == 2 && !strcasecmp(argv[1],"")) {
resetServerSaveParams();
}
} else if (!strcasecmp(argv[0],"dir") && argc == 2) {
if (chdir(argv[1]) == -1) {
serverLog(LL_WARNING,"Can't chdir to '%s': %s",
argv[1], strerror(errno));
exit(1);
}
} else if (!strcasecmp(argv[0],"loglevel") && argc == 2) {
server.verbosity = configEnumGetValue(loglevel_enum,argv[1]);
if (server.verbosity == INT_MIN) {
err = "Invalid log level. "
"Must be one of debug, verbose, notice, warning";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"logfile") && argc == 2) {
FILE *logfp;
zfree(server.logfile);
server.logfile = zstrdup(argv[1]);
if (server.logfile[0] != '\0') {
/* Test if we are able to open the file. The server will not
* be able to abort just for this problem later... */
logfp = fopen(server.logfile,"a");
if (logfp == NULL) {
err = sdscatprintf(sdsempty(),
"Can't open the log file: %s", strerror(errno));
goto loaderr;
}
fclose(logfp);
}
} else if (!strcasecmp(argv[0],"syslog-enabled") && argc == 2) {
if ((server.syslog_enabled = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"syslog-ident") && argc == 2) {
if (server.syslog_ident) zfree(server.syslog_ident);
server.syslog_ident = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"syslog-facility") && argc == 2) {
server.syslog_facility =
configEnumGetValue(syslog_facility_enum,argv[1]);
if (server.syslog_facility == INT_MIN) {
err = "Invalid log facility. Must be one of USER or between LOCAL0-LOCAL7";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"databases") && argc == 2) {
server.dbnum = atoi(argv[1]);
if (server.dbnum < 1) {
err = "Invalid number of databases"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"include") && argc == 2) {
loadServerConfig(argv[1],NULL);
} else if (!strcasecmp(argv[0],"maxclients") && argc == 2) {
server.maxclients = atoi(argv[1]);
if (server.maxclients < 1) {
err = "Invalid max clients limit"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
server.maxmemory = memtoll(argv[1],NULL);
} else if (!strcasecmp(argv[0],"maxmemory-policy") && argc == 2) {
server.maxmemory_policy =
configEnumGetValue(maxmemory_policy_enum,argv[1]);
if (server.maxmemory_policy == INT_MIN) {
err = "Invalid maxmemory policy";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"maxmemory-samples") && argc == 2) {
server.maxmemory_samples = atoi(argv[1]);
if (server.maxmemory_samples <= 0) {
err = "maxmemory-samples must be 1 or greater";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"lfu-log-factor") && argc == 2) {
server.lfu_log_factor = atoi(argv[1]);
if (server.maxmemory_samples < 0) {
err = "lfu-log-factor must be 0 or greater";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"lfu-decay-time") && argc == 2) {
server.lfu_decay_time = atoi(argv[1]);
if (server.maxmemory_samples < 1) {
err = "lfu-decay-time must be 0 or greater";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"slaveof") && argc == 3) {
slaveof_linenum = linenum;
server.masterhost = sdsnew(argv[1]);
server.masterport = atoi(argv[2]);
server.repl_state = REPL_STATE_CONNECT;
} else if (!strcasecmp(argv[0],"repl-ping-slave-period") && argc == 2) {
server.repl_ping_slave_period = atoi(argv[1]);
if (server.repl_ping_slave_period <= 0) {
err = "repl-ping-slave-period must be 1 or greater";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"repl-timeout") && argc == 2) {
server.repl_timeout = atoi(argv[1]);
if (server.repl_timeout <= 0) {
err = "repl-timeout must be 1 or greater";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"repl-disable-tcp-nodelay") && argc==2) {
if ((server.repl_disable_tcp_nodelay = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"repl-diskless-sync") && argc==2) {
if ((server.repl_diskless_sync = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"repl-diskless-sync-delay") && argc==2) {
server.repl_diskless_sync_delay = atoi(argv[1]);
if (server.repl_diskless_sync_delay < 0) {
err = "repl-diskless-sync-delay can't be negative";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"repl-backlog-size") && argc == 2) {
long long size = memtoll(argv[1],NULL);
if (size <= 0) {
err = "repl-backlog-size must be 1 or greater.";
goto loaderr;
}
resizeReplicationBacklog(size);
} else if (!strcasecmp(argv[0],"repl-backlog-ttl") && argc == 2) {
server.repl_backlog_time_limit = atoi(argv[1]);
if (server.repl_backlog_time_limit < 0) {
err = "repl-backlog-ttl can't be negative ";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
zfree(server.masterauth);
server.masterauth = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"slave-serve-stale-data") && argc == 2) {
if ((server.repl_serve_stale_data = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"slave-read-only") && argc == 2) {
if ((server.repl_slave_ro = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) {
if ((server.rdb_compression = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"rdbchecksum") && argc == 2) {
if ((server.rdb_checksum = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) {
if ((server.activerehashing = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"lazyfree-lazy-eviction") && argc == 2) {
if ((server.lazyfree_lazy_eviction = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"lazyfree-lazy-expire") && argc == 2) {
if ((server.lazyfree_lazy_expire = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"lazyfree-lazy-server-del") && argc == 2){
if ((server.lazyfree_lazy_server_del = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"slave-lazy-flush") && argc == 2) {
if ((server.repl_slave_lazy_flush = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"daemonize") && argc == 2) {
if ((server.daemonize = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"hz") && argc == 2) {
server.hz = atoi(argv[1]);
if (server.hz < CONFIG_MIN_HZ) server.hz = CONFIG_MIN_HZ;
if (server.hz > CONFIG_MAX_HZ) server.hz = CONFIG_MAX_HZ;
} else if (!strcasecmp(argv[0],"appendonly") && argc == 2) {
int yes;
if ((yes = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
server.aof_state = yes ? AOF_ON : AOF_OFF;
} else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) {
if (!pathIsBaseName(argv[1])) {
err = "appendfilename can't be a path, just a filename";
goto loaderr;
}
zfree(server.aof_filename);
server.aof_filename = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"no-appendfsync-on-rewrite")
&& argc == 2) {
if ((server.aof_no_fsync_on_rewrite= yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) {
server.aof_fsync = configEnumGetValue(aof_fsync_enum,argv[1]);
if (server.aof_fsync == INT_MIN) {
err = "argument must be 'no', 'always' or 'everysec'";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"auto-aof-rewrite-percentage") &&
argc == 2)
{
server.aof_rewrite_perc = atoi(argv[1]);
if (server.aof_rewrite_perc < 0) {
err = "Invalid negative percentage for AOF auto rewrite";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"auto-aof-rewrite-min-size") &&
argc == 2)
{
server.aof_rewrite_min_size = memtoll(argv[1],NULL);
} else if (!strcasecmp(argv[0],"aof-rewrite-incremental-fsync") &&
argc == 2)
{
if ((server.aof_rewrite_incremental_fsync =
yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"aof-load-truncated") && argc == 2) {
if ((server.aof_load_truncated = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"aof-use-rdb-preamble") && argc == 2) {
if ((server.aof_use_rdb_preamble = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
if (strlen(argv[1]) > CONFIG_AUTHPASS_MAX_LEN) {
err = "Password is longer than CONFIG_AUTHPASS_MAX_LEN";
goto loaderr;
}
server.requirepass = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"pidfile") && argc == 2) {
zfree(server.pidfile);
server.pidfile = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) {
if (!pathIsBaseName(argv[1])) {
err = "dbfilename can't be a path, just a filename";
goto loaderr;
}
zfree(server.rdb_filename);
server.rdb_filename = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"hash-max-ziplist-entries") && argc == 2) {
server.hash_max_ziplist_entries = memtoll(argv[1], NULL);
} else if (!strcasecmp(argv[0],"hash-max-ziplist-value") && argc == 2) {
server.hash_max_ziplist_value = memtoll(argv[1], NULL);
} else if (!strcasecmp(argv[0],"list-max-ziplist-entries") && argc == 2){
/* DEAD OPTION */
} else if (!strcasecmp(argv[0],"list-max-ziplist-value") && argc == 2) {
/* DEAD OPTION */
} else if (!strcasecmp(argv[0],"list-max-ziplist-size") && argc == 2) {
server.list_max_ziplist_size = atoi(argv[1]);
} else if (!strcasecmp(argv[0],"list-compress-depth") && argc == 2) {
server.list_compress_depth = atoi(argv[1]);
} else if (!strcasecmp(argv[0],"set-max-intset-entries") && argc == 2) {
server.set_max_intset_entries = memtoll(argv[1], NULL);
} else if (!strcasecmp(argv[0],"zset-max-ziplist-entries") && argc == 2) {
server.zset_max_ziplist_entries = memtoll(argv[1], NULL);
} else if (!strcasecmp(argv[0],"zset-max-ziplist-value") && argc == 2) {
server.zset_max_ziplist_value = memtoll(argv[1], NULL);
} else if (!strcasecmp(argv[0],"hll-sparse-max-bytes") && argc == 2) {
server.hll_sparse_max_bytes = memtoll(argv[1], NULL);
} else if (!strcasecmp(argv[0],"rename-command") && argc == 3) {
struct redisCommand *cmd = lookupCommand(argv[1]);
int retval;
if (!cmd) {
err = "No such command in rename-command";
goto loaderr;
}
/* If the target command name is the empty string we just
* remove it from the command table. */
retval = dictDelete(server.commands, argv[1]);
serverAssert(retval == DICT_OK);
/* Otherwise we re-add the command under a different name. */
if (sdslen(argv[2]) != 0) {
sds copy = sdsdup(argv[2]);
retval = dictAdd(server.commands, copy, cmd);
if (retval != DICT_OK) {
sdsfree(copy);
err = "Target command name already exists"; goto loaderr;
}
}
} else if (!strcasecmp(argv[0],"cluster-enabled") && argc == 2) {
if ((server.cluster_enabled = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"cluster-config-file") && argc == 2) {
zfree(server.cluster_configfile);
server.cluster_configfile = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"cluster-announce-ip") && argc == 2) {
zfree(server.cluster_announce_ip);
server.cluster_announce_ip = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"cluster-announce-port") && argc == 2) {
server.cluster_announce_port = atoi(argv[1]);
if (server.cluster_announce_port < 0 ||
server.cluster_announce_port > 65535)
{
err = "Invalid port"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"cluster-announce-bus-port") &&
argc == 2)
{
server.cluster_announce_bus_port = atoi(argv[1]);
if (server.cluster_announce_bus_port < 0 ||
server.cluster_announce_bus_port > 65535)
{
err = "Invalid port"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"cluster-require-full-coverage") &&
argc == 2)
{
if ((server.cluster_require_full_coverage = yesnotoi(argv[1])) == -1)
{
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"cluster-node-timeout") && argc == 2) {
server.cluster_node_timeout = strtoll(argv[1],NULL,10);
if (server.cluster_node_timeout <= 0) {
err = "cluster node timeout must be 1 or greater"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"cluster-migration-barrier")
&& argc == 2)
{
server.cluster_migration_barrier = atoi(argv[1]);
if (server.cluster_migration_barrier < 0) {
err = "cluster migration barrier must zero or positive";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"cluster-slave-validity-factor")
&& argc == 2)
{
server.cluster_slave_validity_factor = atoi(argv[1]);
if (server.cluster_slave_validity_factor < 0) {
err = "cluster slave validity factor must be zero or positive";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"lua-time-limit") && argc == 2) {
server.lua_time_limit = strtoll(argv[1],NULL,10);
} else if (!strcasecmp(argv[0],"slowlog-log-slower-than") &&
argc == 2)
{
server.slowlog_log_slower_than = strtoll(argv[1],NULL,10);
} else if (!strcasecmp(argv[0],"latency-monitor-threshold") &&
argc == 2)
{
server.latency_monitor_threshold = strtoll(argv[1],NULL,10);
if (server.latency_monitor_threshold < 0) {
err = "The latency threshold can't be negative";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"slowlog-max-len") && argc == 2) {
server.slowlog_max_len = strtoll(argv[1],NULL,10);
} else if (!strcasecmp(argv[0],"client-output-buffer-limit") &&
argc == 5)
{
int class = getClientTypeByName(argv[1]);
unsigned long long hard, soft;
int soft_seconds;
if (class == -1) {
err = "Unrecognized client limit class";
goto loaderr;
}
hard = memtoll(argv[2],NULL);
soft = memtoll(argv[3],NULL);
soft_seconds = atoi(argv[4]);
if (soft_seconds < 0) {
err = "Negative number of seconds in soft limit is invalid";
goto loaderr;
}
server.client_obuf_limits[class].hard_limit_bytes = hard;
server.client_obuf_limits[class].soft_limit_bytes = soft;
server.client_obuf_limits[class].soft_limit_seconds = soft_seconds;
} else if (!strcasecmp(argv[0],"stop-writes-on-bgsave-error") &&
argc == 2) {
if ((server.stop_writes_on_bgsave_err = yesnotoi(argv[1])) == -1) {
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"slave-priority") && argc == 2) {
server.slave_priority = atoi(argv[1]);
} else if (!strcasecmp(argv[0],"slave-announce-ip") && argc == 2) {
zfree(server.slave_announce_ip);
server.slave_announce_ip = zstrdup(argv[1]);
} else if (!strcasecmp(argv[0],"slave-announce-port") && argc == 2) {
server.slave_announce_port = atoi(argv[1]);
if (server.slave_announce_port < 0 ||
server.slave_announce_port > 65535)
{
err = "Invalid port"; goto loaderr;
}
} else if (!strcasecmp(argv[0],"min-slaves-to-write") && argc == 2) {
server.repl_min_slaves_to_write = atoi(argv[1]);
if (server.repl_min_slaves_to_write < 0) {
err = "Invalid value for min-slaves-to-write."; goto loaderr;
}
} else if (!strcasecmp(argv[0],"min-slaves-max-lag") && argc == 2) {
server.repl_min_slaves_max_lag = atoi(argv[1]);
if (server.repl_min_slaves_max_lag < 0) {
err = "Invalid value for min-slaves-max-lag."; goto loaderr;
}
} else if (!strcasecmp(argv[0],"notify-keyspace-events") && argc == 2) {
int flags = keyspaceEventsStringToFlags(argv[1]);
if (flags == -1) {
err = "Invalid event class character. Use 'g$lshzxeA'.";
goto loaderr;
}
server.notify_keyspace_events = flags;
} else if (!strcasecmp(argv[0],"supervised") && argc == 2) {
server.supervised_mode =
configEnumGetValue(supervised_mode_enum,argv[1]);
if (server.supervised_mode == INT_MIN) {
err = "Invalid option for 'supervised'. "
"Allowed values: 'upstart', 'systemd', 'auto', or 'no'";
goto loaderr;
}
} else if (!strcasecmp(argv[0],"loadmodule") && argc >= 2) {
queueLoadModule(argv[1],&argv[2],argc-2);
} else if (!strcasecmp(argv[0],"sentinel")) {
/* argc == 1 is handled by main() as we need to enter the sentinel
* mode ASAP. */
if (argc != 1) {
if (!server.sentinel_mode) {
err = "sentinel directive while not in sentinel mode";
goto loaderr;
}
err = sentinelHandleConfiguration(argv+1,argc-1);
if (err) goto loaderr;
}
} else {
err = "Bad directive or wrong number of arguments"; goto loaderr;
}
sdsfreesplitres(argv,argc);
}
/* Sanity checks. */
if (server.cluster_enabled && server.masterhost) {
linenum = slaveof_linenum;
i = linenum-1;
err = "slaveof directive not allowed in cluster mode";
goto loaderr;
}
sdsfreesplitres(lines,totlines);
return;
loaderr:
fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n");
fprintf(stderr, "Reading the configuration file, at line %d\n", linenum);
fprintf(stderr, ">>> '%s'\n", lines[i]);
fprintf(stderr, "%s\n", err);
exit(1);
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security: CONFIG SET client-output-buffer-limit overflow fixed.
This commit fixes a vunlerability reported by Cory Duplantis
of Cisco Talos, see TALOS-2016-0206 for reference.
CONFIG SET client-output-buffer-limit accepts as client class "master"
which is actually only used to implement CLIENT KILL. The "master" class
has ID 3. What happens is that the global structure:
server.client_obuf_limits[class]
Is accessed with class = 3. However it is a 3 elements array, so writing
the 4th element means to write up to 24 bytes of memory *after* the end
of the array, since the structure is defined as:
typedef struct clientBufferLimitsConfig {
unsigned long long hard_limit_bytes;
unsigned long long soft_limit_bytes;
time_t soft_limit_seconds;
} clientBufferLimitsConfig;
EVALUATION OF IMPACT:
Checking what's past the boundaries of the array in the global
'server' structure, we find AOF state fields:
clientBufferLimitsConfig client_obuf_limits[CLIENT_TYPE_OBUF_COUNT];
/* AOF persistence */
int aof_state; /* AOF_(ON|OFF|WAIT_REWRITE) */
int aof_fsync; /* Kind of fsync() policy */
char *aof_filename; /* Name of the AOF file */
int aof_no_fsync_on_rewrite; /* Don't fsync if a rewrite is in prog. */
int aof_rewrite_perc; /* Rewrite AOF if % growth is > M and... */
off_t aof_rewrite_min_size; /* the AOF file is at least N bytes. */
off_t aof_rewrite_base_size; /* AOF size on latest startup or rewrite. */
off_t aof_current_size; /* AOF current size. */
Writing to most of these fields should be harmless and only cause problems in
Redis persistence that should not escalate to security problems.
However unfortunately writing to "aof_filename" could be potentially a
security issue depending on the access pattern.
Searching for "aof.filename" accesses in the source code returns many different
usages of the field, including using it as input for open(), logging to the
Redis log file or syslog, and calling the rename() syscall.
It looks possible that attacks could lead at least to informations
disclosure of the state and data inside Redis. However note that the
attacker must already have access to the server. But, worse than that,
it looks possible that being able to change the AOF filename can be used
to mount more powerful attacks: like overwriting random files with AOF
data (easily a potential security issue as demostrated here:
http://antirez.com/news/96), or even more subtle attacks where the
AOF filename is changed to a path were a malicious AOF file is loaded
in order to exploit other potential issues when the AOF parser is fed
with untrusted input (no known issue known currently).
The fix checks the places where the 'master' class is specifiedf in
order to access configuration data structures, and return an error in
this cases.
WHO IS AT RISK?
The "master" client class was introduced in Redis in Jul 28 2015.
Every Redis instance released past this date is not vulnerable
while all the releases after this date are. Notably:
Redis 3.0.x is NOT vunlerable.
Redis 3.2.x IS vulnerable.
Redis unstable is vulnerable.
In order for the instance to be at risk, at least one of the following
conditions must be true:
1. The attacker can access Redis remotely and is able to send
the CONFIG SET command (often banned in managed Redis instances).
2. The attacker is able to control the "redis.conf" file and
can wait or trigger a server restart.
The problem was fixed 26th September 2016 in all the releases affected.'</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: ossl_cipher_set_key(VALUE self, VALUE key)
{
EVP_CIPHER_CTX *ctx;
int key_len;
StringValue(key);
GetCipher(self, ctx);
key_len = EVP_CIPHER_CTX_key_length(ctx);
if (RSTRING_LEN(key) != key_len)
ossl_raise(rb_eArgError, "key must be %d bytes", key_len);
if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1)
ossl_raise(eCipherError, NULL);
return key;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-326', 'CWE-310', 'CWE-703'], 'message': 'cipher: don't set dummy encryption key in Cipher#initialize
Remove the encryption key initialization from Cipher#initialize. This
is effectively a revert of r32723 ("Avoid possible SEGV from AES
encryption/decryption", 2011-07-28).
r32723, which added the key initialization, was a workaround for
Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate()
before setting an encryption key caused segfault. It was not a problem
until OpenSSL implemented GCM mode - the encryption key could be
overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the
case for AES-GCM ciphers. Setting a key, an IV, a key, in this order
causes the IV to be reset to an all-zero IV.
The problem of Bug #2768 persists on the current versions of OpenSSL.
So, make Cipher#update raise an exception if a key is not yet set by the
user. Since encrypting or decrypting without key does not make any
sense, this should not break existing applications.
Users can still call Cipher#key= and Cipher#iv= multiple times with
their own responsibility.
Reference: https://bugs.ruby-lang.org/issues/2768
Reference: https://bugs.ruby-lang.org/issues/8221
Reference: https://github.com/ruby/openssl/issues/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: ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self)
{
EVP_CIPHER_CTX *ctx;
const EVP_MD *digest;
VALUE vpass, vsalt, viter, vdigest;
unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], *salt = NULL;
int iter;
rb_scan_args(argc, argv, "13", &vpass, &vsalt, &viter, &vdigest);
StringValue(vpass);
if(!NIL_P(vsalt)){
StringValue(vsalt);
if(RSTRING_LEN(vsalt) != PKCS5_SALT_LEN)
ossl_raise(eCipherError, "salt must be an 8-octet string");
salt = (unsigned char *)RSTRING_PTR(vsalt);
}
iter = NIL_P(viter) ? 2048 : NUM2INT(viter);
digest = NIL_P(vdigest) ? EVP_md5() : GetDigestPtr(vdigest);
GetCipher(self, ctx);
EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt,
(unsigned char *)RSTRING_PTR(vpass), RSTRING_LENINT(vpass), iter, key, iv);
if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1)
ossl_raise(eCipherError, NULL);
OPENSSL_cleanse(key, sizeof key);
OPENSSL_cleanse(iv, sizeof iv);
return Qnil;
} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx"
[/INST] 'cwe': ['CWE-326', 'CWE-310', 'CWE-703'], 'message': 'cipher: don't set dummy encryption key in Cipher#initialize
Remove the encryption key initialization from Cipher#initialize. This
is effectively a revert of r32723 ("Avoid possible SEGV from AES
encryption/decryption", 2011-07-28).
r32723, which added the key initialization, was a workaround for
Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate()
before setting an encryption key caused segfault. It was not a problem
until OpenSSL implemented GCM mode - the encryption key could be
overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the
case for AES-GCM ciphers. Setting a key, an IV, a key, in this order
causes the IV to be reset to an all-zero IV.
The problem of Bug #2768 persists on the current versions of OpenSSL.
So, make Cipher#update raise an exception if a key is not yet set by the
user. Since encrypting or decrypting without key does not make any
sense, this should not break existing applications.
Users can still call Cipher#key= and Cipher#iv= multiple times with
their own responsibility.
Reference: https://bugs.ruby-lang.org/issues/2768
Reference: https://bugs.ruby-lang.org/issues/8221
Reference: https://github.com/ruby/openssl/issues/49'</s> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.